ToolQRCode.py 39 KB

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