ToolFilm.py 56 KB

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