ToolFilm.py 66 KB

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