ToolFilm.py 49 KB

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