FlatCAMObj.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. from PyQt4 import QtCore
  2. from ObjectUI import *
  3. import FlatCAMApp
  4. import inspect # TODO: For debugging only.
  5. from camlib import *
  6. from FlatCAMCommon import LoudDict
  7. ########################################
  8. ## FlatCAMObj ##
  9. ########################################
  10. class FlatCAMObj(QtCore.QObject):
  11. """
  12. Base type of objects handled in FlatCAM. These become interactive
  13. in the GUI, can be plotted, and their options can be modified
  14. by the user in their respective forms.
  15. """
  16. # Instance of the application to which these are related.
  17. # The app should set this value.
  18. app = None
  19. def __init__(self, name):
  20. """
  21. :param name: Name of the object given by the user.
  22. :param ui: User interface to interact with the object.
  23. :type ui: ObjectUI
  24. :return: FlatCAMObj
  25. """
  26. QtCore.QObject.__init__(self)
  27. # View
  28. self.ui = None
  29. self.options = LoudDict(name=name)
  30. self.options.set_change_callback(self.on_options_change)
  31. self.form_fields = {}
  32. self.axes = None # Matplotlib axes
  33. self.kind = None # Override with proper name
  34. self.muted_ui = False
  35. # assert isinstance(self.ui, ObjectUI)
  36. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  37. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  38. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  39. def on_options_change(self, key):
  40. self.emit(QtCore.SIGNAL("optionChanged"), key)
  41. def set_ui(self, ui):
  42. self.ui = ui
  43. self.form_fields = {"name": self.ui.name_entry}
  44. assert isinstance(self.ui, ObjectUI)
  45. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  46. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  47. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  48. def __str__(self):
  49. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  50. def on_name_activate(self):
  51. old_name = copy(self.options["name"])
  52. new_name = self.ui.name_entry.get_value()
  53. self.options["name"] = self.ui.name_entry.get_value()
  54. self.app.info("Name changed from %s to %s" % (old_name, new_name))
  55. def on_offset_button_click(self):
  56. self.app.report_usage("obj_on_offset_button")
  57. self.read_form()
  58. vect = self.ui.offsetvector_entry.get_value()
  59. self.offset(vect)
  60. self.plot()
  61. def on_scale_button_click(self):
  62. self.app.report_usage("obj_on_scale_button")
  63. self.read_form()
  64. factor = self.ui.scale_entry.get_value()
  65. self.scale(factor)
  66. self.plot()
  67. def setup_axes(self, figure):
  68. """
  69. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  70. them to figure if not part of the figure. 4) Sets transparent
  71. background. 5) Sets 1:1 scale aspect ratio.
  72. :param figure: A Matplotlib.Figure on which to add/configure axes.
  73. :type figure: matplotlib.figure.Figure
  74. :return: None
  75. :rtype: None
  76. """
  77. if self.axes is None:
  78. FlatCAMApp.App.log.debug("setup_axes(): New axes")
  79. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  80. label=self.options["name"])
  81. elif self.axes not in figure.axes:
  82. FlatCAMApp.App.log.debug("setup_axes(): Clearing and attaching axes")
  83. self.axes.cla()
  84. figure.add_axes(self.axes)
  85. else:
  86. FlatCAMApp.App.log.debug("setup_axes(): Clearing Axes")
  87. self.axes.cla()
  88. # Remove all decoration. The app's axes will have
  89. # the ticks and grid.
  90. self.axes.set_frame_on(False) # No frame
  91. self.axes.set_xticks([]) # No tick
  92. self.axes.set_yticks([]) # No ticks
  93. self.axes.patch.set_visible(False) # No background
  94. self.axes.set_aspect(1)
  95. def to_form(self):
  96. """
  97. Copies options to the UI form.
  98. :return: None
  99. """
  100. for option in self.options:
  101. self.set_form_item(option)
  102. def read_form(self):
  103. """
  104. Reads form into ``self.options``.
  105. :return: None
  106. :rtype: None
  107. """
  108. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  109. for option in self.options:
  110. self.read_form_item(option)
  111. def build_ui(self):
  112. """
  113. Sets up the UI/form for this object.
  114. :return: None
  115. :rtype: None
  116. """
  117. self.muted_ui = True
  118. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  119. # Remove anything else in the box
  120. # box_children = self.app.ui.notebook.selected_contents.get_children()
  121. # for child in box_children:
  122. # self.app.ui.notebook.selected_contents.remove(child)
  123. # while self.app.ui.selected_layout.count():
  124. # self.app.ui.selected_layout.takeAt(0)
  125. # Put in the UI
  126. # box_selected.pack_start(sw, True, True, 0)
  127. # self.app.ui.notebook.selected_contents.add(self.ui)
  128. # self.app.ui.selected_layout.addWidget(self.ui)
  129. try:
  130. self.app.ui.selected_scroll_area.takeWidget()
  131. except:
  132. self.app.log.debug("Nothing to remove")
  133. self.app.ui.selected_scroll_area.setWidget(self.ui)
  134. self.to_form()
  135. self.muted_ui = False
  136. def set_form_item(self, option):
  137. """
  138. Copies the specified option to the UI form.
  139. :param option: Name of the option (Key in ``self.options``).
  140. :type option: str
  141. :return: None
  142. """
  143. try:
  144. self.form_fields[option].set_value(self.options[option])
  145. except KeyError:
  146. self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  147. def read_form_item(self, option):
  148. """
  149. Reads the specified option from the UI form into ``self.options``.
  150. :param option: Name of the option.
  151. :type option: str
  152. :return: None
  153. """
  154. try:
  155. self.options[option] = self.form_fields[option].get_value()
  156. except KeyError:
  157. self.app.log.warning("Failed to read option from field: %s" % option)
  158. def plot(self):
  159. """
  160. Plot this object (Extend this method to implement the actual plotting).
  161. Axes get created, appended to canvas and cleared before plotting.
  162. Call this in descendants before doing the plotting.
  163. :return: Whether to continue plotting or not depending on the "plot" option.
  164. :rtype: bool
  165. """
  166. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  167. # Axes must exist and be attached to canvas.
  168. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  169. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  170. if not self.options["plot"]:
  171. self.axes.cla()
  172. self.app.plotcanvas.auto_adjust_axes()
  173. return False
  174. # Clear axes or we will plot on top of them.
  175. self.axes.cla() # TODO: Thread safe?
  176. # GLib.idle_add(self.axes.cla)
  177. return True
  178. def serialize(self):
  179. """
  180. Returns a representation of the object as a dictionary so
  181. it can be later exported as JSON. Override this method.
  182. :return: Dictionary representing the object
  183. :rtype: dict
  184. """
  185. return
  186. def deserialize(self, obj_dict):
  187. """
  188. Re-builds an object from its serialized version.
  189. :param obj_dict: Dictionary representing a FlatCAMObj
  190. :type obj_dict: dict
  191. :return: None
  192. """
  193. return
  194. class FlatCAMGerber(FlatCAMObj, Gerber):
  195. """
  196. Represents Gerber code.
  197. """
  198. ui_type = GerberObjectUI
  199. def __init__(self, name):
  200. Gerber.__init__(self)
  201. FlatCAMObj.__init__(self, name)
  202. self.kind = "gerber"
  203. # The 'name' is already in self.options from FlatCAMObj
  204. # Automatically updates the UI
  205. self.options.update({
  206. "plot": True,
  207. "multicolored": False,
  208. "solid": False,
  209. "isotooldia": 0.016,
  210. "isopasses": 1,
  211. "isooverlap": 0.15,
  212. "cutouttooldia": 0.07,
  213. "cutoutmargin": 0.2,
  214. "cutoutgapsize": 0.15,
  215. "gaps": "tb",
  216. "noncoppermargin": 0.0,
  217. "noncopperrounded": False,
  218. "bboxmargin": 0.0,
  219. "bboxrounded": False
  220. })
  221. # Attributes to be included in serialization
  222. # Always append to it because it carries contents
  223. # from predecessors.
  224. self.ser_attrs += ['options', 'kind']
  225. # assert isinstance(self.ui, GerberObjectUI)
  226. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  227. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  228. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  229. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  230. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  231. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  232. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  233. def set_ui(self, ui):
  234. FlatCAMObj.set_ui(self, ui)
  235. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  236. self.form_fields.update({
  237. "plot": self.ui.plot_cb,
  238. "multicolored": self.ui.multicolored_cb,
  239. "solid": self.ui.solid_cb,
  240. "isotooldia": self.ui.iso_tool_dia_entry,
  241. "isopasses": self.ui.iso_width_entry,
  242. "isooverlap": self.ui.iso_overlap_entry,
  243. "cutouttooldia": self.ui.cutout_tooldia_entry,
  244. "cutoutmargin": self.ui.cutout_margin_entry,
  245. "cutoutgapsize": self.ui.cutout_gap_entry,
  246. "gaps": self.ui.gaps_radio,
  247. "noncoppermargin": self.ui.noncopper_margin_entry,
  248. "noncopperrounded": self.ui.noncopper_rounded_cb,
  249. "bboxmargin": self.ui.bbmargin_entry,
  250. "bboxrounded": self.ui.bbrounded_cb
  251. })
  252. assert isinstance(self.ui, GerberObjectUI)
  253. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  254. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  255. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  256. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  257. self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  258. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  259. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  260. def on_generatenoncopper_button_click(self, *args):
  261. self.app.report_usage("gerber_on_generatenoncopper_button")
  262. self.read_form()
  263. name = self.options["name"] + "_noncopper"
  264. def geo_init(geo_obj, app_obj):
  265. assert isinstance(geo_obj, FlatCAMGeometry)
  266. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  267. if not self.options["noncopperrounded"]:
  268. bounding_box = bounding_box.envelope
  269. non_copper = bounding_box.difference(self.solid_geometry)
  270. geo_obj.solid_geometry = non_copper
  271. # TODO: Check for None
  272. self.app.new_object("geometry", name, geo_init)
  273. def on_generatebb_button_click(self, *args):
  274. self.app.report_usage("gerber_on_generatebb_button")
  275. self.read_form()
  276. name = self.options["name"] + "_bbox"
  277. def geo_init(geo_obj, app_obj):
  278. assert isinstance(geo_obj, FlatCAMGeometry)
  279. # Bounding box with rounded corners
  280. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  281. if not self.options["bboxrounded"]: # Remove rounded corners
  282. bounding_box = bounding_box.envelope
  283. geo_obj.solid_geometry = bounding_box
  284. self.app.new_object("geometry", name, geo_init)
  285. def on_generatecutout_button_click(self, *args):
  286. self.app.report_usage("gerber_on_generatecutout_button")
  287. self.read_form()
  288. name = self.options["name"] + "_cutout"
  289. def geo_init(geo_obj, app_obj):
  290. margin = self.options["cutoutmargin"] + self.options["cutouttooldia"]/2
  291. gap_size = self.options["cutoutgapsize"] + self.options["cutouttooldia"]
  292. minx, miny, maxx, maxy = self.bounds()
  293. minx -= margin
  294. maxx += margin
  295. miny -= margin
  296. maxy += margin
  297. midx = 0.5 * (minx + maxx)
  298. midy = 0.5 * (miny + maxy)
  299. hgap = 0.5 * gap_size
  300. pts = [[midx - hgap, maxy],
  301. [minx, maxy],
  302. [minx, midy + hgap],
  303. [minx, midy - hgap],
  304. [minx, miny],
  305. [midx - hgap, miny],
  306. [midx + hgap, miny],
  307. [maxx, miny],
  308. [maxx, midy - hgap],
  309. [maxx, midy + hgap],
  310. [maxx, maxy],
  311. [midx + hgap, maxy]]
  312. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  313. [pts[6], pts[7], pts[10], pts[11]]],
  314. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  315. [pts[3], pts[4], pts[7], pts[8]]],
  316. "4": [[pts[0], pts[1], pts[2]],
  317. [pts[3], pts[4], pts[5]],
  318. [pts[6], pts[7], pts[8]],
  319. [pts[9], pts[10], pts[11]]]}
  320. cuts = cases[self.options['gaps']]
  321. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  322. # TODO: Check for None
  323. self.app.new_object("geometry", name, geo_init)
  324. def on_iso_button_click(self, *args):
  325. self.app.report_usage("gerber_on_iso_button")
  326. self.read_form()
  327. self.isolate()
  328. def follow(self, outname=None):
  329. """
  330. Creates a geometry object "following" the gerber paths.
  331. :return: None
  332. """
  333. default_name = self.options["name"] + "_follow"
  334. follow_name = outname or default_name
  335. def follow_init(follow_obj, app_obj):
  336. # Propagate options
  337. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  338. follow_obj.solid_geometry = self.solid_geometry
  339. app_obj.info("Follow geometry created: %s" % follow_obj.options["name"])
  340. # TODO: Do something if this is None. Offer changing name?
  341. self.app.new_object("geometry", follow_name, follow_init)
  342. def isolate(self, dia=None, passes=None, overlap=None, outname=None):
  343. """
  344. Creates an isolation routing geometry object in the project.
  345. :param dia: Tool diameter
  346. :param passes: Number of tool widths to cut
  347. :param overlap: Overlap between passes in fraction of tool diameter
  348. :param outname: Base name of the output object
  349. :return: None
  350. """
  351. if dia is None:
  352. dia = self.options["isotooldia"]
  353. if passes is None:
  354. passes = int(self.options["isopasses"])
  355. if overlap is None:
  356. overlap = self.options["isooverlap"] * dia
  357. base_name = self.options["name"] + "_iso"
  358. base_name = outname or base_name
  359. for i in range(passes):
  360. offset = (2*i + 1)/2.0 * dia - i*overlap
  361. if passes > 1:
  362. iso_name = base_name + str(i+1)
  363. else:
  364. iso_name = base_name
  365. # TODO: This is ugly. Create way to pass data into init function.
  366. def iso_init(geo_obj, app_obj):
  367. # Propagate options
  368. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  369. geo_obj.solid_geometry = self.isolation_geometry(offset)
  370. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  371. # TODO: Do something if this is None. Offer changing name?
  372. self.app.new_object("geometry", iso_name, iso_init)
  373. def on_plot_cb_click(self, *args):
  374. if self.muted_ui:
  375. return
  376. self.read_form_item('plot')
  377. self.plot()
  378. def on_solid_cb_click(self, *args):
  379. if self.muted_ui:
  380. return
  381. self.read_form_item('solid')
  382. self.plot()
  383. def on_multicolored_cb_click(self, *args):
  384. if self.muted_ui:
  385. return
  386. self.read_form_item('multicolored')
  387. self.plot()
  388. def convert_units(self, units):
  389. """
  390. Converts the units of the object by scaling dimensions in all geometry
  391. and options.
  392. :param units: Units to which to convert the object: "IN" or "MM".
  393. :type units: str
  394. :return: None
  395. :rtype: None
  396. """
  397. factor = Gerber.convert_units(self, units)
  398. self.options['isotooldia'] *= factor
  399. self.options['cutoutmargin'] *= factor
  400. self.options['cutoutgapsize'] *= factor
  401. self.options['noncoppermargin'] *= factor
  402. self.options['bboxmargin'] *= factor
  403. def plot(self):
  404. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  405. # Does all the required setup and returns False
  406. # if the 'ptint' option is set to False.
  407. if not FlatCAMObj.plot(self):
  408. return
  409. geometry = self.solid_geometry
  410. # Make sure geometry is iterable.
  411. try:
  412. _ = iter(geometry)
  413. except TypeError:
  414. geometry = [geometry]
  415. if self.options["multicolored"]:
  416. linespec = '-'
  417. else:
  418. linespec = 'k-'
  419. if self.options["solid"]:
  420. for poly in geometry:
  421. # TODO: Too many things hardcoded.
  422. try:
  423. patch = PolygonPatch(poly,
  424. facecolor="#BBF268",
  425. edgecolor="#006E20",
  426. alpha=0.75,
  427. zorder=2)
  428. self.axes.add_patch(patch)
  429. except AssertionError:
  430. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  431. FlatCAMApp.App.log.warning(str(poly))
  432. else:
  433. for poly in geometry:
  434. x, y = poly.exterior.xy
  435. self.axes.plot(x, y, linespec)
  436. for ints in poly.interiors:
  437. x, y = ints.coords.xy
  438. self.axes.plot(x, y, linespec)
  439. self.app.plotcanvas.auto_adjust_axes()
  440. #GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  441. #self.emit(QtCore.SIGNAL("plotChanged"), self)
  442. def serialize(self):
  443. return {
  444. "options": self.options,
  445. "kind": self.kind
  446. }
  447. class FlatCAMExcellon(FlatCAMObj, Excellon):
  448. """
  449. Represents Excellon/Drill code.
  450. """
  451. ui_type = ExcellonObjectUI
  452. def __init__(self, name):
  453. Excellon.__init__(self)
  454. FlatCAMObj.__init__(self, name)
  455. self.kind = "excellon"
  456. self.options.update({
  457. "plot": True,
  458. "solid": False,
  459. "drillz": -0.1,
  460. "travelz": 0.1,
  461. "feedrate": 5.0,
  462. # "toolselection": ""
  463. })
  464. # TODO: Document this.
  465. self.tool_cbs = {}
  466. # Attributes to be included in serialization
  467. # Always append to it because it carries contents
  468. # from predecessors.
  469. self.ser_attrs += ['options', 'kind']
  470. def build_ui(self):
  471. FlatCAMObj.build_ui(self)
  472. # Populate tool list
  473. n = len(self.tools)
  474. self.ui.tools_table.setColumnCount(2)
  475. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
  476. self.ui.tools_table.setRowCount(n)
  477. self.ui.tools_table.setSortingEnabled(False)
  478. i = 0
  479. for tool in self.tools:
  480. id = QtGui.QTableWidgetItem(tool)
  481. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  482. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  483. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  484. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  485. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  486. i += 1
  487. self.ui.tools_table.resizeColumnsToContents()
  488. self.ui.tools_table.resizeRowsToContents()
  489. self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
  490. self.ui.tools_table.verticalHeader().hide()
  491. self.ui.tools_table.setSortingEnabled(True)
  492. def set_ui(self, ui):
  493. FlatCAMObj.set_ui(self, ui)
  494. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  495. self.form_fields.update({
  496. "plot": self.ui.plot_cb,
  497. "solid": self.ui.solid_cb,
  498. "drillz": self.ui.cutz_entry,
  499. "travelz": self.ui.travelz_entry,
  500. "feedrate": self.ui.feedrate_entry,
  501. # "toolselection": self.ui.tools_entry
  502. })
  503. assert isinstance(self.ui, ExcellonObjectUI)
  504. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  505. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  506. # self.ui.choose_tools_button.clicked.connect(self.show_tool_chooser)
  507. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  508. def on_create_cncjob_button_click(self, *args):
  509. self.app.report_usage("excellon_on_create_cncjob_button")
  510. self.read_form()
  511. # Get the tools from the list
  512. tools = [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  513. if len(tools) == 0:
  514. self.app.inform.emit("Please select one or more tools from the list and try again.")
  515. return
  516. job_name = self.options["name"] + "_cnc"
  517. # Object initialization function for app.new_object()
  518. def job_init(job_obj, app_obj):
  519. assert isinstance(job_obj, FlatCAMCNCjob)
  520. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  521. app_obj.progress.emit(20)
  522. job_obj.z_cut = self.options["drillz"]
  523. job_obj.z_move = self.options["travelz"]
  524. job_obj.feedrate = self.options["feedrate"]
  525. # There could be more than one drill size...
  526. # job_obj.tooldia = # TODO: duplicate variable!
  527. # job_obj.options["tooldia"] =
  528. tools_csv = ','.join(tools)
  529. # job_obj.generate_from_excellon_by_tool(self, self.options["toolselection"])
  530. job_obj.generate_from_excellon_by_tool(self, tools_csv)
  531. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  532. app_obj.progress.emit(50)
  533. job_obj.gcode_parse()
  534. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  535. app_obj.progress.emit(60)
  536. job_obj.create_geometry()
  537. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  538. app_obj.progress.emit(80)
  539. # To be run in separate thread
  540. def job_thread(app_obj):
  541. app_obj.new_object("cncjob", job_name, job_init)
  542. # GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  543. app_obj.progress.emit(100)
  544. # GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  545. # Send to worker
  546. # self.app.worker.add_task(job_thread, [self.app])
  547. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  548. def on_plot_cb_click(self, *args):
  549. if self.muted_ui:
  550. return
  551. self.read_form_item('plot')
  552. self.plot()
  553. def on_solid_cb_click(self, *args):
  554. if self.muted_ui:
  555. return
  556. self.read_form_item('solid')
  557. self.plot()
  558. def convert_units(self, units):
  559. factor = Excellon.convert_units(self, units)
  560. self.options['drillz'] *= factor
  561. self.options['travelz'] *= factor
  562. self.options['feedrate'] *= factor
  563. def plot(self):
  564. # Does all the required setup and returns False
  565. # if the 'ptint' option is set to False.
  566. if not FlatCAMObj.plot(self):
  567. return
  568. try:
  569. _ = iter(self.solid_geometry)
  570. except TypeError:
  571. self.solid_geometry = [self.solid_geometry]
  572. # Plot excellon (All polygons?)
  573. if self.options["solid"]:
  574. for geo in self.solid_geometry:
  575. patch = PolygonPatch(geo,
  576. facecolor="#C40000",
  577. edgecolor="#750000",
  578. alpha=0.75,
  579. zorder=3)
  580. self.axes.add_patch(patch)
  581. else:
  582. for geo in self.solid_geometry:
  583. x, y = geo.exterior.coords.xy
  584. self.axes.plot(x, y, 'r-')
  585. for ints in geo.interiors:
  586. x, y = ints.coords.xy
  587. self.axes.plot(x, y, 'g-')
  588. self.app.plotcanvas.auto_adjust_axes()
  589. # GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  590. # self.emit(QtCore.SIGNAL("plotChanged"), self)
  591. def show_tool_chooser(self):
  592. # win = Gtk.Window()
  593. # box = Gtk.Box(spacing=2)
  594. # box.set_orientation(Gtk.Orientation(1))
  595. # win.add(box)
  596. # for tool in self.tools:
  597. # self.tool_cbs[tool] = Gtk.CheckButton(label=tool + ": " + str(self.tools[tool]))
  598. # box.pack_start(self.tool_cbs[tool], False, False, 1)
  599. # button = Gtk.Button(label="Accept")
  600. # box.pack_start(button, False, False, 1)
  601. # win.show_all()
  602. #
  603. # def on_accept(widget):
  604. # win.destroy()
  605. # tool_list = []
  606. # for toolx in self.tool_cbs:
  607. # if self.tool_cbs[toolx].get_active():
  608. # tool_list.append(toolx)
  609. # self.options["toolselection"] = ", ".join(tool_list)
  610. # self.to_form()
  611. #
  612. # button.connect("activate", on_accept)
  613. # button.connect("clicked", on_accept)
  614. return
  615. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  616. """
  617. Represents G-Code.
  618. """
  619. ui_type = CNCObjectUI
  620. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  621. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  622. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  623. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  624. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia)
  625. FlatCAMObj.__init__(self, name)
  626. self.kind = "cncjob"
  627. self.options.update({
  628. "plot": True,
  629. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  630. "append": ""
  631. })
  632. # Attributes to be included in serialization
  633. # Always append to it because it carries contents
  634. # from predecessors.
  635. self.ser_attrs += ['options', 'kind']
  636. def set_ui(self, ui):
  637. FlatCAMObj.set_ui(self, ui)
  638. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  639. assert isinstance(self.ui, CNCObjectUI)
  640. self.form_fields.update({
  641. "plot": self.ui.plot_cb,
  642. "tooldia": self.ui.tooldia_entry,
  643. "append": self.ui.append_text
  644. })
  645. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  646. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  647. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  648. def on_updateplot_button_click(self, *args):
  649. """
  650. Callback for the "Updata Plot" button. Reads the form for updates
  651. and plots the object.
  652. """
  653. self.read_form()
  654. self.plot()
  655. def on_exportgcode_button_click(self, *args):
  656. self.app.report_usage("cncjob_on_exportgcode_button")
  657. try:
  658. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  659. directory=self.app.last_folder)
  660. except TypeError:
  661. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...")
  662. postamble = str(self.ui.append_text.get_value())
  663. self.export_gcode(filename, preamble='', postamble=postamble)
  664. def export_gcode(self, filename, preamble='', postamble=''):
  665. f = open(filename, 'w')
  666. f.write(preamble + '\n' + self.gcode + "\n" + postamble)
  667. f.close()
  668. self.app.file_opened.emit("cncjob", filename)
  669. self.app.inform.emit("Saved to: " + filename)
  670. def on_plot_cb_click(self, *args):
  671. if self.muted_ui:
  672. return
  673. self.read_form_item('plot')
  674. self.plot()
  675. def plot(self):
  676. # Does all the required setup and returns False
  677. # if the 'ptint' option is set to False.
  678. if not FlatCAMObj.plot(self):
  679. return
  680. self.plot2(self.axes, tooldia=self.options["tooldia"])
  681. self.app.plotcanvas.auto_adjust_axes()
  682. def convert_units(self, units):
  683. factor = CNCjob.convert_units(self, units)
  684. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  685. self.options["tooldia"] *= factor
  686. class FlatCAMGeometry(FlatCAMObj, Geometry):
  687. """
  688. Geometric object not associated with a specific
  689. format.
  690. """
  691. ui_type = GeometryObjectUI
  692. def __init__(self, name):
  693. FlatCAMObj.__init__(self, name)
  694. Geometry.__init__(self)
  695. self.kind = "geometry"
  696. self.options.update({
  697. "plot": True,
  698. # "solid": False,
  699. # "multicolored": False,
  700. "cutz": -0.002,
  701. "travelz": 0.1,
  702. "feedrate": 5.0,
  703. "cnctooldia": 0.4 / 25.4,
  704. "painttooldia": 0.0625,
  705. "paintoverlap": 0.15,
  706. "paintmargin": 0.01
  707. })
  708. # Attributes to be included in serialization
  709. # Always append to it because it carries contents
  710. # from predecessors.
  711. self.ser_attrs += ['options', 'kind']
  712. def set_ui(self, ui):
  713. FlatCAMObj.set_ui(self, ui)
  714. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  715. assert isinstance(self.ui, GeometryObjectUI)
  716. self.form_fields.update({
  717. "plot": self.ui.plot_cb,
  718. # "solid": self.ui.sol,
  719. # "multicolored": self.ui.,
  720. "cutz": self.ui.cutz_entry,
  721. "travelz": self.ui.travelz_entry,
  722. "feedrate": self.ui.cncfeedrate_entry,
  723. "cnctooldia": self.ui.cnctooldia_entry,
  724. "painttooldia": self.ui.painttooldia_entry,
  725. "paintoverlap": self.ui.paintoverlap_entry,
  726. "paintmargin": self.ui.paintmargin_entry
  727. })
  728. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  729. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  730. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  731. def on_paint_button_click(self, *args):
  732. self.app.report_usage("geometry_on_paint_button")
  733. self.app.info("Click inside the desired polygon.")
  734. self.read_form()
  735. tooldia = self.options["painttooldia"]
  736. overlap = self.options["paintoverlap"]
  737. # Connection ID for the click event
  738. subscription = None
  739. # To be called after clicking on the plot.
  740. def doit(event):
  741. self.app.plotcanvas.mpl_disconnect(subscription)
  742. point = [event.xdata, event.ydata]
  743. self.paint_poly(point, tooldia, overlap)
  744. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  745. def paint_poly(self, inside_pt, tooldia, overlap):
  746. poly = find_polygon(self.solid_geometry, inside_pt)
  747. # Initializes the new geometry object
  748. def gen_paintarea(geo_obj, app_obj):
  749. assert isinstance(geo_obj, FlatCAMGeometry)
  750. #assert isinstance(app_obj, App)
  751. cp = clear_poly(poly.buffer(-self.options["paintmargin"]), tooldia, overlap)
  752. geo_obj.solid_geometry = cp
  753. geo_obj.options["cnctooldia"] = tooldia
  754. name = self.options["name"] + "_paint"
  755. self.app.new_object("geometry", name, gen_paintarea)
  756. def on_generatecnc_button_click(self, *args):
  757. self.app.report_usage("geometry_on_generatecnc_button")
  758. self.read_form()
  759. self.generatecncjob()
  760. def generatecncjob(self, z_cut=None, z_move=None,
  761. feedrate=None, tooldia=None, outname=None):
  762. outname = outname if outname is not None else self.options["name"] + "_cnc"
  763. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  764. z_move = z_move if z_move is not None else self.options["travelz"]
  765. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  766. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  767. # Object initialization function for app.new_object()
  768. # RUNNING ON SEPARATE THREAD!
  769. def job_init(job_obj, app_obj):
  770. assert isinstance(job_obj, FlatCAMCNCjob)
  771. # Propagate options
  772. job_obj.options["tooldia"] = tooldia
  773. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  774. app_obj.progress.emit(20)
  775. job_obj.z_cut = z_cut
  776. job_obj.z_move = z_move
  777. job_obj.feedrate = feedrate
  778. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry..."))
  779. app_obj.progress.emit(40)
  780. # TODO: The tolerance should not be hard coded. Just for testing.
  781. job_obj.generate_from_geometry(self, tolerance=0.0005)
  782. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  783. app_obj.progress.emit(50)
  784. job_obj.gcode_parse()
  785. # TODO: job_obj.create_geometry creates stuff that is not used.
  786. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  787. #job_obj.create_geometry()
  788. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  789. app_obj.progress.emit(80)
  790. # To be run in separate thread
  791. def job_thread(app_obj):
  792. app_obj.new_object("cncjob", outname, job_init)
  793. # GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name))
  794. # GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  795. # GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, "Idle"))
  796. app_obj.inform.emit("CNCjob created: %s" % outname)
  797. app_obj.progress.emit(100)
  798. # Send to worker
  799. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  800. def on_plot_cb_click(self, *args): # TODO: args not needed
  801. if self.muted_ui:
  802. return
  803. self.read_form_item('plot')
  804. self.plot()
  805. def scale(self, factor):
  806. """
  807. Scales all geometry by a given factor.
  808. :param factor: Factor by which to scale the object's geometry/
  809. :type factor: float
  810. :return: None
  811. :rtype: None
  812. """
  813. if type(self.solid_geometry) == list:
  814. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  815. for g in self.solid_geometry]
  816. else:
  817. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  818. origin=(0, 0))
  819. def offset(self, vect):
  820. """
  821. Offsets all geometry by a given vector/
  822. :param vect: (x, y) vector by which to offset the object's geometry.
  823. :type vect: tuple
  824. :return: None
  825. :rtype: None
  826. """
  827. dx, dy = vect
  828. if type(self.solid_geometry) == list:
  829. self.solid_geometry = [affinity.translate(g, xoff=dx, yoff=dy)
  830. for g in self.solid_geometry]
  831. else:
  832. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  833. def convert_units(self, units):
  834. factor = Geometry.convert_units(self, units)
  835. self.options['cutz'] *= factor
  836. self.options['travelz'] *= factor
  837. self.options['feedrate'] *= factor
  838. self.options['cnctooldia'] *= factor
  839. self.options['painttooldia'] *= factor
  840. self.options['paintmargin'] *= factor
  841. return factor
  842. def plot(self):
  843. """
  844. Plots the object into its axes. If None, of if the axes
  845. are not part of the app's figure, it fetches new ones.
  846. :return: None
  847. """
  848. # Does all the required setup and returns False
  849. # if the 'ptint' option is set to False.
  850. if not FlatCAMObj.plot(self):
  851. return
  852. # Make sure solid_geometry is iterable.
  853. # TODO: This method should not modify the object !!!
  854. try:
  855. _ = iter(self.solid_geometry)
  856. except TypeError:
  857. if self.solid_geometry is None:
  858. self.solid_geometry = []
  859. else:
  860. self.solid_geometry = [self.solid_geometry]
  861. for geo in self.solid_geometry:
  862. if type(geo) == Polygon:
  863. x, y = geo.exterior.coords.xy
  864. self.axes.plot(x, y, 'r-')
  865. for ints in geo.interiors:
  866. x, y = ints.coords.xy
  867. self.axes.plot(x, y, 'r-')
  868. continue
  869. if type(geo) == LineString or type(geo) == LinearRing:
  870. x, y = geo.coords.xy
  871. self.axes.plot(x, y, 'r-')
  872. continue
  873. if type(geo) == MultiPolygon:
  874. for poly in geo:
  875. x, y = poly.exterior.coords.xy
  876. self.axes.plot(x, y, 'r-')
  877. for ints in poly.interiors:
  878. x, y = ints.coords.xy
  879. self.axes.plot(x, y, 'r-')
  880. continue
  881. FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  882. self.app.plotcanvas.auto_adjust_axes()
  883. # GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  884. # self.emit(QtCore.SIGNAL("plotChanged"), self)