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, OptionalInputSection
  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. _("Contain the expected calibration points and the\n"
  74. "ones measured.")
  75. )
  76. grid_lay.addWidget(self.qrcode_label, 0, 0, 1, 2)
  77. # VERSION #
  78. self.version_label = QtWidgets.QLabel('%s:' % _("Version"))
  79. self.version_label.setToolTip(
  80. _("QRCode version can have values from 1 (21x21 boxes)\n"
  81. "to 40 (177x177 boxes).")
  82. )
  83. self.version_entry = FCSpinner()
  84. self.version_entry.set_range(1, 40)
  85. self.version_entry.setWrapping(True)
  86. grid_lay.addWidget(self.version_label, 1, 0)
  87. grid_lay.addWidget(self.version_entry, 1, 1)
  88. # ERROR CORRECTION #
  89. self.error_label = QtWidgets.QLabel('%s:' % _("Error correction"))
  90. self.error_label.setToolTip(
  91. _("Parameter that controls the error correction used for the QR Code.\n"
  92. "L = maximum 7% errors can be corrected\n"
  93. "M = maximum 15% errors can be corrected\n"
  94. "Q = maximum 25% errors can be corrected\n"
  95. "H = maximum 30% errors can be corrected.")
  96. )
  97. self.error_radio = RadioSet([{'label': 'L', 'value': 'L'},
  98. {'label': 'M', 'value': 'M'},
  99. {'label': 'Q', 'value': 'Q'},
  100. {'label': 'H', 'value': 'H'}])
  101. self.error_radio.setToolTip(
  102. _("Parameter that controls the error correction used for the QR Code.\n"
  103. "L = maximum 7% errors can be corrected\n"
  104. "M = maximum 15% errors can be corrected\n"
  105. "Q = maximum 25% errors can be corrected\n"
  106. "H = maximum 30% errors can be corrected.")
  107. )
  108. grid_lay.addWidget(self.error_label, 2, 0)
  109. grid_lay.addWidget(self.error_radio, 2, 1)
  110. # BOX SIZE #
  111. self.bsize_label = QtWidgets.QLabel('%s:' % _("Box Size"))
  112. self.bsize_label.setToolTip(
  113. _("Box size control the overall size of the QRcode\n"
  114. "by adjusting the size of each box in the code.")
  115. )
  116. self.bsize_entry = FCSpinner()
  117. self.bsize_entry.set_range(1, 9999)
  118. self.bsize_entry.setWrapping(True)
  119. grid_lay.addWidget(self.bsize_label, 3, 0)
  120. grid_lay.addWidget(self.bsize_entry, 3, 1)
  121. # BORDER SIZE #
  122. self.border_size_label = QtWidgets.QLabel('%s:' % _("Border Size"))
  123. self.border_size_label.setToolTip(
  124. _("Size of the QRCode border. How many boxes thick is the border.\n"
  125. "Default value is 4. The width of the clearance around the QRCode.")
  126. )
  127. self.border_size_entry = FCSpinner()
  128. self.border_size_entry.set_range(1, 9999)
  129. self.border_size_entry.setWrapping(True)
  130. self.border_size_entry.set_value(4)
  131. grid_lay.addWidget(self.border_size_label, 4, 0)
  132. grid_lay.addWidget(self.border_size_entry, 4, 1)
  133. # Text box
  134. self.text_label = QtWidgets.QLabel('%s:' % _("QRCode Data"))
  135. self.text_label.setToolTip(
  136. _("QRCode Data. Alphanumeric text to be encoded in the QRCode.")
  137. )
  138. self.text_data = FCTextArea()
  139. self.text_data.setPlaceholderText(
  140. _("Add here the text to be included in the QRCode...")
  141. )
  142. grid_lay.addWidget(self.text_label, 5, 0)
  143. grid_lay.addWidget(self.text_data, 6, 0, 1, 2)
  144. # POLARITY CHOICE #
  145. self.pol_label = QtWidgets.QLabel('%s:' % _("Polarity"))
  146. self.pol_label.setToolTip(
  147. _("Choose the polarity of the QRCode.\n"
  148. "It can be drawn in a negative way (squares are clear)\n"
  149. "or in a positive way (squares are opaque).")
  150. )
  151. self.pol_radio = RadioSet([{'label': _('Negative'), 'value': 'neg'},
  152. {'label': _('Positive'), 'value': 'pos'}])
  153. self.pol_radio.setToolTip(
  154. _("Choose the type of QRCode to be created.\n"
  155. "If added on a Silkscreen Gerber file the QRCode may\n"
  156. "be added as positive. If it is added to a Copper Gerber\n"
  157. "file then perhaps the QRCode can be added as negative.")
  158. )
  159. grid_lay.addWidget(self.pol_label, 7, 0)
  160. grid_lay.addWidget(self.pol_radio, 7, 1)
  161. # BOUNDING BOX TYPE #
  162. self.bb_label = QtWidgets.QLabel('%s:' % _("Bounding Box"))
  163. self.bb_label.setToolTip(
  164. _("The bounding box, meaning the empty space that surrounds\n"
  165. "the QRCode geometry, can have a rounded or a square shape.")
  166. )
  167. self.bb_radio = RadioSet([{'label': _('Rounded'), 'value': 'r'},
  168. {'label': _('Square'), 'value': 's'}])
  169. self.bb_radio.setToolTip(
  170. _("The bounding box, meaning the empty space that surrounds\n"
  171. "the QRCode geometry, can have a rounded or a square shape.")
  172. )
  173. grid_lay.addWidget(self.bb_label, 8, 0)
  174. grid_lay.addWidget(self.bb_radio, 8, 1)
  175. # Export QRCode
  176. self.export_cb = FCCheckBox(_("Export QRCode"))
  177. self.export_cb.setToolTip(
  178. _("Show a set of controls allowing to export the QRCode\n"
  179. "to a SVG file or an PNG file.")
  180. )
  181. grid_lay.addWidget(self.export_cb, 9, 0, 1, 2)
  182. # this way I can hide/show the frame
  183. self.export_frame = QtWidgets.QFrame()
  184. self.export_frame.setContentsMargins(0, 0, 0, 0)
  185. self.layout.addWidget(self.export_frame)
  186. self.export_lay = QtWidgets.QGridLayout()
  187. self.export_lay.setContentsMargins(0, 0, 0, 0)
  188. self.export_frame.setLayout(self.export_lay)
  189. self.export_lay.setColumnStretch(0, 0)
  190. self.export_lay.setColumnStretch(1, 1)
  191. # default is hidden
  192. self.export_frame.hide()
  193. # FILL COLOR #
  194. self.fill_color_label = QtWidgets.QLabel('%s:' % _('Fill Color'))
  195. self.fill_color_label.setToolTip(
  196. _("Set the QRCode fill color (squares color).")
  197. )
  198. self.fill_color_entry = FCEntry()
  199. self.fill_color_button = QtWidgets.QPushButton()
  200. self.fill_color_button.setFixedSize(15, 15)
  201. fill_lay_child = QtWidgets.QHBoxLayout()
  202. fill_lay_child.setContentsMargins(0, 0, 0, 0)
  203. fill_lay_child.addWidget(self.fill_color_entry)
  204. fill_lay_child.addWidget(self.fill_color_button, alignment=Qt.AlignRight)
  205. fill_lay_child.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  206. fill_color_widget = QtWidgets.QWidget()
  207. fill_color_widget.setLayout(fill_lay_child)
  208. self.export_lay.addWidget(self.fill_color_label, 0, 0)
  209. self.export_lay.addWidget(fill_color_widget, 0, 1)
  210. self.transparent_cb = FCCheckBox(_("Transparent back color"))
  211. self.export_lay.addWidget(self.transparent_cb, 1, 0, 1, 2)
  212. # BACK COLOR #
  213. self.back_color_label = QtWidgets.QLabel('%s:' % _('Back Color'))
  214. self.back_color_label.setToolTip(
  215. _("Set the QRCode background color.")
  216. )
  217. self.back_color_entry = FCEntry()
  218. self.back_color_button = QtWidgets.QPushButton()
  219. self.back_color_button.setFixedSize(15, 15)
  220. back_lay_child = QtWidgets.QHBoxLayout()
  221. back_lay_child.setContentsMargins(0, 0, 0, 0)
  222. back_lay_child.addWidget(self.back_color_entry)
  223. back_lay_child.addWidget(self.back_color_button, alignment=Qt.AlignRight)
  224. back_lay_child.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  225. back_color_widget = QtWidgets.QWidget()
  226. back_color_widget.setLayout(back_lay_child)
  227. self.export_lay.addWidget(self.back_color_label, 2, 0)
  228. self.export_lay.addWidget(back_color_widget, 2, 1)
  229. # ## Export QRCode as SVG image
  230. self.export_svg_button = QtWidgets.QPushButton(_("Export QRCode SVG"))
  231. self.export_svg_button.setToolTip(
  232. _("Export a SVG file with the QRCode content.")
  233. )
  234. self.export_lay.addWidget(self.export_svg_button, 3, 0, 1, 2)
  235. # ## Export QRCode as PNG image
  236. self.export_png_button = QtWidgets.QPushButton(_("Export QRCode PNG"))
  237. self.export_png_button.setToolTip(
  238. _("Export a PNG image file with the QRCode content.")
  239. )
  240. self.export_lay.addWidget(self.export_png_button, 4, 0, 1, 2)
  241. # ## Insert QRCode
  242. self.qrcode_button = QtWidgets.QPushButton(_("Insert QRCode"))
  243. self.qrcode_button.setToolTip(
  244. _("Create the QRCode object.")
  245. )
  246. self.layout.addWidget(self.qrcode_button)
  247. self.layout.addStretch()
  248. self.grb_object = None
  249. self.box_poly = None
  250. self.proc = None
  251. self.origin = (0, 0)
  252. self.mm = None
  253. self.mr = None
  254. self.kr = None
  255. self.shapes = self.app.move_tool.sel_shapes
  256. self.qrcode_geometry = MultiPolygon()
  257. self.qrcode_utility_geometry = MultiPolygon()
  258. self.old_back_color = ''
  259. # Signals #
  260. self.qrcode_button.clicked.connect(self.execute)
  261. self.export_cb.stateChanged.connect(self.on_export_frame)
  262. self.export_png_button.clicked.connect(self.export_png_file)
  263. self.export_svg_button.clicked.connect(self.export_svg_file)
  264. self.fill_color_entry.editingFinished.connect(self.on_qrcode_fill_color_entry)
  265. self.fill_color_button.clicked.connect(self.on_qrcode_fill_color_button)
  266. self.back_color_entry.editingFinished.connect(self.on_qrcode_back_color_entry)
  267. self.back_color_button.clicked.connect(self.on_qrcode_back_color_button)
  268. self.transparent_cb.stateChanged.connect(self.on_transparent_back_color)
  269. def run(self, toggle=True):
  270. self.app.report_usage("QRCode()")
  271. if toggle:
  272. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  273. if self.app.ui.splitter.sizes()[0] == 0:
  274. self.app.ui.splitter.setSizes([1, 1])
  275. else:
  276. try:
  277. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  278. # if tab is populated with the tool but it does not have the focus, focus on it
  279. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  280. # focus on Tool Tab
  281. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  282. else:
  283. self.app.ui.splitter.setSizes([0, 1])
  284. except AttributeError:
  285. pass
  286. else:
  287. if self.app.ui.splitter.sizes()[0] == 0:
  288. self.app.ui.splitter.setSizes([1, 1])
  289. FlatCAMTool.run(self)
  290. self.set_tool_ui()
  291. self.app.ui.notebook.setTabText(2, _("QRCode Tool"))
  292. def install(self, icon=None, separator=None, **kwargs):
  293. FlatCAMTool.install(self, icon, separator, shortcut='ALT+Q', **kwargs)
  294. def set_tool_ui(self):
  295. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value()
  296. self.version_entry.set_value(int(self.app.defaults["tools_qrcode_version"]))
  297. self.error_radio.set_value(self.app.defaults["tools_qrcode_error"])
  298. self.bsize_entry.set_value(int(self.app.defaults["tools_qrcode_box_size"]))
  299. self.border_size_entry.set_value(int(self.app.defaults["tools_qrcode_border_size"]))
  300. self.pol_radio.set_value(self.app.defaults["tools_qrcode_polarity"])
  301. self.bb_radio.set_value(self.app.defaults["tools_qrcode_rounded"])
  302. self.text_data.set_value(self.app.defaults["tools_qrcode_qrdata"])
  303. self.fill_color_entry.set_value(self.app.defaults['tools_qrcode_fill_color'])
  304. self.fill_color_button.setStyleSheet("background-color:%s" %
  305. str(self.app.defaults['tools_qrcode_fill_color'])[:7])
  306. self.back_color_entry.set_value(self.app.defaults['tools_qrcode_back_color'])
  307. self.back_color_button.setStyleSheet("background-color:%s" %
  308. str(self.app.defaults['tools_qrcode_back_color'])[:7])
  309. def on_export_frame(self, state):
  310. self.export_frame.setVisible(state)
  311. self.qrcode_button.setVisible(not state)
  312. def execute(self):
  313. text_data = self.text_data.get_value()
  314. if text_data == '':
  315. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  316. return 'fail'
  317. # get the Gerber object on which the QRCode will be inserted
  318. selection_index = self.grb_object_combo.currentIndex()
  319. model_index = self.app.collection.index(selection_index, 0, self.grb_object_combo.rootModelIndex())
  320. try:
  321. self.grb_object = model_index.internalPointer().obj
  322. except Exception as e:
  323. log.debug("QRCode.execute() --> %s" % str(e))
  324. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  325. return 'fail'
  326. # we can safely activate the mouse events
  327. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  328. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  329. self.kr = self.app.plotcanvas.graph_event_connect('key_release', self.on_key_release)
  330. self.proc = self.app.proc_container.new('%s...' % _("Generating QRCode geometry"))
  331. def job_thread_qr(app_obj):
  332. error_code = {
  333. 'L': qrcode.constants.ERROR_CORRECT_L,
  334. 'M': qrcode.constants.ERROR_CORRECT_M,
  335. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  336. 'H': qrcode.constants.ERROR_CORRECT_H
  337. }[self.error_radio.get_value()]
  338. qr = qrcode.QRCode(
  339. version=self.version_entry.get_value(),
  340. error_correction=error_code,
  341. box_size=self.bsize_entry.get_value(),
  342. border=self.border_size_entry.get_value(),
  343. image_factory=qrcode.image.svg.SvgFragmentImage
  344. )
  345. qr.add_data(text_data)
  346. qr.make()
  347. svg_file = BytesIO()
  348. img = qr.make_image()
  349. img.save(svg_file)
  350. svg_text = StringIO(svg_file.getvalue().decode('UTF-8'))
  351. svg_geometry = self.convert_svg_to_geo(svg_text, units=self.units)
  352. self.qrcode_geometry = deepcopy(svg_geometry)
  353. svg_geometry = unary_union(svg_geometry).buffer(0.0000001).buffer(-0.0000001)
  354. self.qrcode_utility_geometry = svg_geometry
  355. # make a bounding box of the QRCode geometry to help drawing the utility geometry in case it is too
  356. # complicated
  357. try:
  358. a, b, c, d = self.qrcode_utility_geometry.bounds
  359. self.box_poly = box(minx=a, miny=b, maxx=c, maxy=d)
  360. except Exception as ee:
  361. log.debug("QRCode.make() bounds error --> %s" % str(ee))
  362. app_obj.call_source = 'qrcode_tool'
  363. app_obj.inform.emit(_("Click on the Destination point ..."))
  364. self.app.worker_task.emit({'fcn': job_thread_qr, 'params': [self.app]})
  365. def make(self, pos):
  366. self.on_exit()
  367. # add the svg geometry to the selected Gerber object solid_geometry and in obj.apertures, apid = 0
  368. if not isinstance(self.grb_object.solid_geometry, Iterable):
  369. self.grb_object.solid_geometry = list(self.grb_object.solid_geometry)
  370. # I use the utility geometry (self.qrcode_utility_geometry) because it is already buffered
  371. geo_list = self.grb_object.solid_geometry
  372. if isinstance(self.grb_object.solid_geometry, MultiPolygon):
  373. geo_list = list(self.grb_object.solid_geometry.geoms)
  374. # this is the bounding box of the QRCode geometry
  375. a, b, c, d = self.qrcode_utility_geometry.bounds
  376. buff_val = self.border_size_entry.get_value() * (self.bsize_entry.get_value() / 10)
  377. if self.bb_radio.get_value() == 'r':
  378. mask_geo = box(a, b, c, d).buffer(buff_val)
  379. else:
  380. mask_geo = box(a, b, c, d).buffer(buff_val, join_style=2)
  381. # update the solid geometry with the cutout (if it is the case)
  382. new_solid_geometry = list()
  383. offset_mask_geo = translate(mask_geo, xoff=pos[0], yoff=pos[1])
  384. for poly in geo_list:
  385. if poly.contains(offset_mask_geo):
  386. new_solid_geometry.append(poly.difference(offset_mask_geo))
  387. else:
  388. if poly not in new_solid_geometry:
  389. new_solid_geometry.append(poly)
  390. geo_list = deepcopy(list(new_solid_geometry))
  391. # Polarity
  392. if self.pol_radio.get_value() == 'pos':
  393. working_geo = self.qrcode_utility_geometry
  394. else:
  395. working_geo = mask_geo.difference(self.qrcode_utility_geometry)
  396. try:
  397. for geo in working_geo:
  398. geo_list.append(translate(geo, xoff=pos[0], yoff=pos[1]))
  399. except TypeError:
  400. geo_list.append(translate(working_geo, xoff=pos[0], yoff=pos[1]))
  401. self.grb_object.solid_geometry = deepcopy(geo_list)
  402. box_size = float(self.bsize_entry.get_value()) / 10.0
  403. sort_apid = list()
  404. new_apid = '10'
  405. if self.grb_object.apertures:
  406. for k, v in list(self.grb_object.apertures.items()):
  407. sort_apid.append(int(k))
  408. sorted_apertures = sorted(sort_apid)
  409. max_apid = max(sorted_apertures)
  410. if max_apid >= 10:
  411. new_apid = str(max_apid + 1)
  412. else:
  413. new_apid = '10'
  414. # don't know if the condition is required since I already made sure above that the new_apid is a new one
  415. if new_apid not in self.grb_object.apertures:
  416. self.grb_object.apertures[new_apid] = dict()
  417. self.grb_object.apertures[new_apid]['geometry'] = list()
  418. self.grb_object.apertures[new_apid]['type'] = 'R'
  419. # TODO: HACK
  420. # I've artificially added 1% to the height and width because otherwise after loading the
  421. # exported file, it will not be correctly reconstructed (it will be made from multiple shapes instead of
  422. # one shape which show that the buffering didn't worked well). It may be the MM to INCH conversion.
  423. self.grb_object.apertures[new_apid]['height'] = deepcopy(box_size * 1.01)
  424. self.grb_object.apertures[new_apid]['width'] = deepcopy(box_size * 1.01)
  425. self.grb_object.apertures[new_apid]['size'] = deepcopy(math.sqrt(box_size ** 2 + box_size ** 2))
  426. if '0' not in self.grb_object.apertures:
  427. self.grb_object.apertures['0'] = dict()
  428. self.grb_object.apertures['0']['geometry'] = list()
  429. self.grb_object.apertures['0']['type'] = 'REG'
  430. self.grb_object.apertures['0']['size'] = 0.0
  431. # in case that the QRCode geometry is dropped onto a copper region (found in the '0' aperture)
  432. # make sure that I place a cutout there
  433. zero_elem = dict()
  434. zero_elem['clear'] = offset_mask_geo
  435. self.grb_object.apertures['0']['geometry'].append(deepcopy(zero_elem))
  436. try:
  437. a, b, c, d = self.grb_object.bounds()
  438. self.grb_object.options['xmin'] = a
  439. self.grb_object.options['ymin'] = b
  440. self.grb_object.options['xmax'] = c
  441. self.grb_object.options['ymax'] = d
  442. except Exception as e:
  443. log.debug("QRCode.make() bounds error --> %s" % str(e))
  444. try:
  445. for geo in self.qrcode_geometry:
  446. geo_elem = dict()
  447. geo_elem['solid'] = translate(geo, xoff=pos[0], yoff=pos[1])
  448. geo_elem['follow'] = translate(geo.centroid, xoff=pos[0], yoff=pos[1])
  449. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  450. except TypeError:
  451. geo_elem = dict()
  452. geo_elem['solid'] = self.qrcode_geometry
  453. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  454. # update the source file with the new geometry:
  455. self.grb_object.source_file = self.app.export_gerber(obj_name=self.grb_object.options['name'], filename=None,
  456. local_use=self.grb_object, use_thread=False)
  457. self.replot(obj=self.grb_object)
  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
  464. if len(self.qrcode_geometry) <= 330:
  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)