ToolQRCode.py 39 KB

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