ToolFilm.py 54 KB

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