FlatCAMObj.py 36 KB

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