ToolQRCode.py 36 KB

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