ToolQRCode.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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 AppTools.AppTool import AppTool
  10. from AppGUI.GUIElements import RadioSet, FCTextArea, FCSpinner, FCEntry, FCCheckBox, FCComboBox, FCFileSaveDialog
  11. from AppParsers.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 AppTranslation 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(AppTool):
  32. toolName = _("QRCode Tool")
  33. def __init__(self, app):
  34. AppTool.__init__(self, app)
  35. self.app = app
  36. self.canvas = self.app.plotcanvas
  37. self.decimals = self.app.decimals
  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 = FCComboBox()
  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.is_last = True
  59. self.grb_object_combo.obj_type = "Gerber"
  60. self.grbobj_label = QtWidgets.QLabel("<b>%s:</b>" % _("Object"))
  61. self.grbobj_label.setToolTip(
  62. _("Gerber Object to which the QRCode will be added.")
  63. )
  64. i_grid_lay.addWidget(self.grbobj_label, 0, 0)
  65. i_grid_lay.addWidget(self.grb_object_combo, 0, 1, 1, 2)
  66. i_grid_lay.addWidget(QtWidgets.QLabel(''), 1, 0)
  67. # ## Grid Layout
  68. grid_lay = QtWidgets.QGridLayout()
  69. self.layout.addLayout(grid_lay)
  70. grid_lay.setColumnStretch(0, 0)
  71. grid_lay.setColumnStretch(1, 1)
  72. self.qrcode_label = QtWidgets.QLabel('<b>%s</b>' % _('QRCode Parameters'))
  73. self.qrcode_label.setToolTip(
  74. _("The parameters used to shape the QRCode.")
  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(callback=self.confirmation_message_int)
  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(callback=self.confirmation_message_int)
  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(callback=self.confirmation_message_int)
  128. self.border_size_entry.set_range(1, 9999)
  129. self.border_size_entry.setWrapping(True)
  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_svg_button.setStyleSheet("""
  234. QPushButton
  235. {
  236. font-weight: bold;
  237. }
  238. """)
  239. self.export_lay.addWidget(self.export_svg_button, 3, 0, 1, 2)
  240. # ## Export QRCode as PNG image
  241. self.export_png_button = QtWidgets.QPushButton(_("Export QRCode PNG"))
  242. self.export_png_button.setToolTip(
  243. _("Export a PNG image file with the QRCode content.")
  244. )
  245. self.export_png_button.setStyleSheet("""
  246. QPushButton
  247. {
  248. font-weight: bold;
  249. }
  250. """)
  251. self.export_lay.addWidget(self.export_png_button, 4, 0, 1, 2)
  252. # ## Insert QRCode
  253. self.qrcode_button = QtWidgets.QPushButton(_("Insert QRCode"))
  254. self.qrcode_button.setToolTip(
  255. _("Create the QRCode object.")
  256. )
  257. self.qrcode_button.setStyleSheet("""
  258. QPushButton
  259. {
  260. font-weight: bold;
  261. }
  262. """)
  263. self.layout.addWidget(self.qrcode_button)
  264. self.layout.addStretch()
  265. # ## Reset Tool
  266. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  267. self.reset_button.setToolTip(
  268. _("Will reset the tool parameters.")
  269. )
  270. self.reset_button.setStyleSheet("""
  271. QPushButton
  272. {
  273. font-weight: bold;
  274. }
  275. """)
  276. self.layout.addWidget(self.reset_button)
  277. self.grb_object = None
  278. self.box_poly = None
  279. self.proc = None
  280. self.origin = (0, 0)
  281. self.mm = None
  282. self.mr = None
  283. self.kr = None
  284. self.shapes = self.app.move_tool.sel_shapes
  285. self.qrcode_geometry = MultiPolygon()
  286. self.qrcode_utility_geometry = MultiPolygon()
  287. self.old_back_color = ''
  288. # Signals #
  289. self.qrcode_button.clicked.connect(self.execute)
  290. self.export_cb.stateChanged.connect(self.on_export_frame)
  291. self.export_png_button.clicked.connect(self.export_png_file)
  292. self.export_svg_button.clicked.connect(self.export_svg_file)
  293. self.fill_color_entry.editingFinished.connect(self.on_qrcode_fill_color_entry)
  294. self.fill_color_button.clicked.connect(self.on_qrcode_fill_color_button)
  295. self.back_color_entry.editingFinished.connect(self.on_qrcode_back_color_entry)
  296. self.back_color_button.clicked.connect(self.on_qrcode_back_color_button)
  297. self.transparent_cb.stateChanged.connect(self.on_transparent_back_color)
  298. self.reset_button.clicked.connect(self.set_tool_ui)
  299. def run(self, toggle=True):
  300. self.app.defaults.report_usage("QRCode()")
  301. if toggle:
  302. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  303. if self.app.ui.splitter.sizes()[0] == 0:
  304. self.app.ui.splitter.setSizes([1, 1])
  305. else:
  306. try:
  307. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  308. # if tab is populated with the tool but it does not have the focus, focus on it
  309. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  310. # focus on Tool Tab
  311. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  312. else:
  313. self.app.ui.splitter.setSizes([0, 1])
  314. except AttributeError:
  315. pass
  316. else:
  317. if self.app.ui.splitter.sizes()[0] == 0:
  318. self.app.ui.splitter.setSizes([1, 1])
  319. AppTool.run(self)
  320. self.set_tool_ui()
  321. self.app.ui.notebook.setTabText(2, _("QRCode Tool"))
  322. def install(self, icon=None, separator=None, **kwargs):
  323. AppTool.install(self, icon, separator, shortcut='Alt+Q', **kwargs)
  324. def set_tool_ui(self):
  325. self.units = self.app.defaults['units']
  326. self.border_size_entry.set_value(4)
  327. self.version_entry.set_value(int(self.app.defaults["tools_qrcode_version"]))
  328. self.error_radio.set_value(self.app.defaults["tools_qrcode_error"])
  329. self.bsize_entry.set_value(int(self.app.defaults["tools_qrcode_box_size"]))
  330. self.border_size_entry.set_value(int(self.app.defaults["tools_qrcode_border_size"]))
  331. self.pol_radio.set_value(self.app.defaults["tools_qrcode_polarity"])
  332. self.bb_radio.set_value(self.app.defaults["tools_qrcode_rounded"])
  333. self.text_data.set_value(self.app.defaults["tools_qrcode_qrdata"])
  334. self.fill_color_entry.set_value(self.app.defaults['tools_qrcode_fill_color'])
  335. self.fill_color_button.setStyleSheet("background-color:%s" %
  336. str(self.app.defaults['tools_qrcode_fill_color'])[:7])
  337. self.back_color_entry.set_value(self.app.defaults['tools_qrcode_back_color'])
  338. self.back_color_button.setStyleSheet("background-color:%s" %
  339. str(self.app.defaults['tools_qrcode_back_color'])[:7])
  340. def on_export_frame(self, state):
  341. self.export_frame.setVisible(state)
  342. self.qrcode_button.setVisible(not state)
  343. def execute(self):
  344. text_data = self.text_data.get_value()
  345. if text_data == '':
  346. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  347. return 'fail'
  348. # get the Gerber object on which the QRCode will be inserted
  349. selection_index = self.grb_object_combo.currentIndex()
  350. model_index = self.app.collection.index(selection_index, 0, self.grb_object_combo.rootModelIndex())
  351. try:
  352. self.grb_object = model_index.internalPointer().obj
  353. except Exception as e:
  354. log.debug("QRCode.execute() --> %s" % str(e))
  355. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  356. return 'fail'
  357. # we can safely activate the mouse events
  358. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  359. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  360. self.kr = self.app.plotcanvas.graph_event_connect('key_release', self.on_key_release)
  361. self.proc = self.app.proc_container.new('%s...' % _("Generating QRCode geometry"))
  362. def job_thread_qr(app_obj):
  363. error_code = {
  364. 'L': qrcode.constants.ERROR_CORRECT_L,
  365. 'M': qrcode.constants.ERROR_CORRECT_M,
  366. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  367. 'H': qrcode.constants.ERROR_CORRECT_H
  368. }[self.error_radio.get_value()]
  369. qr = qrcode.QRCode(
  370. version=self.version_entry.get_value(),
  371. error_correction=error_code,
  372. box_size=self.bsize_entry.get_value(),
  373. border=self.border_size_entry.get_value(),
  374. image_factory=qrcode.image.svg.SvgFragmentImage
  375. )
  376. qr.add_data(text_data)
  377. qr.make()
  378. svg_file = BytesIO()
  379. img = qr.make_image()
  380. img.save(svg_file)
  381. svg_text = StringIO(svg_file.getvalue().decode('UTF-8'))
  382. svg_geometry = self.convert_svg_to_geo(svg_text, units=self.units)
  383. self.qrcode_geometry = deepcopy(svg_geometry)
  384. svg_geometry = unary_union(svg_geometry).buffer(0.0000001).buffer(-0.0000001)
  385. self.qrcode_utility_geometry = svg_geometry
  386. # make a bounding box of the QRCode geometry to help drawing the utility geometry in case it is too
  387. # complicated
  388. try:
  389. a, b, c, d = self.qrcode_utility_geometry.bounds
  390. self.box_poly = box(minx=a, miny=b, maxx=c, maxy=d)
  391. except Exception as ee:
  392. log.debug("QRCode.make() bounds error --> %s" % str(ee))
  393. app_obj.call_source = 'qrcode_tool'
  394. app_obj.inform.emit(_("Click on the Destination point ..."))
  395. self.app.worker_task.emit({'fcn': job_thread_qr, 'params': [self.app]})
  396. def make(self, pos):
  397. self.on_exit()
  398. # make sure that the source object solid geometry is an Iterable
  399. if not isinstance(self.grb_object.solid_geometry, Iterable):
  400. self.grb_object.solid_geometry = [self.grb_object.solid_geometry]
  401. # I use the utility geometry (self.qrcode_utility_geometry) because it is already buffered
  402. geo_list = self.grb_object.solid_geometry
  403. if isinstance(self.grb_object.solid_geometry, MultiPolygon):
  404. geo_list = list(self.grb_object.solid_geometry.geoms)
  405. # this is the bounding box of the QRCode geometry
  406. a, b, c, d = self.qrcode_utility_geometry.bounds
  407. buff_val = self.border_size_entry.get_value() * (self.bsize_entry.get_value() / 10)
  408. if self.bb_radio.get_value() == 'r':
  409. mask_geo = box(a, b, c, d).buffer(buff_val)
  410. else:
  411. mask_geo = box(a, b, c, d).buffer(buff_val, join_style=2)
  412. # update the solid geometry with the cutout (if it is the case)
  413. new_solid_geometry = []
  414. offset_mask_geo = translate(mask_geo, xoff=pos[0], yoff=pos[1])
  415. for poly in geo_list:
  416. if poly.contains(offset_mask_geo):
  417. new_solid_geometry.append(poly.difference(offset_mask_geo))
  418. else:
  419. if poly not in new_solid_geometry:
  420. new_solid_geometry.append(poly)
  421. geo_list = deepcopy(list(new_solid_geometry))
  422. # Polarity
  423. if self.pol_radio.get_value() == 'pos':
  424. working_geo = self.qrcode_utility_geometry
  425. else:
  426. working_geo = mask_geo.difference(self.qrcode_utility_geometry)
  427. try:
  428. for geo in working_geo:
  429. geo_list.append(translate(geo, xoff=pos[0], yoff=pos[1]))
  430. except TypeError:
  431. geo_list.append(translate(working_geo, xoff=pos[0], yoff=pos[1]))
  432. self.grb_object.solid_geometry = deepcopy(geo_list)
  433. box_size = float(self.bsize_entry.get_value()) / 10.0
  434. sort_apid = []
  435. new_apid = '10'
  436. if self.grb_object.apertures:
  437. for k, v in list(self.grb_object.apertures.items()):
  438. sort_apid.append(int(k))
  439. sorted_apertures = sorted(sort_apid)
  440. max_apid = max(sorted_apertures)
  441. if max_apid >= 10:
  442. new_apid = str(max_apid + 1)
  443. else:
  444. new_apid = '10'
  445. # don't know if the condition is required since I already made sure above that the new_apid is a new one
  446. if new_apid not in self.grb_object.apertures:
  447. self.grb_object.apertures[new_apid] = {}
  448. self.grb_object.apertures[new_apid]['geometry'] = []
  449. self.grb_object.apertures[new_apid]['type'] = 'R'
  450. # TODO: HACK
  451. # I've artificially added 1% to the height and width because otherwise after loading the
  452. # exported file, it will not be correctly reconstructed (it will be made from multiple shapes instead of
  453. # one shape which show that the buffering didn't worked well). It may be the MM to INCH conversion.
  454. self.grb_object.apertures[new_apid]['height'] = deepcopy(box_size * 1.01)
  455. self.grb_object.apertures[new_apid]['width'] = deepcopy(box_size * 1.01)
  456. self.grb_object.apertures[new_apid]['size'] = deepcopy(math.sqrt(box_size ** 2 + box_size ** 2))
  457. if '0' not in self.grb_object.apertures:
  458. self.grb_object.apertures['0'] = {}
  459. self.grb_object.apertures['0']['geometry'] = []
  460. self.grb_object.apertures['0']['type'] = 'REG'
  461. self.grb_object.apertures['0']['size'] = 0.0
  462. # in case that the QRCode geometry is dropped onto a copper region (found in the '0' aperture)
  463. # make sure that I place a cutout there
  464. zero_elem = {}
  465. zero_elem['clear'] = offset_mask_geo
  466. self.grb_object.apertures['0']['geometry'].append(deepcopy(zero_elem))
  467. try:
  468. a, b, c, d = self.grb_object.bounds()
  469. self.grb_object.options['xmin'] = a
  470. self.grb_object.options['ymin'] = b
  471. self.grb_object.options['xmax'] = c
  472. self.grb_object.options['ymax'] = d
  473. except Exception as e:
  474. log.debug("QRCode.make() bounds error --> %s" % str(e))
  475. try:
  476. for geo in self.qrcode_geometry:
  477. geo_elem = {}
  478. geo_elem['solid'] = translate(geo, xoff=pos[0], yoff=pos[1])
  479. geo_elem['follow'] = translate(geo.centroid, xoff=pos[0], yoff=pos[1])
  480. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  481. except TypeError:
  482. geo_elem = {}
  483. geo_elem['solid'] = self.qrcode_geometry
  484. self.grb_object.apertures[new_apid]['geometry'].append(deepcopy(geo_elem))
  485. # update the source file with the new geometry:
  486. self.grb_object.source_file = self.app.export_gerber(obj_name=self.grb_object.options['name'], filename=None,
  487. local_use=self.grb_object, use_thread=False)
  488. self.replot(obj=self.grb_object)
  489. self.app.inform.emit('[success] %s' % _("QRCode Tool done."))
  490. def draw_utility_geo(self, pos):
  491. # face = '#0000FF' + str(hex(int(0.2 * 255)))[2:]
  492. outline = '#0000FFAF'
  493. offset_geo = []
  494. # I use the len of self.qrcode_geometry instead of the utility one because the complexity of the polygons is
  495. # better seen in this (bit what if the sel.qrcode_geometry is just one geo element? len will fail ...
  496. if len(self.qrcode_geometry) <= self.app.defaults["tools_qrcode_sel_limit"]:
  497. try:
  498. for poly in self.qrcode_utility_geometry:
  499. offset_geo.append(translate(poly.exterior, xoff=pos[0], yoff=pos[1]))
  500. for geo_int in poly.interiors:
  501. offset_geo.append(translate(geo_int, xoff=pos[0], yoff=pos[1]))
  502. except TypeError:
  503. offset_geo.append(translate(self.qrcode_utility_geometry.exterior, xoff=pos[0], yoff=pos[1]))
  504. for geo_int in self.qrcode_utility_geometry.interiors:
  505. offset_geo.append(translate(geo_int, xoff=pos[0], yoff=pos[1]))
  506. else:
  507. offset_geo = [translate(self.box_poly, xoff=pos[0], yoff=pos[1])]
  508. for shape in offset_geo:
  509. self.shapes.add(shape, color=outline, update=True, layer=0, tolerance=None)
  510. if self.app.is_legacy is True:
  511. self.shapes.redraw()
  512. def delete_utility_geo(self):
  513. self.shapes.clear(update=True)
  514. self.shapes.redraw()
  515. def on_mouse_move(self, event):
  516. if self.app.is_legacy is False:
  517. event_pos = event.pos
  518. else:
  519. event_pos = (event.xdata, event.ydata)
  520. try:
  521. x = float(event_pos[0])
  522. y = float(event_pos[1])
  523. except TypeError:
  524. return
  525. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  526. # if GRID is active we need to get the snapped positions
  527. if self.app.grid_status() == True:
  528. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  529. else:
  530. pos = pos_canvas
  531. dx = pos[0] - self.origin[0]
  532. dy = pos[1] - self.origin[1]
  533. # delete the utility geometry
  534. self.delete_utility_geo()
  535. self.draw_utility_geo((dx, dy))
  536. def on_mouse_release(self, event):
  537. # mouse click will be accepted only if the left button is clicked
  538. # this is necessary because right mouse click and middle mouse click
  539. # are used for panning on the canvas
  540. if self.app.is_legacy is False:
  541. event_pos = event.pos
  542. else:
  543. event_pos = (event.xdata, event.ydata)
  544. if event.button == 1:
  545. pos_canvas = self.app.plotcanvas.translate_coords(event_pos)
  546. self.delete_utility_geo()
  547. # if GRID is active we need to get the snapped positions
  548. if self.app.grid_status() == True:
  549. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  550. else:
  551. pos = pos_canvas
  552. dx = pos[0] - self.origin[0]
  553. dy = pos[1] - self.origin[1]
  554. self.make(pos=(dx, dy))
  555. def on_key_release(self, event):
  556. pass
  557. def convert_svg_to_geo(self, filename, object_type=None, flip=True, units='MM'):
  558. """
  559. Convert shapes from an SVG file into a geometry list.
  560. :param filename: A String Stream file.
  561. :param object_type: parameter passed further along. What kind the object will receive the SVG geometry
  562. :param flip: Flip the vertically.
  563. :type flip: bool
  564. :param units: FlatCAM units
  565. :return: None
  566. """
  567. # Parse into list of shapely objects
  568. svg_tree = ET.parse(filename)
  569. svg_root = svg_tree.getroot()
  570. # Change origin to bottom left
  571. # h = float(svg_root.get('height'))
  572. # w = float(svg_root.get('width'))
  573. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  574. geos = getsvggeo(svg_root, object_type)
  575. if flip:
  576. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  577. # flatten the svg geometry for the case when the QRCode SVG is added into a Gerber object
  578. solid_geometry = list(self.flatten_list(geos))
  579. geos_text = getsvgtext(svg_root, object_type, units=units)
  580. if geos_text is not None:
  581. geos_text_f = []
  582. if flip:
  583. # Change origin to bottom left
  584. for i in geos_text:
  585. _, minimy, _, maximy = i.bounds
  586. h2 = (maximy - minimy) * 0.5
  587. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  588. if geos_text_f:
  589. solid_geometry += geos_text_f
  590. return solid_geometry
  591. def flatten_list(self, geo_list):
  592. for item in geo_list:
  593. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  594. yield from self.flatten_list(item)
  595. else:
  596. yield item
  597. def replot(self, obj):
  598. def worker_task():
  599. with self.app.proc_container.new('%s...' % _("Plotting")):
  600. obj.plot()
  601. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  602. def on_exit(self):
  603. if self.app.is_legacy is False:
  604. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  605. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  606. self.app.plotcanvas.graph_event_disconnect('key_release', self.on_key_release)
  607. else:
  608. self.app.plotcanvas.graph_event_disconnect(self.mm)
  609. self.app.plotcanvas.graph_event_disconnect(self.mr)
  610. self.app.plotcanvas.graph_event_disconnect(self.kr)
  611. # delete the utility geometry
  612. self.delete_utility_geo()
  613. self.app.call_source = 'app'
  614. def export_png_file(self):
  615. text_data = self.text_data.get_value()
  616. if text_data == '':
  617. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  618. return 'fail'
  619. def job_thread_qr_png(app_obj, fname):
  620. error_code = {
  621. 'L': qrcode.constants.ERROR_CORRECT_L,
  622. 'M': qrcode.constants.ERROR_CORRECT_M,
  623. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  624. 'H': qrcode.constants.ERROR_CORRECT_H
  625. }[self.error_radio.get_value()]
  626. qr = qrcode.QRCode(
  627. version=self.version_entry.get_value(),
  628. error_correction=error_code,
  629. box_size=self.bsize_entry.get_value(),
  630. border=self.border_size_entry.get_value(),
  631. image_factory=qrcode.image.pil.PilImage
  632. )
  633. qr.add_data(text_data)
  634. qr.make(fit=True)
  635. img = qr.make_image(fill_color=self.fill_color_entry.get_value(),
  636. back_color=self.back_color_entry.get_value())
  637. img.save(fname)
  638. app_obj.call_source = 'qrcode_tool'
  639. name = 'qr_code'
  640. _filter = "PNG File (*.png);;All Files (*.*)"
  641. try:
  642. filename, _f = FCFileSaveDialog.get_saved_filename(
  643. caption=_("Export PNG"),
  644. directory=self.app.get_last_save_folder() + '/' + str(name) + '_png',
  645. filter=_filter)
  646. except TypeError:
  647. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG"), filter=_filter)
  648. filename = str(filename)
  649. if filename == "":
  650. self.app.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  651. return
  652. else:
  653. self.app.worker_task.emit({'fcn': job_thread_qr_png, 'params': [self.app, filename]})
  654. def export_svg_file(self):
  655. text_data = self.text_data.get_value()
  656. if text_data == '':
  657. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Cancelled. There is no QRCode Data in the text box."))
  658. return 'fail'
  659. def job_thread_qr_svg(app_obj, fname):
  660. error_code = {
  661. 'L': qrcode.constants.ERROR_CORRECT_L,
  662. 'M': qrcode.constants.ERROR_CORRECT_M,
  663. 'Q': qrcode.constants.ERROR_CORRECT_Q,
  664. 'H': qrcode.constants.ERROR_CORRECT_H
  665. }[self.error_radio.get_value()]
  666. qr = qrcode.QRCode(
  667. version=self.version_entry.get_value(),
  668. error_correction=error_code,
  669. box_size=self.bsize_entry.get_value(),
  670. border=self.border_size_entry.get_value(),
  671. image_factory=qrcode.image.svg.SvgPathImage
  672. )
  673. qr.add_data(text_data)
  674. img = qr.make_image(fill_color=self.fill_color_entry.get_value(),
  675. back_color=self.back_color_entry.get_value())
  676. img.save(fname)
  677. app_obj.call_source = 'qrcode_tool'
  678. name = 'qr_code'
  679. _filter = "SVG File (*.svg);;All Files (*.*)"
  680. try:
  681. filename, _f = FCFileSaveDialog.get_saved_filename(
  682. caption=_("Export SVG"),
  683. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  684. filter=_filter)
  685. except TypeError:
  686. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  687. filename = str(filename)
  688. if filename == "":
  689. self.app.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  690. return
  691. else:
  692. self.app.worker_task.emit({'fcn': job_thread_qr_svg, 'params': [self.app, filename]})
  693. def on_qrcode_fill_color_entry(self):
  694. color = self.fill_color_entry.get_value()
  695. self.fill_color_button.setStyleSheet("background-color:%s" % str(color))
  696. def on_qrcode_fill_color_button(self):
  697. current_color = QtGui.QColor(self.fill_color_entry.get_value())
  698. c_dialog = QtWidgets.QColorDialog()
  699. fill_color = c_dialog.getColor(initial=current_color)
  700. if fill_color.isValid() is False:
  701. return
  702. self.fill_color_button.setStyleSheet("background-color:%s" % str(fill_color.name()))
  703. new_val_sel = str(fill_color.name())
  704. self.fill_color_entry.set_value(new_val_sel)
  705. def on_qrcode_back_color_entry(self):
  706. color = self.back_color_entry.get_value()
  707. self.back_color_button.setStyleSheet("background-color:%s" % str(color))
  708. def on_qrcode_back_color_button(self):
  709. current_color = QtGui.QColor(self.back_color_entry.get_value())
  710. c_dialog = QtWidgets.QColorDialog()
  711. back_color = c_dialog.getColor(initial=current_color)
  712. if back_color.isValid() is False:
  713. return
  714. self.back_color_button.setStyleSheet("background-color:%s" % str(back_color.name()))
  715. new_val_sel = str(back_color.name())
  716. self.back_color_entry.set_value(new_val_sel)
  717. def on_transparent_back_color(self, state):
  718. if state:
  719. self.back_color_entry.setDisabled(True)
  720. self.back_color_button.setDisabled(True)
  721. self.old_back_color = self.back_color_entry.get_value()
  722. self.back_color_entry.set_value('transparent')
  723. else:
  724. self.back_color_entry.setDisabled(False)
  725. self.back_color_button.setDisabled(False)
  726. self.back_color_entry.set_value(self.old_back_color)