ToolFilm.py 66 KB

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