ToolFilm.py 56 KB

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