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