ToolFilm.py 55 KB

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