ToolQRCode.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 10/24/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from PyQt5.QtCore import Qt
  9. from FlatCAMTool import FlatCAMTool
  10. from flatcamGUI.GUIElements import RadioSet, FCTextArea, FCSpinner, FCEntry, FCCheckBox
  11. from flatcamParsers.ParseSVG import *
  12. from shapely.geometry.base import *
  13. from shapely.ops import unary_union
  14. from shapely.affinity import translate
  15. from shapely.geometry import box
  16. from io import StringIO, BytesIO
  17. from collections import Iterable
  18. import logging
  19. from copy import deepcopy
  20. import qrcode
  21. import qrcode.image.svg
  22. import qrcode.image.pil
  23. from lxml import etree as ET
  24. import gettext
  25. import FlatCAMTranslation as fcTranslate
  26. import builtins
  27. fcTranslate.apply_language('strings')
  28. if '_' not in builtins.__dict__:
  29. _ = gettext.gettext
  30. log = logging.getLogger('base')
  31. class QRCode(FlatCAMTool):
  32. toolName = _("QRCode Tool")
  33. def __init__(self, app):
  34. FlatCAMTool.__init__(self, app)
  35. self.app = app
  36. self.canvas = self.app.plotcanvas
  37. self.decimals = 4
  38. self.units = ''
  39. # ## Title
  40. title_label = QtWidgets.QLabel("%s" % self.toolName)
  41. title_label.setStyleSheet("""
  42. QLabel
  43. {
  44. font-size: 16px;
  45. font-weight: bold;
  46. }
  47. """)
  48. self.layout.addWidget(title_label)
  49. self.layout.addWidget(QtWidgets.QLabel(''))
  50. # ## Grid Layout
  51. i_grid_lay = QtWidgets.QGridLayout()
  52. self.layout.addLayout(i_grid_lay)
  53. i_grid_lay.setColumnStretch(0, 0)
  54. i_grid_lay.setColumnStretch(1, 1)
  55. self.grb_object_combo = QtWidgets.QComboBox()
  56. self.grb_object_combo.setModel(self.app.collection)
  57. self.grb_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  58. self.grb_object_combo.setCurrentIndex(1)
  59. self.grbobj_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  60. self.grbobj_label.setToolTip(
  61. _("Gerber Object to which the QRCode will be added.")
  62. )
  63. i_grid_lay.addWidget(self.grbobj_label, 0, 0)
  64. i_grid_lay.addWidget(self.grb_object_combo, 0, 1, 1, 2)
  65. i_grid_lay.addWidget(QtWidgets.QLabel(''), 1, 0)
  66. # ## Grid Layout
  67. grid_lay = QtWidgets.QGridLayout()
  68. self.layout.addLayout(grid_lay)
  69. grid_lay.setColumnStretch(0, 0)
  70. grid_lay.setColumnStretch(1, 1)
  71. self.qrcode_label = QtWidgets.QLabel('<b>%s</b>' % _('QRCode Parameters'))
  72. self.qrcode_label.setToolTip(
  73. _("The parameters used to shape the QRCode.")
  74. )
  75. grid_lay.addWidget(self.qrcode_label, 0, 0, 1, 2)
  76. # VERSION #
  77. self.version_label = QtWidgets.QLabel('%s:' % _("Version"))
  78. self.version_label.setToolTip(
  79. _("QRCode version can have values from 1 (21x21 boxes)\n"
  80. "to 40 (177x177 boxes).")
  81. )
  82. self.version_entry = FCSpinner()
  83. self.version_entry.set_range(1, 40)
  84. self.version_entry.setWrapping(True)
  85. grid_lay.addWidget(self.version_label, 1, 0)
  86. grid_lay.addWidget(self.version_entry, 1, 1)
  87. # ERROR CORRECTION #
  88. self.error_label = QtWidgets.QLabel('%s:' % _("Error correction"))
  89. self.error_label.setToolTip(
  90. _("Parameter that controls the error correction used for the QR Code.\n"
  91. "L = maximum 7% errors can be corrected\n"
  92. "M = maximum 15% errors can be corrected\n"
  93. "Q = maximum 25% errors can be corrected\n"
  94. "H = maximum 30% errors can be corrected.")
  95. )
  96. self.error_radio = RadioSet([{'label': 'L', 'value': 'L'},
  97. {'label': 'M', 'value': 'M'},
  98. {'label': 'Q', 'value': 'Q'},
  99. {'label': 'H', 'value': 'H'}])
  100. self.error_radio.setToolTip(
  101. _("Parameter that controls the error correction used for the QR Code.\n"
  102. "L = maximum 7% errors can be corrected\n"
  103. "M = maximum 15% errors can be corrected\n"
  104. "Q = maximum 25% errors can be corrected\n"
  105. "H = maximum 30% errors can be corrected.")
  106. )
  107. grid_lay.addWidget(self.error_label, 2, 0)
  108. grid_lay.addWidget(self.error_radio, 2, 1)
  109. # BOX SIZE #
  110. self.bsize_label = QtWidgets.QLabel('%s:' % _("Box Size"))
  111. self.bsize_label.setToolTip(
  112. _("Box size control the overall size of the QRcode\n"
  113. "by adjusting the size of each box in the code.")
  114. )
  115. self.bsize_entry = FCSpinner()
  116. self.bsize_entry.set_range(1, 9999)
  117. self.bsize_entry.setWrapping(True)
  118. grid_lay.addWidget(self.bsize_label, 3, 0)
  119. grid_lay.addWidget(self.bsize_entry, 3, 1)
  120. # BORDER SIZE #
  121. self.border_size_label = QtWidgets.QLabel('%s:' % _("Border Size"))
  122. self.border_size_label.setToolTip(
  123. _("Size of the QRCode border. How many boxes thick is the border.\n"
  124. "Default value is 4. The width of the clearance around the QRCode.")
  125. )
  126. self.border_size_entry = FCSpinner()
  127. self.border_size_entry.set_range(1, 9999)
  128. self.border_size_entry.setWrapping(True)
  129. self.border_size_entry.set_value(4)
  130. grid_lay.addWidget(self.border_size_label, 4, 0)
  131. grid_lay.addWidget(self.border_size_entry, 4, 1)
  132. # Text box
  133. self.text_label = QtWidgets.QLabel('%s:' % _("QRCode Data"))
  134. self.text_label.setToolTip(
  135. _("QRCode Data. Alphanumeric text to be encoded in the QRCode.")
  136. )
  137. self.text_data = FCTextArea()
  138. self.text_data.setPlaceholderText(
  139. _("Add here the text to be included in the QRCode...")
  140. )
  141. grid_lay.addWidget(self.text_label, 5, 0)
  142. grid_lay.addWidget(self.text_data, 6, 0, 1, 2)
  143. # POLARITY CHOICE #
  144. self.pol_label = QtWidgets.QLabel('%s:' % _("Polarity"))
  145. self.pol_label.setToolTip(
  146. _("Choose the polarity of the QRCode.\n"
  147. "It can be drawn in a negative way (squares are clear)\n"
  148. "or in a positive way (squares are opaque).")
  149. )
  150. self.pol_radio = RadioSet([{'label': _('Negative'), 'value': 'neg'},
  151. {'label': _('Positive'), 'value': 'pos'}])
  152. self.pol_radio.setToolTip(
  153. _("Choose the type of QRCode to be created.\n"
  154. "If added on a Silkscreen Gerber file the QRCode may\n"
  155. "be added as positive. If it is added to a Copper Gerber\n"
  156. "file then perhaps the QRCode can be added as negative.")
  157. )
  158. grid_lay.addWidget(self.pol_label, 7, 0)
  159. grid_lay.addWidget(self.pol_radio, 7, 1)
  160. # BOUNDING BOX TYPE #
  161. self.bb_label = QtWidgets.QLabel('%s:' % _("Bounding Box"))
  162. self.bb_label.setToolTip(
  163. _("The bounding box, meaning the empty space that surrounds\n"
  164. "the QRCode geometry, can have a rounded or a square shape.")
  165. )
  166. self.bb_radio = RadioSet([{'label': _('Rounded'), 'value': 'r'},
  167. {'label': _('Square'), 'value': 's'}])
  168. self.bb_radio.setToolTip(
  169. _("The bounding box, meaning the empty space that surrounds\n"
  170. "the QRCode geometry, can have a rounded or a square shape.")
  171. )
  172. grid_lay.addWidget(self.bb_label, 8, 0)
  173. grid_lay.addWidget(self.bb_radio, 8, 1)
  174. # Export QRCode
  175. self.export_cb = FCCheckBox(_("Export QRCode"))
  176. self.export_cb.setToolTip(
  177. _("Show a set of controls allowing to export the QRCode\n"
  178. "to a SVG file or an PNG file.")
  179. )
  180. grid_lay.addWidget(self.export_cb, 9, 0, 1, 2)
  181. # this way I can hide/show the frame
  182. self.export_frame = QtWidgets.QFrame()
  183. self.export_frame.setContentsMargins(0, 0, 0, 0)
  184. self.layout.addWidget(self.export_frame)
  185. self.export_lay = QtWidgets.QGridLayout()
  186. self.export_lay.setContentsMargins(0, 0, 0, 0)
  187. self.export_frame.setLayout(self.export_lay)
  188. self.export_lay.setColumnStretch(0, 0)
  189. self.export_lay.setColumnStretch(1, 1)
  190. # default is hidden
  191. self.export_frame.hide()
  192. # FILL COLOR #
  193. self.fill_color_label = QtWidgets.QLabel('%s:' % _('Fill Color'))
  194. self.fill_color_label.setToolTip(
  195. _("Set the QRCode fill color (squares color).")
  196. )
  197. self.fill_color_entry = FCEntry()
  198. self.fill_color_button = QtWidgets.QPushButton()
  199. self.fill_color_button.setFixedSize(15, 15)
  200. fill_lay_child = QtWidgets.QHBoxLayout()
  201. fill_lay_child.setContentsMargins(0, 0, 0, 0)
  202. fill_lay_child.addWidget(self.fill_color_entry)
  203. fill_lay_child.addWidget(self.fill_color_button, alignment=Qt.AlignRight)
  204. fill_lay_child.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  205. fill_color_widget = QtWidgets.QWidget()
  206. fill_color_widget.setLayout(fill_lay_child)
  207. self.export_lay.addWidget(self.fill_color_label, 0, 0)
  208. self.export_lay.addWidget(fill_color_widget, 0, 1)
  209. self.transparent_cb = FCCheckBox(_("Transparent back color"))
  210. self.export_lay.addWidget(self.transparent_cb, 1, 0, 1, 2)
  211. # BACK COLOR #
  212. self.back_color_label = QtWidgets.QLabel('%s:' % _('Back Color'))
  213. self.back_color_label.setToolTip(
  214. _("Set the QRCode background color.")
  215. )
  216. self.back_color_entry = FCEntry()
  217. self.back_color_button = QtWidgets.QPushButton()
  218. self.back_color_button.setFixedSize(15, 15)
  219. back_lay_child = QtWidgets.QHBoxLayout()
  220. back_lay_child.setContentsMargins(0, 0, 0, 0)
  221. back_lay_child.addWidget(self.back_color_entry)
  222. back_lay_child.addWidget(self.back_color_button, alignment=Qt.AlignRight)
  223. back_lay_child.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  224. back_color_widget = QtWidgets.QWidget()
  225. back_color_widget.setLayout(back_lay_child)
  226. self.export_lay.addWidget(self.back_color_label, 2, 0)
  227. self.export_lay.addWidget(back_color_widget, 2, 1)
  228. # ## Export QRCode as SVG image
  229. self.export_svg_button = QtWidgets.QPushButton(_("Export QRCode SVG"))
  230. self.export_svg_button.setToolTip(
  231. _("Export a SVG file with the QRCode content.")
  232. )
  233. self.export_lay.addWidget(self.export_svg_button, 3, 0, 1, 2)
  234. # ## Export QRCode as PNG image
  235. self.export_png_button = QtWidgets.QPushButton(_("Export QRCode PNG"))
  236. self.export_png_button.setToolTip(
  237. _("Export a PNG image file with the QRCode content.")
  238. )
  239. self.export_lay.addWidget(self.export_png_button, 4, 0, 1, 2)
  240. # ## Insert QRCode
  241. self.qrcode_button = QtWidgets.QPushButton(_("Insert QRCode"))
  242. self.qrcode_button.setToolTip(
  243. _("Create the QRCode object.")
  244. )
  245. self.layout.addWidget(self.qrcode_button)
  246. self.layout.addStretch()
  247. self.grb_object = None
  248. self.box_poly = None
  249. self.proc = None
  250. self.origin = (0, 0)
  251. self.mm = None
  252. self.mr = None
  253. self.kr = None
  254. self.shapes = self.app.move_tool.sel_shapes
  255. self.qrcode_geometry = MultiPolygon()
  256. self.qrcode_utility_geometry = MultiPolygon()
  257. self.old_back_color = ''
  258. # Signals #
  259. self.qrcode_button.clicked.connect(self.execute)
  260. self.export_cb.stateChanged.connect(self.on_export_frame)
  261. self.export_png_button.clicked.connect(self.export_png_file)
  262. self.export_svg_button.clicked.connect(self.export_svg_file)
  263. self.fill_color_entry.editingFinished.connect(self.on_qrcode_fill_color_entry)
  264. self.fill_color_button.clicked.connect(self.on_qrcode_fill_color_button)
  265. self.back_color_entry.editingFinished.connect(self.on_qrcode_back_color_entry)
  266. self.back_color_button.clicked.connect(self.on_qrcode_back_color_button)
  267. self.transparent_cb.stateChanged.connect(self.on_transparent_back_color)
  268. def run(self, toggle=True):
  269. self.app.report_usage("QRCode()")
  270. if toggle:
  271. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  272. if self.app.ui.splitter.sizes()[0] == 0:
  273. self.app.ui.splitter.setSizes([1, 1])
  274. else:
  275. try:
  276. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  277. # if tab is populated with the tool but it does not have the focus, focus on it
  278. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  279. # focus on Tool Tab
  280. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  281. else:
  282. self.app.ui.splitter.setSizes([0, 1])
  283. except AttributeError:
  284. pass
  285. else:
  286. if self.app.ui.splitter.sizes()[0] == 0:
  287. self.app.ui.splitter.setSizes([1, 1])
  288. FlatCAMTool.run(self)
  289. self.set_tool_ui()
  290. self.app.ui.notebook.setTabText(2, _("QRCode Tool"))
  291. def install(self, icon=None, separator=None, **kwargs):
  292. FlatCAMTool.install(self, icon, separator, shortcut='ALT+Q', **kwargs)
  293. def set_tool_ui(self):
  294. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value()
  295. self.version_entry.set_value(int(self.app.defaults["tools_qrcode_version"]))
  296. self.error_radio.set_value(self.app.defaults["tools_qrcode_error"])
  297. self.bsize_entry.set_value(int(self.app.defaults["tools_qrcode_box_size"]))
  298. self.border_size_entry.set_value(int(self.app.defaults["tools_qrcode_border_size"]))
  299. self.pol_radio.set_value(self.app.defaults["tools_qrcode_polarity"])
  300. self.bb_radio.set_value(self.app.defaults["tools_qrcode_rounded"])
  301. self.text_data.set_value(self.app.defaults["tools_qrcode_qrdata"])
  302. self.fill_color_entry.set_value(self.app.defaults['tools_qrcode_fill_color'])
  303. self.fill_color_button.setStyleSheet("background-color:%s" %
  304. str(self.app.defaults['tools_qrcode_fill_color'])[:7])
  305. self.back_color_entry.set_value(self.app.defaults['tools_qrcode_back_color'])
  306. self.back_color_button.setStyleSheet("background-color:%s" %
  307. str(self.app.defaults['tools_qrcode_back_color'])[:7])
  308. def on_export_frame(self, state):
  309. self.export_frame.setVisible(state)
  310. self.qrcode_button.setVisible(not state)
  311. def execute(self):
  312. text_data = self.text_data.get_value()
  313. if text_data == '':
  314. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  315. return 'fail'
  316. # get the Gerber object on which the QRCode will be inserted
  317. selection_index = self.grb_object_combo.currentIndex()
  318. model_index = self.app.collection.index(selection_index, 0, self.grb_object_combo.rootModelIndex())
  319. try:
  320. self.grb_object = model_index.internalPointer().obj
  321. except Exception as e:
  322. log.debug("QRCode.execute() --> %s" % str(e))
  323. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  324. return 'fail'
  325. # we can safely activate the mouse events
  326. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  327. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  328. self.kr = self.app.plotcanvas.graph_event_connect('key_release', self.on_key_release)
  329. self.proc = self.app.proc_container.new('%s...' % _("Generating QRCode geometry"))
  330. def job_thread_qr(app_obj):
  331. error_code = {
  332. 'L': qrcode.constants.ERROR_CORRECT_L,
  333. 'M': qrcode.constants.ERROR_CORRECT_M,
  334. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  335. 'H': qrcode.constants.ERROR_CORRECT_H
  336. }[self.error_radio.get_value()]
  337. qr = qrcode.QRCode(
  338. version=self.version_entry.get_value(),
  339. error_correction=error_code,
  340. box_size=self.bsize_entry.get_value(),
  341. border=self.border_size_entry.get_value(),
  342. image_factory=qrcode.image.svg.SvgFragmentImage
  343. )
  344. qr.add_data(text_data)
  345. qr.make()
  346. svg_file = BytesIO()
  347. img = qr.make_image()
  348. img.save(svg_file)
  349. svg_text = StringIO(svg_file.getvalue().decode('UTF-8'))
  350. svg_geometry = self.convert_svg_to_geo(svg_text, units=self.units)
  351. self.qrcode_geometry = deepcopy(svg_geometry)
  352. svg_geometry = unary_union(svg_geometry).buffer(0.0000001).buffer(-0.0000001)
  353. self.qrcode_utility_geometry = svg_geometry
  354. # make a bounding box of the QRCode geometry to help drawing the utility geometry in case it is too
  355. # complicated
  356. try:
  357. a, b, c, d = self.qrcode_utility_geometry.bounds
  358. self.box_poly = box(minx=a, miny=b, maxx=c, maxy=d)
  359. except Exception as ee:
  360. log.debug("QRCode.make() bounds error --> %s" % str(ee))
  361. app_obj.call_source = 'qrcode_tool'
  362. app_obj.inform.emit(_("Click on the Destination point ..."))
  363. self.app.worker_task.emit({'fcn': job_thread_qr, 'params': [self.app]})
  364. def make(self, pos):
  365. self.on_exit()
  366. # make sure that the source object solid geometry is an Iterable
  367. if not isinstance(self.grb_object.solid_geometry, Iterable):
  368. self.grb_object.solid_geometry = [self.grb_object.solid_geometry]
  369. # I use the utility geometry (self.qrcode_utility_geometry) because it is already buffered
  370. geo_list = self.grb_object.solid_geometry
  371. if isinstance(self.grb_object.solid_geometry, MultiPolygon):
  372. geo_list = list(self.grb_object.solid_geometry.geoms)
  373. # this is the bounding box of the QRCode geometry
  374. a, b, c, d = self.qrcode_utility_geometry.bounds
  375. buff_val = self.border_size_entry.get_value() * (self.bsize_entry.get_value() / 10)
  376. if self.bb_radio.get_value() == 'r':
  377. mask_geo = box(a, b, c, d).buffer(buff_val)
  378. else:
  379. mask_geo = box(a, b, c, d).buffer(buff_val, join_style=2)
  380. # update the solid geometry with the cutout (if it is the case)
  381. new_solid_geometry = list()
  382. offset_mask_geo = translate(mask_geo, xoff=pos[0], yoff=pos[1])
  383. for poly in geo_list:
  384. if poly.contains(offset_mask_geo):
  385. new_solid_geometry.append(poly.difference(offset_mask_geo))
  386. else:
  387. if poly not in new_solid_geometry:
  388. new_solid_geometry.append(poly)
  389. geo_list = deepcopy(list(new_solid_geometry))
  390. # Polarity
  391. if self.pol_radio.get_value() == 'pos':
  392. working_geo = self.qrcode_utility_geometry
  393. else:
  394. working_geo = mask_geo.difference(self.qrcode_utility_geometry)
  395. try:
  396. for geo in working_geo:
  397. geo_list.append(translate(geo, xoff=pos[0], yoff=pos[1]))
  398. except TypeError:
  399. geo_list.append(translate(working_geo, xoff=pos[0], yoff=pos[1]))
  400. self.grb_object.solid_geometry = deepcopy(geo_list)
  401. box_size = float(self.bsize_entry.get_value()) / 10.0
  402. sort_apid = list()
  403. new_apid = '10'
  404. if self.grb_object.apertures:
  405. for k, v in list(self.grb_object.apertures.items()):
  406. sort_apid.append(int(k))
  407. sorted_apertures = sorted(sort_apid)
  408. max_apid = max(sorted_apertures)
  409. if max_apid >= 10:
  410. new_apid = str(max_apid + 1)
  411. else:
  412. new_apid = '10'
  413. # don't know if the condition is required since I already made sure above that the new_apid is a new one
  414. if new_apid not in self.grb_object.apertures:
  415. self.grb_object.apertures[new_apid] = dict()
  416. self.grb_object.apertures[new_apid]['geometry'] = list()
  417. self.grb_object.apertures[new_apid]['type'] = 'R'
  418. # TODO: HACK
  419. # I've artificially added 1% to the height and width because otherwise after loading the
  420. # exported file, it will not be correctly reconstructed (it will be made from multiple shapes instead of
  421. # one shape which show that the buffering didn't worked well). It may be the MM to INCH conversion.
  422. self.grb_object.apertures[new_apid]['height'] = deepcopy(box_size * 1.01)
  423. self.grb_object.apertures[new_apid]['width'] = deepcopy(box_size * 1.01)
  424. self.grb_object.apertures[new_apid]['size'] = deepcopy(math.sqrt(box_size ** 2 + box_size ** 2))
  425. if '0' not in self.grb_object.apertures:
  426. self.grb_object.apertures['0'] = dict()
  427. self.grb_object.apertures['0']['geometry'] = list()
  428. self.grb_object.apertures['0']['type'] = 'REG'
  429. self.grb_object.apertures['0']['size'] = 0.0
  430. # in case that the QRCode geometry is dropped onto a copper region (found in the '0' aperture)
  431. # make sure that I place a cutout there
  432. zero_elem = dict()
  433. zero_elem['clear'] = offset_mask_geo
  434. self.grb_object.apertures['0']['geometry'].append(deepcopy(zero_elem))
  435. try:
  436. a, b, c, d = self.grb_object.bounds()
  437. self.grb_object.options['xmin'] = a
  438. self.grb_object.options['ymin'] = b
  439. self.grb_object.options['xmax'] = c
  440. self.grb_object.options['ymax'] = d
  441. except Exception as e:
  442. log.debug("QRCode.make() bounds error --> %s" % str(e))
  443. try:
  444. for geo in self.qrcode_geometry:
  445. geo_elem = dict()
  446. geo_elem['solid'] = translate(geo, xoff=pos[0], yoff=pos[1])
  447. geo_elem['follow'] = translate(geo.centroid, xoff=pos[0], yoff=pos[1])
  448. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  449. except TypeError:
  450. geo_elem = dict()
  451. geo_elem['solid'] = self.qrcode_geometry
  452. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  453. # update the source file with the new geometry:
  454. self.grb_object.source_file = self.app.export_gerber(obj_name=self.grb_object.options['name'], filename=None,
  455. local_use=self.grb_object, use_thread=False)
  456. self.replot(obj=self.grb_object)
  457. self.app.inform.emit('[success] %s' % _("QRCode Tool done."))
  458. def draw_utility_geo(self, pos):
  459. # face = '#0000FF' + str(hex(int(0.2 * 255)))[2:]
  460. outline = '#0000FFAF'
  461. offset_geo = list()
  462. # I use the len of self.qrcode_geometry instead of the utility one because the complexity of the polygons is
  463. # better seen in this (bit what if the sel.qrcode_geometry is just one geo element? len will fail ...
  464. if len(self.qrcode_geometry) <= self.app.defaults["tools_qrcode_sel_limit"]:
  465. try:
  466. for poly in self.qrcode_utility_geometry:
  467. offset_geo.append(translate(poly.exterior, xoff=pos[0], yoff=pos[1]))
  468. for geo_int in poly.interiors:
  469. offset_geo.append(translate(geo_int, xoff=pos[0], yoff=pos[1]))
  470. except TypeError:
  471. offset_geo.append(translate(self.qrcode_utility_geometry.exterior, xoff=pos[0], yoff=pos[1]))
  472. for geo_int in self.qrcode_utility_geometry.interiors:
  473. offset_geo.append(translate(geo_int, xoff=pos[0], yoff=pos[1]))
  474. else:
  475. offset_geo = [translate(self.box_poly, xoff=pos[0], yoff=pos[1])]
  476. for shape in offset_geo:
  477. self.shapes.add(shape, color=outline, update=True, layer=0, tolerance=None)
  478. if self.app.is_legacy is True:
  479. self.shapes.redraw()
  480. def delete_utility_geo(self):
  481. self.shapes.clear(update=True)
  482. self.shapes.redraw()
  483. def on_mouse_move(self, event):
  484. if self.app.is_legacy is False:
  485. event_pos = event.pos
  486. else:
  487. event_pos = (event.xdata, event.ydata)
  488. try:
  489. x = float(event_pos[0])
  490. y = float(event_pos[1])
  491. except TypeError:
  492. return
  493. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  494. # if GRID is active we need to get the snapped positions
  495. if self.app.grid_status() == True:
  496. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  497. else:
  498. pos = pos_canvas
  499. dx = pos[0] - self.origin[0]
  500. dy = pos[1] - self.origin[1]
  501. # delete the utility geometry
  502. self.delete_utility_geo()
  503. self.draw_utility_geo((dx, dy))
  504. def on_mouse_release(self, event):
  505. # mouse click will be accepted only if the left button is clicked
  506. # this is necessary because right mouse click and middle mouse click
  507. # are used for panning on the canvas
  508. if self.app.is_legacy is False:
  509. event_pos = event.pos
  510. else:
  511. event_pos = (event.xdata, event.ydata)
  512. if event.button == 1:
  513. pos_canvas = self.app.plotcanvas.translate_coords(event_pos)
  514. self.delete_utility_geo()
  515. # if GRID is active we need to get the snapped positions
  516. if self.app.grid_status() == True:
  517. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  518. else:
  519. pos = pos_canvas
  520. dx = pos[0] - self.origin[0]
  521. dy = pos[1] - self.origin[1]
  522. self.make(pos=(dx, dy))
  523. def on_key_release(self, event):
  524. pass
  525. def convert_svg_to_geo(self, filename, object_type=None, flip=True, units='MM'):
  526. """
  527. Convert shapes from an SVG file into a geometry list.
  528. :param filename: A String Stream file.
  529. :param object_type: parameter passed further along. What kind the object will receive the SVG geometry
  530. :param flip: Flip the vertically.
  531. :type flip: bool
  532. :param units: FlatCAM units
  533. :return: None
  534. """
  535. # Parse into list of shapely objects
  536. svg_tree = ET.parse(filename)
  537. svg_root = svg_tree.getroot()
  538. # Change origin to bottom left
  539. # h = float(svg_root.get('height'))
  540. # w = float(svg_root.get('width'))
  541. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  542. geos = getsvggeo(svg_root, object_type)
  543. if flip:
  544. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  545. # flatten the svg geometry for the case when the QRCode SVG is added into a Gerber object
  546. solid_geometry = list(self.flatten_list(geos))
  547. geos_text = getsvgtext(svg_root, object_type, units=units)
  548. if geos_text is not None:
  549. geos_text_f = []
  550. if flip:
  551. # Change origin to bottom left
  552. for i in geos_text:
  553. _, minimy, _, maximy = i.bounds
  554. h2 = (maximy - minimy) * 0.5
  555. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  556. if geos_text_f:
  557. solid_geometry += geos_text_f
  558. return solid_geometry
  559. def flatten_list(self, geo_list):
  560. for item in geo_list:
  561. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  562. yield from self.flatten_list(item)
  563. else:
  564. yield item
  565. def replot(self, obj):
  566. def worker_task():
  567. with self.app.proc_container.new('%s...' % _("Plotting")):
  568. obj.plot()
  569. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  570. def on_exit(self):
  571. if self.app.is_legacy is False:
  572. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  573. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  574. self.app.plotcanvas.graph_event_disconnect('key_release', self.on_key_release)
  575. else:
  576. self.app.plotcanvas.graph_event_disconnect(self.mm)
  577. self.app.plotcanvas.graph_event_disconnect(self.mr)
  578. self.app.plotcanvas.graph_event_disconnect(self.kr)
  579. # delete the utility geometry
  580. self.delete_utility_geo()
  581. self.app.call_source = 'app'
  582. def export_png_file(self):
  583. text_data = self.text_data.get_value()
  584. if text_data == '':
  585. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  586. return 'fail'
  587. def job_thread_qr_png(app_obj, fname):
  588. error_code = {
  589. 'L': qrcode.constants.ERROR_CORRECT_L,
  590. 'M': qrcode.constants.ERROR_CORRECT_M,
  591. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  592. 'H': qrcode.constants.ERROR_CORRECT_H
  593. }[self.error_radio.get_value()]
  594. qr = qrcode.QRCode(
  595. version=self.version_entry.get_value(),
  596. error_correction=error_code,
  597. box_size=self.bsize_entry.get_value(),
  598. border=self.border_size_entry.get_value(),
  599. image_factory=qrcode.image.pil.PilImage
  600. )
  601. qr.add_data(text_data)
  602. qr.make(fit=True)
  603. img = qr.make_image(fill_color=self.fill_color_entry.get_value(),
  604. back_color=self.back_color_entry.get_value())
  605. img.save(fname)
  606. app_obj.call_source = 'qrcode_tool'
  607. name = 'qr_code'
  608. _filter = "PNG File (*.png);;All Files (*.*)"
  609. try:
  610. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  611. caption=_("Export PNG"),
  612. directory=self.app.get_last_save_folder() + '/' + str(name) + '_png',
  613. filter=_filter)
  614. except TypeError:
  615. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG"), filter=_filter)
  616. filename = str(filename)
  617. if filename == "":
  618. self.app.inform.emit('[WARNING_NOTCL]%s' % _(" Export PNG cancelled."))
  619. return
  620. else:
  621. self.app.worker_task.emit({'fcn': job_thread_qr_png, 'params': [self.app, filename]})
  622. def export_svg_file(self):
  623. text_data = self.text_data.get_value()
  624. if text_data == '':
  625. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  626. return 'fail'
  627. def job_thread_qr_svg(app_obj, fname):
  628. error_code = {
  629. 'L': qrcode.constants.ERROR_CORRECT_L,
  630. 'M': qrcode.constants.ERROR_CORRECT_M,
  631. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  632. 'H': qrcode.constants.ERROR_CORRECT_H
  633. }[self.error_radio.get_value()]
  634. qr = qrcode.QRCode(
  635. version=self.version_entry.get_value(),
  636. error_correction=error_code,
  637. box_size=self.bsize_entry.get_value(),
  638. border=self.border_size_entry.get_value(),
  639. image_factory=qrcode.image.svg.SvgPathImage
  640. )
  641. qr.add_data(text_data)
  642. img = qr.make_image(fill_color=self.fill_color_entry.get_value(),
  643. back_color=self.back_color_entry.get_value())
  644. img.save(fname)
  645. app_obj.call_source = 'qrcode_tool'
  646. name = 'qr_code'
  647. _filter = "SVG File (*.svg);;All Files (*.*)"
  648. try:
  649. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  650. caption=_("Export SVG"),
  651. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  652. filter=_filter)
  653. except TypeError:
  654. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  655. filename = str(filename)
  656. if filename == "":
  657. self.app.inform.emit('[WARNING_NOTCL]%s' % _(" Export SVG cancelled."))
  658. return
  659. else:
  660. self.app.worker_task.emit({'fcn': job_thread_qr_svg, 'params': [self.app, filename]})
  661. def on_qrcode_fill_color_entry(self):
  662. color = self.fill_color_entry.get_value()
  663. self.fill_color_button.setStyleSheet("background-color:%s" % str(color))
  664. def on_qrcode_fill_color_button(self):
  665. current_color = QtGui.QColor(self.fill_color_entry.get_value())
  666. c_dialog = QtWidgets.QColorDialog()
  667. fill_color = c_dialog.getColor(initial=current_color)
  668. if fill_color.isValid() is False:
  669. return
  670. self.fill_color_button.setStyleSheet("background-color:%s" % str(fill_color.name()))
  671. new_val_sel = str(fill_color.name())
  672. self.fill_color_entry.set_value(new_val_sel)
  673. def on_qrcode_back_color_entry(self):
  674. color = self.back_color_entry.get_value()
  675. self.back_color_button.setStyleSheet("background-color:%s" % str(color))
  676. def on_qrcode_back_color_button(self):
  677. current_color = QtGui.QColor(self.back_color_entry.get_value())
  678. c_dialog = QtWidgets.QColorDialog()
  679. back_color = c_dialog.getColor(initial=current_color)
  680. if back_color.isValid() is False:
  681. return
  682. self.back_color_button.setStyleSheet("background-color:%s" % str(back_color.name()))
  683. new_val_sel = str(back_color.name())
  684. self.back_color_entry.set_value(new_val_sel)
  685. def on_transparent_back_color(self, state):
  686. if state:
  687. self.back_color_entry.setDisabled(True)
  688. self.back_color_button.setDisabled(True)
  689. self.old_back_color = self.back_color_entry.get_value()
  690. self.back_color_entry.set_value('transparent')
  691. else:
  692. self.back_color_entry.setDisabled(False)
  693. self.back_color_button.setDisabled(False)
  694. self.back_color_entry.set_value(self.old_back_color)