ToolFilm.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtCore, QtWidgets, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import RadioSet, FCDoubleSpinner, FCCheckBox, \
  10. OptionalHideInputSection, FCComboBox, FCFileSaveDialog
  11. from copy import deepcopy
  12. import logging
  13. from shapely.geometry import Polygon, MultiPolygon, Point
  14. from reportlab.graphics import renderPDF
  15. from reportlab.pdfgen import canvas
  16. from reportlab.graphics import renderPM
  17. from reportlab.lib.units import inch, mm
  18. from reportlab.lib.pagesizes import landscape, portrait
  19. from svglib.svglib import svg2rlg
  20. from xml.dom.minidom import parseString as parse_xml_string
  21. from lxml import etree as ET
  22. from io import StringIO
  23. import gettext
  24. import appTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. log = logging.getLogger('base')
  30. class Film(AppTool):
  31. def __init__(self, app):
  32. AppTool.__init__(self, app)
  33. self.decimals = self.app.decimals
  34. self.units = self.app.defaults['units']
  35. # #############################################################################
  36. # ######################### Tool GUI ##########################################
  37. # #############################################################################
  38. self.ui = FilmUI(layout=self.layout, app=self.app)
  39. self.toolName = self.ui.toolName
  40. # ## Signals
  41. self.ui.film_object_button.clicked.connect(self.on_film_creation)
  42. self.ui.tf_type_obj_combo.activated_custom.connect(self.on_type_obj_index_changed)
  43. self.ui.tf_type_box_combo.activated_custom.connect(self.on_type_box_index_changed)
  44. self.ui.film_type.activated_custom.connect(self.ui.on_film_type)
  45. self.ui.source_punch.activated_custom.connect(self.ui.on_punch_source)
  46. self.ui.file_type_radio.activated_custom.connect(self.ui.on_file_type)
  47. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  48. def on_type_obj_index_changed(self, val):
  49. obj_type = 2 if val == 'geo' else 0
  50. self.ui.tf_object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  51. self.ui.tf_object_combo.setCurrentIndex(0)
  52. self.ui.tf_object_combo.obj_type = {
  53. "grb": "gerber", "geo": "geometry"
  54. }[self.ui.tf_type_obj_combo.get_value()]
  55. def on_type_box_index_changed(self, val):
  56. obj_type = 2 if val == 'geo' else 0
  57. self.ui.tf_box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  58. self.ui.tf_box_combo.setCurrentIndex(0)
  59. self.ui.tf_box_combo.obj_type = {
  60. "grb": "gerber", "geo": "geometry"
  61. }[self.ui.tf_type_obj_combo.get_value()]
  62. def run(self, toggle=True):
  63. self.app.defaults.report_usage("ToolFilm()")
  64. if toggle:
  65. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  66. if self.app.ui.splitter.sizes()[0] == 0:
  67. self.app.ui.splitter.setSizes([1, 1])
  68. else:
  69. try:
  70. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  71. # if tab is populated with the tool but it does not have the focus, focus on it
  72. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  73. # focus on Tool Tab
  74. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  75. else:
  76. self.app.ui.splitter.setSizes([0, 1])
  77. except AttributeError:
  78. pass
  79. else:
  80. if self.app.ui.splitter.sizes()[0] == 0:
  81. self.app.ui.splitter.setSizes([1, 1])
  82. AppTool.run(self)
  83. self.set_tool_ui()
  84. self.app.ui.notebook.setTabText(2, _("Film Tool"))
  85. def install(self, icon=None, separator=None, **kwargs):
  86. AppTool.install(self, icon, separator, shortcut='Alt+L', **kwargs)
  87. def set_tool_ui(self):
  88. self.reset_fields()
  89. f_type = self.app.defaults["tools_film_type"] if self.app.defaults["tools_film_type"] else 'neg'
  90. self.ui.film_type.set_value(str(f_type))
  91. self.ui.on_film_type(val=f_type)
  92. b_entry = self.app.defaults["tools_film_boundary"] if self.app.defaults["tools_film_boundary"] else 0.0
  93. self.ui.boundary_entry.set_value(float(b_entry))
  94. scale_stroke_width = self.app.defaults["tools_film_scale_stroke"] if \
  95. self.app.defaults["tools_film_scale_stroke"] else 0.0
  96. self.ui.film_scale_stroke_entry.set_value(int(scale_stroke_width))
  97. self.ui.punch_cb.set_value(False)
  98. self.ui.source_punch.set_value('exc')
  99. self.ui.film_scale_cb.set_value(self.app.defaults["tools_film_scale_cb"])
  100. self.ui.film_scalex_entry.set_value(float(self.app.defaults["tools_film_scale_x_entry"]))
  101. self.ui.film_scaley_entry.set_value(float(self.app.defaults["tools_film_scale_y_entry"]))
  102. self.ui.film_skew_cb.set_value(self.app.defaults["tools_film_skew_cb"])
  103. self.ui.film_skewx_entry.set_value(float(self.app.defaults["tools_film_skew_x_entry"]))
  104. self.ui.film_skewy_entry.set_value(float(self.app.defaults["tools_film_skew_y_entry"]))
  105. self.ui.film_skew_reference.set_value(self.app.defaults["tools_film_skew_ref_radio"])
  106. self.ui.film_mirror_cb.set_value(self.app.defaults["tools_film_mirror_cb"])
  107. self.ui.film_mirror_axis.set_value(self.app.defaults["tools_film_mirror_axis_radio"])
  108. self.ui.file_type_radio.set_value(self.app.defaults["tools_film_file_type_radio"])
  109. self.ui.orientation_radio.set_value(self.app.defaults["tools_film_orientation"])
  110. self.ui.pagesize_combo.set_value(self.app.defaults["tools_film_pagesize"])
  111. self.ui.tf_type_obj_combo.set_value('grb')
  112. self.ui.tf_type_box_combo.set_value('grb')
  113. # run once to update the obj_type attribute in the FCCombobox so the last object is showed in cb
  114. self.on_type_obj_index_changed(val='grb')
  115. self.on_type_box_index_changed(val='grb')
  116. def on_film_creation(self):
  117. log.debug("ToolFilm.Film.on_film_creation() started ...")
  118. try:
  119. name = self.ui.tf_object_combo.currentText()
  120. except Exception:
  121. self.app.inform.emit('[ERROR_NOTCL] %s' %
  122. _("No FlatCAM object selected. Load an object for Film and retry."))
  123. return
  124. try:
  125. boxname = self.ui.tf_box_combo.currentText()
  126. except Exception:
  127. self.app.inform.emit('[ERROR_NOTCL] %s' %
  128. _("No FlatCAM object selected. Load an object for Box and retry."))
  129. return
  130. if name == '' or boxname == '':
  131. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No FlatCAM object selected."))
  132. return
  133. scale_stroke_width = float(self.ui.film_scale_stroke_entry.get_value())
  134. source = self.ui.source_punch.get_value()
  135. file_type = self.ui.file_type_radio.get_value()
  136. # #################################################################
  137. # ################ STARTING THE JOB ###############################
  138. # #################################################################
  139. self.app.inform.emit(_("Generating Film ..."))
  140. if self.ui.film_type.get_value() == "pos":
  141. if self.ui.punch_cb.get_value() is False:
  142. self.generate_positive_normal_film(name, boxname, factor=scale_stroke_width, ftype=file_type)
  143. else:
  144. self.generate_positive_punched_film(name, boxname, source, factor=scale_stroke_width, ftype=file_type)
  145. else:
  146. self.generate_negative_film(name, boxname, factor=scale_stroke_width, ftype=file_type)
  147. def generate_positive_normal_film(self, name, boxname, factor, ftype='svg'):
  148. log.debug("ToolFilm.Film.generate_positive_normal_film() started ...")
  149. scale_factor_x = None
  150. scale_factor_y = None
  151. skew_factor_x = None
  152. skew_factor_y = None
  153. mirror = None
  154. skew_reference = 'center'
  155. if self.ui.film_scale_cb.get_value():
  156. if self.ui.film_scalex_entry.get_value() != 1.0:
  157. scale_factor_x = self.ui.film_scalex_entry.get_value()
  158. if self.ui.film_scaley_entry.get_value() != 1.0:
  159. scale_factor_y = self.ui.film_scaley_entry.get_value()
  160. if self.ui.film_skew_cb.get_value():
  161. if self.ui.film_skewx_entry.get_value() != 0.0:
  162. skew_factor_x = self.ui.film_skewx_entry.get_value()
  163. if self.ui.film_skewy_entry.get_value() != 0.0:
  164. skew_factor_y = self.ui.film_skewy_entry.get_value()
  165. skew_reference = self.ui.film_skew_reference.get_value()
  166. if self.ui.film_mirror_cb.get_value():
  167. if self.ui.film_mirror_axis.get_value() != 'none':
  168. mirror = self.ui.film_mirror_axis.get_value()
  169. if ftype == 'svg':
  170. filter_ext = "SVG Files (*.SVG);;"\
  171. "All Files (*.*)"
  172. elif ftype == 'png':
  173. filter_ext = "PNG Files (*.PNG);;" \
  174. "All Files (*.*)"
  175. else:
  176. filter_ext = "PDF Files (*.PDF);;" \
  177. "All Files (*.*)"
  178. try:
  179. filename, _f = FCFileSaveDialog.get_saved_filename(
  180. caption=_("Export positive film"),
  181. directory=self.app.get_last_save_folder() + '/' + name + '_film',
  182. ext_filter=filter_ext)
  183. except TypeError:
  184. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export positive film"))
  185. filename = str(filename)
  186. if str(filename) == "":
  187. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  188. return
  189. else:
  190. pagesize = self.ui.pagesize_combo.get_value()
  191. orientation = self.ui.orientation_radio.get_value()
  192. color = self.app.defaults['tools_film_color']
  193. self.export_positive(name, boxname, filename,
  194. scale_stroke_factor=factor,
  195. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  196. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  197. skew_reference=skew_reference,
  198. mirror=mirror,
  199. pagesize_val=pagesize, orientation_val=orientation, color_val=color, opacity_val=1.0,
  200. ftype=ftype
  201. )
  202. def generate_positive_punched_film(self, name, boxname, source, factor, ftype='svg'):
  203. film_obj = self.app.collection.get_by_name(name)
  204. if source == 'exc':
  205. log.debug("ToolFilm.Film.generate_positive_punched_film() with Excellon source started ...")
  206. try:
  207. exc_name = self.ui.exc_combo.currentText()
  208. except Exception:
  209. self.app.inform.emit('[ERROR_NOTCL] %s' %
  210. _("No Excellon object selected. Load an object for punching reference and retry."))
  211. return
  212. exc_obj = self.app.collection.get_by_name(exc_name)
  213. exc_solid_geometry = MultiPolygon(exc_obj.solid_geometry)
  214. punched_solid_geometry = MultiPolygon(film_obj.solid_geometry).difference(exc_solid_geometry)
  215. def init_func(new_obj, app_obj):
  216. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  217. outname = name + "_punched"
  218. self.app.app_obj.new_object('gerber', outname, init_func)
  219. self.generate_positive_normal_film(outname, boxname, factor=factor, ftype=ftype)
  220. else:
  221. log.debug("ToolFilm.Film.generate_positive_punched_film() with Pad center source started ...")
  222. punch_size = float(self.ui.punch_size_spinner.get_value())
  223. punching_geo = []
  224. for apid in film_obj.apertures:
  225. if film_obj.apertures[apid]['type'] == 'C':
  226. if punch_size >= float(film_obj.apertures[apid]['size']):
  227. self.app.inform.emit('[ERROR_NOTCL] %s' %
  228. _(" Could not generate punched hole film because the punch hole size"
  229. "is bigger than some of the apertures in the Gerber object."))
  230. return 'fail'
  231. else:
  232. for elem in film_obj.apertures[apid]['geometry']:
  233. if 'follow' in elem:
  234. if isinstance(elem['follow'], Point):
  235. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  236. else:
  237. if punch_size >= float(film_obj.apertures[apid]['width']) or \
  238. punch_size >= float(film_obj.apertures[apid]['height']):
  239. self.app.inform.emit('[ERROR_NOTCL] %s' %
  240. _("Could not generate punched hole film because the punch hole size"
  241. "is bigger than some of the apertures in the Gerber object."))
  242. return 'fail'
  243. else:
  244. for elem in film_obj.apertures[apid]['geometry']:
  245. if 'follow' in elem:
  246. if isinstance(elem['follow'], Point):
  247. punching_geo.append(elem['follow'].buffer(punch_size / 2))
  248. punching_geo = MultiPolygon(punching_geo)
  249. if not isinstance(film_obj.solid_geometry, Polygon):
  250. temp_solid_geometry = MultiPolygon(film_obj.solid_geometry)
  251. else:
  252. temp_solid_geometry = film_obj.solid_geometry
  253. punched_solid_geometry = temp_solid_geometry.difference(punching_geo)
  254. if punched_solid_geometry == temp_solid_geometry:
  255. self.app.inform.emit('[WARNING_NOTCL] %s' %
  256. _("Could not generate punched hole film because the newly created object geometry "
  257. "is the same as the one in the source object geometry..."))
  258. return 'fail'
  259. def init_func(new_obj, app_obj):
  260. new_obj.solid_geometry = deepcopy(punched_solid_geometry)
  261. outname = name + "_punched"
  262. self.app.app_obj.new_object('gerber', outname, init_func)
  263. self.generate_positive_normal_film(outname, boxname, factor=factor, ftype=ftype)
  264. def generate_negative_film(self, name, boxname, factor, ftype='svg'):
  265. log.debug("ToolFilm.Film.generate_negative_film() started ...")
  266. scale_factor_x = None
  267. scale_factor_y = None
  268. skew_factor_x = None
  269. skew_factor_y = None
  270. mirror = None
  271. skew_reference = 'center'
  272. if self.ui.film_scale_cb.get_value():
  273. if self.ui.film_scalex_entry.get_value() != 1.0:
  274. scale_factor_x = self.ui.film_scalex_entry.get_value()
  275. if self.ui.film_scaley_entry.get_value() != 1.0:
  276. scale_factor_y = self.ui.film_scaley_entry.get_value()
  277. if self.ui.film_skew_cb.get_value():
  278. if self.ui.film_skewx_entry.get_value() != 0.0:
  279. skew_factor_x = self.ui.film_skewx_entry.get_value()
  280. if self.ui.film_skewy_entry.get_value() != 0.0:
  281. skew_factor_y = self.ui.film_skewy_entry.get_value()
  282. skew_reference = self.ui.film_skew_reference.get_value()
  283. if self.ui.film_mirror_cb.get_value():
  284. if self.ui.film_mirror_axis.get_value() != 'none':
  285. mirror = self.ui.film_mirror_axis.get_value()
  286. border = float(self.ui.boundary_entry.get_value())
  287. if border is None:
  288. border = 0
  289. if ftype == 'svg':
  290. filter_ext = "SVG Files (*.SVG);;"\
  291. "All Files (*.*)"
  292. elif ftype == 'png':
  293. filter_ext = "PNG Files (*.PNG);;" \
  294. "All Files (*.*)"
  295. else:
  296. filter_ext = "PDF Files (*.PDF);;" \
  297. "All Files (*.*)"
  298. try:
  299. filename, _f = FCFileSaveDialog.get_saved_filename(
  300. caption=_("Export negative film"),
  301. directory=self.app.get_last_save_folder() + '/' + name + '_film',
  302. ext_filter=filter_ext)
  303. except TypeError:
  304. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export negative film"))
  305. filename = str(filename)
  306. if str(filename) == "":
  307. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  308. return
  309. else:
  310. self.export_negative(name, boxname, filename, border,
  311. scale_stroke_factor=factor,
  312. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  313. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  314. skew_reference=skew_reference,
  315. mirror=mirror, ftype=ftype
  316. )
  317. def export_negative(self, obj_name, box_name, filename, boundary,
  318. scale_stroke_factor=0.00,
  319. scale_factor_x=None, scale_factor_y=None,
  320. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  321. mirror=None,
  322. use_thread=True, ftype='svg'):
  323. """
  324. Exports a Geometry Object to an SVG file in negative.
  325. :param obj_name: the name of the FlatCAM object to be saved as SVG
  326. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  327. :param filename: Path to the SVG file to save to.
  328. :param boundary: thickness of a black border to surround all the features
  329. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  330. :param scale_factor_x: factor to scale the svg geometry on the X axis
  331. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  332. :param skew_factor_x: factor to skew the svg geometry on the X axis
  333. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  334. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  335. those are the 4 points of the bounding box of the geometry to be skewed.
  336. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  337. :param use_thread: if to be run in a separate thread; boolean
  338. :param ftype: the type of file for saving the film: 'svg', 'png' or 'pdf'
  339. :return:
  340. """
  341. self.app.defaults.report_usage("export_negative()")
  342. if filename is None:
  343. filename = self.app.defaults["global_last_save_folder"]
  344. self.app.log.debug("export_svg() negative")
  345. try:
  346. obj = self.app.collection.get_by_name(str(obj_name))
  347. except Exception:
  348. return "Could not retrieve object: %s" % obj_name
  349. try:
  350. box = self.app.collection.get_by_name(str(box_name))
  351. except Exception:
  352. return "Could not retrieve object: %s" % box_name
  353. if box is None:
  354. self.app.inform.emit('[WARNING_NOTCL] %s: %s' % (_("No object Box. Using instead"), obj))
  355. box = obj
  356. def make_negative_film():
  357. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  358. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  359. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  360. mirror=mirror
  361. )
  362. # Determine bounding area for svg export
  363. bounds = box.bounds()
  364. size = box.size()
  365. uom = obj.units.lower()
  366. # Convert everything to strings for use in the xml doc
  367. svgwidth = str(size[0] + (2 * boundary))
  368. svgheight = str(size[1] + (2 * boundary))
  369. minx = str(bounds[0] - boundary)
  370. miny = str(bounds[1] + boundary + size[1])
  371. miny_rect = str(bounds[1] - boundary)
  372. # Add a SVG Header and footer to the svg output from shapely
  373. # The transform flips the Y Axis so that everything renders
  374. # properly within svg apps such as inkscape
  375. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  376. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  377. svg_header += 'width="' + svgwidth + uom + '" '
  378. svg_header += 'height="' + svgheight + uom + '" '
  379. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  380. svg_header += '>'
  381. svg_header += '<g transform="scale(1,-1)">'
  382. svg_footer = '</g> </svg>'
  383. # Change the attributes of the exported SVG
  384. # We don't need stroke-width - wrong, we do when we have lines with certain width
  385. # We set opacity to maximum
  386. # We set the color to WHITE
  387. root = ET.fromstring(exported_svg)
  388. for child in root:
  389. child.set('fill', '#FFFFFF')
  390. child.set('opacity', '1.0')
  391. child.set('stroke', '#FFFFFF')
  392. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  393. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  394. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  395. first_svg_elem_tag = 'rect'
  396. first_svg_elem_attribs = {
  397. 'x': minx,
  398. 'y': miny_rect,
  399. 'width': svgwidth,
  400. 'height': svgheight,
  401. 'id': 'neg_rect',
  402. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  403. }
  404. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  405. exported_svg = ET.tostring(root)
  406. svg_elem = svg_header + str(exported_svg) + svg_footer
  407. # Parse the xml through a xml parser just to add line feeds
  408. # and to make it look more pretty for the output
  409. doc = parse_xml_string(svg_elem)
  410. doc_final = doc.toprettyxml()
  411. if ftype == 'svg':
  412. try:
  413. with open(filename, 'w') as fp:
  414. fp.write(doc_final)
  415. except PermissionError:
  416. self.app.inform.emit('[WARNING] %s' %
  417. _("Permission denied, saving not possible.\n"
  418. "Most likely another app is holding the file open and not accessible."))
  419. return 'fail'
  420. elif ftype == 'png':
  421. try:
  422. doc_final = StringIO(doc_final)
  423. drawing = svg2rlg(doc_final)
  424. renderPM.drawToFile(drawing, filename, 'PNG')
  425. except Exception as e:
  426. log.debug("FilmTool.export_negative() --> PNG output --> %s" % str(e))
  427. return 'fail'
  428. else:
  429. try:
  430. if self.units == 'INCH':
  431. unit = inch
  432. else:
  433. unit = mm
  434. doc_final = StringIO(doc_final)
  435. drawing = svg2rlg(doc_final)
  436. p_size = self.ui.pagesize_combo.get_value()
  437. if p_size == 'Bounds':
  438. renderPDF.drawToFile(drawing, filename)
  439. else:
  440. if self.ui.orientation_radio.get_value() == 'p':
  441. page_size = portrait(self.ui.pagesize[p_size])
  442. else:
  443. page_size = landscape(self.ui.pagesize[p_size])
  444. my_canvas = canvas.Canvas(filename, pagesize=page_size)
  445. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  446. renderPDF.draw(drawing, my_canvas, 0, 0)
  447. my_canvas.save()
  448. except Exception as e:
  449. log.debug("FilmTool.export_negative() --> PDF output --> %s" % str(e))
  450. return 'fail'
  451. if self.app.defaults["global_open_style"] is False:
  452. self.app.file_opened.emit("SVG", filename)
  453. self.app.file_saved.emit("SVG", filename)
  454. self.app.inform.emit('[success] %s: %s' % (_("Film file exported to"), filename))
  455. if use_thread is True:
  456. proc = self.app.proc_container.new(_("Generating Film ... Please wait."))
  457. def job_thread_film(app_obj):
  458. try:
  459. make_negative_film()
  460. except Exception:
  461. proc.done()
  462. return
  463. proc.done()
  464. self.app.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  465. else:
  466. make_negative_film()
  467. def export_positive(self, obj_name, box_name, filename,
  468. scale_stroke_factor=0.00,
  469. scale_factor_x=None, scale_factor_y=None,
  470. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  471. mirror=None, orientation_val='p', pagesize_val='A4', color_val='black', opacity_val=1.0,
  472. use_thread=True, ftype='svg'):
  473. """
  474. Exports a Geometry Object to an SVG file in positive black.
  475. :param obj_name: the name of the FlatCAM object to be saved
  476. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  477. :param filename: Path to the file to save to.
  478. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  479. :param scale_factor_x: factor to scale the geometry on the X axis
  480. :param scale_factor_y: factor to scale the geometry on the Y axis
  481. :param skew_factor_x: factor to skew the geometry on the X axis
  482. :param skew_factor_y: factor to skew the geometry on the Y axis
  483. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft',
  484. 'topright' and those are the 4 points of the bounding box of the geometry to be skewed.
  485. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  486. :param orientation_val:
  487. :param pagesize_val:
  488. :param color_val:
  489. :param opacity_val:
  490. :param use_thread: if to be run in a separate thread; boolean
  491. :param ftype: the type of file for saving the film: 'svg', 'png' or 'pdf'
  492. :return:
  493. """
  494. self.app.defaults.report_usage("export_positive()")
  495. if filename is None:
  496. filename = self.app.defaults["global_last_save_folder"]
  497. self.app.log.debug("export_svg() black")
  498. try:
  499. obj = self.app.collection.get_by_name(str(obj_name))
  500. except Exception:
  501. return "Could not retrieve object: %s" % obj_name
  502. try:
  503. box = self.app.collection.get_by_name(str(box_name))
  504. except Exception:
  505. return "Could not retrieve object: %s" % box_name
  506. if box is None:
  507. self.inform.emit('[WARNING_NOTCL] %s: %s' % (_("No object Box. Using instead"), obj))
  508. box = obj
  509. p_size = pagesize_val
  510. orientation = orientation_val
  511. color = color_val
  512. transparency_level = opacity_val
  513. def make_positive_film(p_size, orientation, color, transparency_level):
  514. log.debug("FilmTool.export_positive().make_positive_film()")
  515. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  516. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  517. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  518. mirror=mirror
  519. )
  520. # Change the attributes of the exported SVG
  521. # We don't need stroke-width
  522. # We set opacity to maximum
  523. # We set the colour to WHITE
  524. root = ET.fromstring(exported_svg)
  525. for child in root:
  526. child.set('fill', str(color))
  527. child.set('opacity', str(transparency_level))
  528. child.set('stroke', str(color))
  529. exported_svg = ET.tostring(root)
  530. # Determine bounding area for svg export
  531. bounds = box.bounds()
  532. size = box.size()
  533. # This contain the measure units
  534. uom = obj.units.lower()
  535. # Define a boundary around SVG of about 1.0mm (~39mils)
  536. if uom in "mm":
  537. boundary = 1.0
  538. else:
  539. boundary = 0.0393701
  540. # Convert everything to strings for use in the xml doc
  541. svgwidth = str(size[0] + (2 * boundary))
  542. svgheight = str(size[1] + (2 * boundary))
  543. minx = str(bounds[0] - boundary)
  544. miny = str(bounds[1] + boundary + size[1])
  545. # Add a SVG Header and footer to the svg output from shapely
  546. # The transform flips the Y Axis so that everything renders
  547. # properly within svg apps such as inkscape
  548. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  549. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  550. svg_header += 'width="' + svgwidth + uom + '" '
  551. svg_header += 'height="' + svgheight + uom + '" '
  552. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  553. svg_header += '>'
  554. svg_header += '<g transform="scale(1,-1)">'
  555. svg_footer = '</g> </svg>'
  556. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  557. # Parse the xml through a xml parser just to add line feeds
  558. # and to make it look more pretty for the output
  559. doc = parse_xml_string(svg_elem)
  560. doc_final = doc.toprettyxml()
  561. if ftype == 'svg':
  562. try:
  563. with open(filename, 'w') as fp:
  564. fp.write(doc_final)
  565. except PermissionError:
  566. self.app.inform.emit('[WARNING] %s' %
  567. _("Permission denied, saving not possible.\n"
  568. "Most likely another app is holding the file open and not accessible."))
  569. return 'fail'
  570. elif ftype == 'png':
  571. try:
  572. doc_final = StringIO(doc_final)
  573. drawing = svg2rlg(doc_final)
  574. renderPM.drawToFile(drawing, filename, 'PNG')
  575. except Exception as e:
  576. log.debug("FilmTool.export_positive() --> PNG output --> %s" % str(e))
  577. return 'fail'
  578. else:
  579. try:
  580. if self.units == 'IN':
  581. unit = inch
  582. else:
  583. unit = mm
  584. doc_final = StringIO(doc_final)
  585. drawing = svg2rlg(doc_final)
  586. if p_size == 'Bounds':
  587. renderPDF.drawToFile(drawing, filename)
  588. else:
  589. if orientation == 'p':
  590. page_size = portrait(self.pagesize[p_size])
  591. else:
  592. page_size = landscape(self.pagesize[p_size])
  593. my_canvas = canvas.Canvas(filename, pagesize=page_size)
  594. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  595. renderPDF.draw(drawing, my_canvas, 0, 0)
  596. my_canvas.save()
  597. except Exception as e:
  598. log.debug("FilmTool.export_positive() --> PDF output --> %s" % str(e))
  599. return 'fail'
  600. if self.app.defaults["global_open_style"] is False:
  601. self.app.file_opened.emit("SVG", filename)
  602. self.app.file_saved.emit("SVG", filename)
  603. self.app.inform.emit('[success] %s: %s' % (_("Film file exported to"), filename))
  604. if use_thread is True:
  605. proc = self.app.proc_container.new(_("Generating Film ... Please wait."))
  606. def job_thread_film():
  607. try:
  608. make_positive_film(p_size=p_size, orientation=orientation, color=color,
  609. transparency_level=transparency_level)
  610. except Exception:
  611. proc.done()
  612. return
  613. proc.done()
  614. self.app.worker_task.emit({'fcn': job_thread_film, 'params': []})
  615. else:
  616. make_positive_film(p_size=p_size, orientation=orientation, color=color,
  617. transparency_level=transparency_level)
  618. def reset_fields(self):
  619. self.ui.tf_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  620. self.ui.tf_box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  621. class FilmUI:
  622. toolName = _("Film PCB")
  623. def __init__(self, layout, app):
  624. self.app = app
  625. self.decimals = self.app.decimals
  626. self.layout = layout
  627. # ## Title
  628. title_label = QtWidgets.QLabel("%s" % self.toolName)
  629. title_label.setStyleSheet("""
  630. QLabel
  631. {
  632. font-size: 16px;
  633. font-weight: bold;
  634. }
  635. """)
  636. self.layout.addWidget(title_label)
  637. self.layout.addWidget(QtWidgets.QLabel(""))
  638. # Form Layout
  639. grid0 = QtWidgets.QGridLayout()
  640. self.layout.addLayout(grid0)
  641. grid0.setColumnStretch(0, 0)
  642. grid0.setColumnStretch(1, 1)
  643. # Type of object for which to create the film
  644. self.tf_type_obj_combo = RadioSet([{'label': _('Gerber'), 'value': 'grb'},
  645. {'label': _('Geometry'), 'value': 'geo'}])
  646. self.tf_type_obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("Object"))
  647. self.tf_type_obj_combo_label.setToolTip(
  648. _("Specify the type of object for which to create the film.\n"
  649. "The object can be of type: Gerber or Geometry.\n"
  650. "The selection here decide the type of objects that will be\n"
  651. "in the Film Object combobox.")
  652. )
  653. grid0.addWidget(self.tf_type_obj_combo_label, 0, 0)
  654. grid0.addWidget(self.tf_type_obj_combo, 0, 1)
  655. # List of objects for which we can create the film
  656. self.tf_object_combo = FCComboBox()
  657. self.tf_object_combo.setModel(self.app.collection)
  658. self.tf_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  659. self.tf_object_combo.is_last = True
  660. grid0.addWidget(self.tf_object_combo, 1, 0, 1, 2)
  661. # Type of Box Object to be used as an envelope for film creation
  662. # Within this we can create negative
  663. self.tf_type_box_combo = RadioSet([{'label': _('Gerber'), 'value': 'grb'},
  664. {'label': _('Geometry'), 'value': 'geo'}])
  665. self.tf_type_box_combo_label = QtWidgets.QLabel(_("Box Type:"))
  666. self.tf_type_box_combo_label.setToolTip(
  667. _("Specify the type of object to be used as an container for\n"
  668. "film creation. It can be: Gerber or Geometry type."
  669. "The selection here decide the type of objects that will be\n"
  670. "in the Box Object combobox.")
  671. )
  672. grid0.addWidget(self.tf_type_box_combo_label, 2, 0)
  673. grid0.addWidget(self.tf_type_box_combo, 2, 1)
  674. # Box
  675. self.tf_box_combo = FCComboBox()
  676. self.tf_box_combo.setModel(self.app.collection)
  677. self.tf_box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  678. self.tf_box_combo.is_last = True
  679. grid0.addWidget(self.tf_box_combo, 3, 0, 1, 2)
  680. separator_line = QtWidgets.QFrame()
  681. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  682. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  683. grid0.addWidget(separator_line, 4, 0, 1, 2)
  684. self.film_adj_label = QtWidgets.QLabel('<b>%s</b>' % _("Film Adjustments"))
  685. self.film_adj_label.setToolTip(
  686. _("Sometime the printers will distort the print shape, especially the Laser types.\n"
  687. "This section provide the tools to compensate for the print distortions.")
  688. )
  689. grid0.addWidget(self.film_adj_label, 5, 0, 1, 2)
  690. # Scale Geometry
  691. self.film_scale_cb = FCCheckBox('%s' % _("Scale Film geometry"))
  692. self.film_scale_cb.setToolTip(
  693. _("A value greater than 1 will stretch the film\n"
  694. "while a value less than 1 will jolt it.")
  695. )
  696. self.film_scale_cb.setStyleSheet(
  697. """
  698. QCheckBox {font-weight: bold; color: black}
  699. """
  700. )
  701. grid0.addWidget(self.film_scale_cb, 6, 0, 1, 2)
  702. self.film_scalex_label = QtWidgets.QLabel('%s:' % _("X factor"))
  703. self.film_scalex_entry = FCDoubleSpinner(callback=self.confirmation_message)
  704. self.film_scalex_entry.set_range(-999.9999, 999.9999)
  705. self.film_scalex_entry.set_precision(self.decimals)
  706. self.film_scalex_entry.setSingleStep(0.01)
  707. grid0.addWidget(self.film_scalex_label, 7, 0)
  708. grid0.addWidget(self.film_scalex_entry, 7, 1)
  709. self.film_scaley_label = QtWidgets.QLabel('%s:' % _("Y factor"))
  710. self.film_scaley_entry = FCDoubleSpinner(callback=self.confirmation_message)
  711. self.film_scaley_entry.set_range(-999.9999, 999.9999)
  712. self.film_scaley_entry.set_precision(self.decimals)
  713. self.film_scaley_entry.setSingleStep(0.01)
  714. grid0.addWidget(self.film_scaley_label, 8, 0)
  715. grid0.addWidget(self.film_scaley_entry, 8, 1)
  716. self.ois_scale = OptionalHideInputSection(self.film_scale_cb,
  717. [
  718. self.film_scalex_label,
  719. self.film_scalex_entry,
  720. self.film_scaley_label,
  721. self.film_scaley_entry
  722. ])
  723. separator_line = QtWidgets.QFrame()
  724. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  725. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  726. grid0.addWidget(separator_line, 9, 0, 1, 2)
  727. # Skew Geometry
  728. self.film_skew_cb = FCCheckBox('%s' % _("Skew Film geometry"))
  729. self.film_skew_cb.setToolTip(
  730. _("Positive values will skew to the right\n"
  731. "while negative values will skew to the left.")
  732. )
  733. self.film_skew_cb.setStyleSheet(
  734. """
  735. QCheckBox {font-weight: bold; color: black}
  736. """
  737. )
  738. grid0.addWidget(self.film_skew_cb, 10, 0, 1, 2)
  739. self.film_skewx_label = QtWidgets.QLabel('%s:' % _("X angle"))
  740. self.film_skewx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  741. self.film_skewx_entry.set_range(-999.9999, 999.9999)
  742. self.film_skewx_entry.set_precision(self.decimals)
  743. self.film_skewx_entry.setSingleStep(0.01)
  744. grid0.addWidget(self.film_skewx_label, 11, 0)
  745. grid0.addWidget(self.film_skewx_entry, 11, 1)
  746. self.film_skewy_label = QtWidgets.QLabel('%s:' % _("Y angle"))
  747. self.film_skewy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  748. self.film_skewy_entry.set_range(-999.9999, 999.9999)
  749. self.film_skewy_entry.set_precision(self.decimals)
  750. self.film_skewy_entry.setSingleStep(0.01)
  751. grid0.addWidget(self.film_skewy_label, 12, 0)
  752. grid0.addWidget(self.film_skewy_entry, 12, 1)
  753. self.film_skew_ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  754. self.film_skew_ref_label.setToolTip(
  755. _("The reference point to be used as origin for the skew.\n"
  756. "It can be one of the four points of the geometry bounding box.")
  757. )
  758. self.film_skew_reference = RadioSet([{'label': _('Bottom Left'), 'value': 'bottomleft'},
  759. {'label': _('Top Left'), 'value': 'topleft'},
  760. {'label': _('Bottom Right'), 'value': 'bottomright'},
  761. {'label': _('Top right'), 'value': 'topright'}],
  762. orientation='vertical',
  763. stretch=False)
  764. grid0.addWidget(self.film_skew_ref_label, 13, 0)
  765. grid0.addWidget(self.film_skew_reference, 13, 1)
  766. self.ois_skew = OptionalHideInputSection(self.film_skew_cb,
  767. [
  768. self.film_skewx_label,
  769. self.film_skewx_entry,
  770. self.film_skewy_label,
  771. self.film_skewy_entry,
  772. self.film_skew_ref_label,
  773. self.film_skew_reference
  774. ])
  775. separator_line1 = QtWidgets.QFrame()
  776. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  777. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  778. grid0.addWidget(separator_line1, 14, 0, 1, 2)
  779. # Mirror Geometry
  780. self.film_mirror_cb = FCCheckBox('%s' % _("Mirror Film geometry"))
  781. self.film_mirror_cb.setToolTip(
  782. _("Mirror the film geometry on the selected axis or on both.")
  783. )
  784. self.film_mirror_cb.setStyleSheet(
  785. """
  786. QCheckBox {font-weight: bold; color: black}
  787. """
  788. )
  789. grid0.addWidget(self.film_mirror_cb, 15, 0, 1, 2)
  790. self.film_mirror_axis = RadioSet([{'label': _('None'), 'value': 'none'},
  791. {'label': _('X'), 'value': 'x'},
  792. {'label': _('Y'), 'value': 'y'},
  793. {'label': _('Both'), 'value': 'both'}],
  794. stretch=False)
  795. self.film_mirror_axis_label = QtWidgets.QLabel('%s:' % _("Mirror axis"))
  796. grid0.addWidget(self.film_mirror_axis_label, 16, 0)
  797. grid0.addWidget(self.film_mirror_axis, 16, 1)
  798. self.ois_mirror = OptionalHideInputSection(self.film_mirror_cb,
  799. [
  800. self.film_mirror_axis_label,
  801. self.film_mirror_axis
  802. ])
  803. separator_line2 = QtWidgets.QFrame()
  804. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  805. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  806. grid0.addWidget(separator_line2, 17, 0, 1, 2)
  807. self.film_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Film Parameters"))
  808. grid0.addWidget(self.film_param_label, 18, 0, 1, 2)
  809. # Scale Stroke size
  810. self.film_scale_stroke_entry = FCDoubleSpinner(callback=self.confirmation_message)
  811. self.film_scale_stroke_entry.set_range(-999.9999, 999.9999)
  812. self.film_scale_stroke_entry.setSingleStep(0.01)
  813. self.film_scale_stroke_entry.set_precision(self.decimals)
  814. self.film_scale_stroke_label = QtWidgets.QLabel('%s:' % _("Scale Stroke"))
  815. self.film_scale_stroke_label.setToolTip(
  816. _("Scale the line stroke thickness of each feature in the SVG file.\n"
  817. "It means that the line that envelope each SVG feature will be thicker or thinner,\n"
  818. "therefore the fine features may be more affected by this parameter.")
  819. )
  820. grid0.addWidget(self.film_scale_stroke_label, 19, 0)
  821. grid0.addWidget(self.film_scale_stroke_entry, 19, 1)
  822. # Film Type
  823. self.film_type = RadioSet([{'label': _('Positive'), 'value': 'pos'},
  824. {'label': _('Negative'), 'value': 'neg'}],
  825. stretch=False)
  826. self.film_type_label = QtWidgets.QLabel(_("Film Type:"))
  827. self.film_type_label.setToolTip(
  828. _("Generate a Positive black film or a Negative film.\n"
  829. "Positive means that it will print the features\n"
  830. "with black on a white canvas.\n"
  831. "Negative means that it will print the features\n"
  832. "with white on a black canvas.\n"
  833. "The Film format is SVG.")
  834. )
  835. grid0.addWidget(self.film_type_label, 21, 0)
  836. grid0.addWidget(self.film_type, 21, 1)
  837. # Boundary for negative film generation
  838. self.boundary_entry = FCDoubleSpinner(callback=self.confirmation_message)
  839. self.boundary_entry.set_range(-999.9999, 999.9999)
  840. self.boundary_entry.setSingleStep(0.01)
  841. self.boundary_entry.set_precision(self.decimals)
  842. self.boundary_label = QtWidgets.QLabel('%s:' % _("Border"))
  843. self.boundary_label.setToolTip(
  844. _("Specify a border around the object.\n"
  845. "Only for negative film.\n"
  846. "It helps if we use as a Box Object the same \n"
  847. "object as in Film Object. It will create a thick\n"
  848. "black bar around the actual print allowing for a\n"
  849. "better delimitation of the outline features which are of\n"
  850. "white color like the rest and which may confound with the\n"
  851. "surroundings if not for this border.")
  852. )
  853. grid0.addWidget(self.boundary_label, 22, 0)
  854. grid0.addWidget(self.boundary_entry, 22, 1)
  855. self.boundary_label.hide()
  856. self.boundary_entry.hide()
  857. # Punch Drill holes
  858. self.punch_cb = FCCheckBox(_("Punch drill holes"))
  859. self.punch_cb.setToolTip(_("When checked the generated film will have holes in pads when\n"
  860. "the generated film is positive. This is done to help drilling,\n"
  861. "when done manually."))
  862. grid0.addWidget(self.punch_cb, 23, 0, 1, 2)
  863. # this way I can hide/show the frame
  864. self.punch_frame = QtWidgets.QFrame()
  865. self.punch_frame.setContentsMargins(0, 0, 0, 0)
  866. self.layout.addWidget(self.punch_frame)
  867. punch_grid = QtWidgets.QGridLayout()
  868. punch_grid.setContentsMargins(0, 0, 0, 0)
  869. self.punch_frame.setLayout(punch_grid)
  870. punch_grid.setColumnStretch(0, 0)
  871. punch_grid.setColumnStretch(1, 1)
  872. self.ois_p = OptionalHideInputSection(self.punch_cb, [self.punch_frame])
  873. self.source_label = QtWidgets.QLabel('%s:' % _("Source"))
  874. self.source_label.setToolTip(
  875. _("The punch hole source can be:\n"
  876. "- Excellon -> an Excellon holes center will serve as reference.\n"
  877. "- Pad Center -> will try to use the pads center as reference.")
  878. )
  879. self.source_punch = RadioSet([{'label': _('Excellon'), 'value': 'exc'},
  880. {'label': _('Pad center'), 'value': 'pad'}],
  881. stretch=False)
  882. punch_grid.addWidget(self.source_label, 0, 0)
  883. punch_grid.addWidget(self.source_punch, 0, 1)
  884. self.exc_label = QtWidgets.QLabel('%s:' % _("Excellon Obj"))
  885. self.exc_label.setToolTip(
  886. _("Remove the geometry of Excellon from the Film to create the holes in pads.")
  887. )
  888. self.exc_combo = FCComboBox()
  889. self.exc_combo.setModel(self.app.collection)
  890. self.exc_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  891. self.exc_combo.is_last = True
  892. self.exc_combo.obj_type = "Excellon"
  893. punch_grid.addWidget(self.exc_label, 1, 0)
  894. punch_grid.addWidget(self.exc_combo, 1, 1)
  895. self.exc_label.hide()
  896. self.exc_combo.hide()
  897. self.punch_size_label = QtWidgets.QLabel('%s:' % _("Punch Size"))
  898. self.punch_size_label.setToolTip(_("The value here will control how big is the punch hole in the pads."))
  899. self.punch_size_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  900. self.punch_size_spinner.set_range(0, 999.9999)
  901. self.punch_size_spinner.setSingleStep(0.1)
  902. self.punch_size_spinner.set_precision(self.decimals)
  903. punch_grid.addWidget(self.punch_size_label, 2, 0)
  904. punch_grid.addWidget(self.punch_size_spinner, 2, 1)
  905. self.punch_size_label.hide()
  906. self.punch_size_spinner.hide()
  907. grid1 = QtWidgets.QGridLayout()
  908. self.layout.addLayout(grid1)
  909. grid1.setColumnStretch(0, 0)
  910. grid1.setColumnStretch(1, 1)
  911. separator_line3 = QtWidgets.QFrame()
  912. separator_line3.setFrameShape(QtWidgets.QFrame.HLine)
  913. separator_line3.setFrameShadow(QtWidgets.QFrame.Sunken)
  914. grid1.addWidget(separator_line3, 0, 0, 1, 2)
  915. # File type
  916. self.file_type_radio = RadioSet([{'label': _('SVG'), 'value': 'svg'},
  917. {'label': _('PNG'), 'value': 'png'},
  918. {'label': _('PDF'), 'value': 'pdf'}
  919. ], stretch=False)
  920. self.file_type_label = QtWidgets.QLabel(_("Film Type:"))
  921. self.file_type_label.setToolTip(
  922. _("The file type of the saved film. Can be:\n"
  923. "- 'SVG' -> open-source vectorial format\n"
  924. "- 'PNG' -> raster image\n"
  925. "- 'PDF' -> portable document format")
  926. )
  927. grid1.addWidget(self.file_type_label, 1, 0)
  928. grid1.addWidget(self.file_type_radio, 1, 1)
  929. # Page orientation
  930. self.orientation_label = QtWidgets.QLabel('%s:' % _("Page Orientation"))
  931. self.orientation_label.setToolTip(_("Can be:\n"
  932. "- Portrait\n"
  933. "- Landscape"))
  934. self.orientation_radio = RadioSet([{'label': _('Portrait'), 'value': 'p'},
  935. {'label': _('Landscape'), 'value': 'l'},
  936. ], stretch=False)
  937. grid1.addWidget(self.orientation_label, 2, 0)
  938. grid1.addWidget(self.orientation_radio, 2, 1)
  939. # Page Size
  940. self.pagesize_label = QtWidgets.QLabel('%s:' % _("Page Size"))
  941. self.pagesize_label.setToolTip(_("A selection of standard ISO 216 page sizes."))
  942. self.pagesize_combo = FCComboBox()
  943. self.pagesize = {}
  944. self.pagesize.update(
  945. {
  946. 'Bounds': None,
  947. 'A0': (841 * mm, 1189 * mm),
  948. 'A1': (594 * mm, 841 * mm),
  949. 'A2': (420 * mm, 594 * mm),
  950. 'A3': (297 * mm, 420 * mm),
  951. 'A4': (210 * mm, 297 * mm),
  952. 'A5': (148 * mm, 210 * mm),
  953. 'A6': (105 * mm, 148 * mm),
  954. 'A7': (74 * mm, 105 * mm),
  955. 'A8': (52 * mm, 74 * mm),
  956. 'A9': (37 * mm, 52 * mm),
  957. 'A10': (26 * mm, 37 * mm),
  958. 'B0': (1000 * mm, 1414 * mm),
  959. 'B1': (707 * mm, 1000 * mm),
  960. 'B2': (500 * mm, 707 * mm),
  961. 'B3': (353 * mm, 500 * mm),
  962. 'B4': (250 * mm, 353 * mm),
  963. 'B5': (176 * mm, 250 * mm),
  964. 'B6': (125 * mm, 176 * mm),
  965. 'B7': (88 * mm, 125 * mm),
  966. 'B8': (62 * mm, 88 * mm),
  967. 'B9': (44 * mm, 62 * mm),
  968. 'B10': (31 * mm, 44 * mm),
  969. 'C0': (917 * mm, 1297 * mm),
  970. 'C1': (648 * mm, 917 * mm),
  971. 'C2': (458 * mm, 648 * mm),
  972. 'C3': (324 * mm, 458 * mm),
  973. 'C4': (229 * mm, 324 * mm),
  974. 'C5': (162 * mm, 229 * mm),
  975. 'C6': (114 * mm, 162 * mm),
  976. 'C7': (81 * mm, 114 * mm),
  977. 'C8': (57 * mm, 81 * mm),
  978. 'C9': (40 * mm, 57 * mm),
  979. 'C10': (28 * mm, 40 * mm),
  980. # American paper sizes
  981. 'LETTER': (8.5 * inch, 11 * inch),
  982. 'LEGAL': (8.5 * inch, 14 * inch),
  983. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  984. # From https://en.wikipedia.org/wiki/Paper_size
  985. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  986. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  987. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  988. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  989. 'LEDGER': (17 * inch, 11 * inch),
  990. }
  991. )
  992. page_size_list = list(self.pagesize.keys())
  993. self.pagesize_combo.addItems(page_size_list)
  994. grid1.addWidget(self.pagesize_label, 3, 0)
  995. grid1.addWidget(self.pagesize_combo, 3, 1)
  996. self.on_film_type(val='hide')
  997. # Buttons
  998. self.film_object_button = QtWidgets.QPushButton(_("Save Film"))
  999. self.film_object_button.setToolTip(
  1000. _("Create a Film for the selected object, within\n"
  1001. "the specified box. Does not create a new \n "
  1002. "FlatCAM object, but directly save it in the\n"
  1003. "selected format.")
  1004. )
  1005. self.film_object_button.setStyleSheet("""
  1006. QPushButton
  1007. {
  1008. font-weight: bold;
  1009. }
  1010. """)
  1011. grid1.addWidget(self.film_object_button, 4, 0, 1, 2)
  1012. self.layout.addStretch()
  1013. # ## Reset Tool
  1014. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  1015. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  1016. self.reset_button.setToolTip(
  1017. _("Will reset the tool parameters.")
  1018. )
  1019. self.reset_button.setStyleSheet("""
  1020. QPushButton
  1021. {
  1022. font-weight: bold;
  1023. }
  1024. """)
  1025. self.layout.addWidget(self.reset_button)
  1026. # #################################### FINSIHED GUI ###########################
  1027. # #############################################################################
  1028. def on_film_type(self, val):
  1029. type_of_film = val
  1030. if type_of_film == 'neg':
  1031. self.boundary_label.show()
  1032. self.boundary_entry.show()
  1033. self.punch_cb.set_value(False) # required so the self.punch_frame it's hidden also by the signal emitted
  1034. self.punch_cb.hide()
  1035. else:
  1036. self.boundary_label.hide()
  1037. self.boundary_entry.hide()
  1038. self.punch_cb.show()
  1039. def on_file_type(self, val):
  1040. if val == 'pdf':
  1041. self.orientation_label.show()
  1042. self.orientation_radio.show()
  1043. self.pagesize_label.show()
  1044. self.pagesize_combo.show()
  1045. else:
  1046. self.orientation_label.hide()
  1047. self.orientation_radio.hide()
  1048. self.pagesize_label.hide()
  1049. self.pagesize_combo.hide()
  1050. def on_punch_source(self, val):
  1051. if val == 'pad' and self.punch_cb.get_value():
  1052. self.punch_size_label.show()
  1053. self.punch_size_spinner.show()
  1054. self.exc_label.hide()
  1055. self.exc_combo.hide()
  1056. else:
  1057. self.punch_size_label.hide()
  1058. self.punch_size_spinner.hide()
  1059. self.exc_label.show()
  1060. self.exc_combo.show()
  1061. if val == 'pad' and self.tf_type_obj_combo.get_value() == 'geo':
  1062. self.source_punch.set_value('exc')
  1063. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Using the Pad center does not work on Geometry objects. "
  1064. "Only a Gerber object has pads."))
  1065. def confirmation_message(self, accepted, minval, maxval):
  1066. if accepted is False:
  1067. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1068. self.decimals,
  1069. minval,
  1070. self.decimals,
  1071. maxval), False)
  1072. else:
  1073. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1074. def confirmation_message_int(self, accepted, minval, maxval):
  1075. if accepted is False:
  1076. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1077. (_("Edited value is out of range"), minval, maxval), False)
  1078. else:
  1079. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)