ToolQRCode.py 38 KB

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