ToolFilm.py 66 KB

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