ToolFilm.py 66 KB

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