ToolFilm.py 56 KB

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