ToolFilm.py 60 KB

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