FlatCAMObj.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. from FlatCAMDraw import FlatCAMDraw
  8. ########################################
  9. ## FlatCAMObj ##
  10. ########################################
  11. class FlatCAMObj(QtCore.QObject):
  12. """
  13. Base type of objects handled in FlatCAM. These become interactive
  14. in the GUI, can be plotted, and their options can be modified
  15. by the user in their respective forms.
  16. """
  17. # Instance of the application to which these are related.
  18. # The app should set this value.
  19. app = None
  20. def __init__(self, name):
  21. """
  22. :param name: Name of the object given by the user.
  23. :return: FlatCAMObj
  24. """
  25. QtCore.QObject.__init__(self)
  26. # View
  27. self.ui = None
  28. self.options = LoudDict(name=name)
  29. self.options.set_change_callback(self.on_options_change)
  30. self.form_fields = {}
  31. self.axes = None # Matplotlib axes
  32. self.kind = None # Override with proper name
  33. self.muted_ui = False
  34. # assert isinstance(self.ui, ObjectUI)
  35. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  36. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  37. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  38. def on_options_change(self, key):
  39. self.emit(QtCore.SIGNAL("optionChanged"), key)
  40. def set_ui(self, ui):
  41. self.ui = ui
  42. self.form_fields = {"name": self.ui.name_entry}
  43. assert isinstance(self.ui, ObjectUI)
  44. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  45. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  46. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  47. def __str__(self):
  48. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  49. def on_name_activate(self):
  50. old_name = copy(self.options["name"])
  51. new_name = self.ui.name_entry.get_value()
  52. self.options["name"] = self.ui.name_entry.get_value()
  53. self.app.info("Name changed from %s to %s" % (old_name, new_name))
  54. def on_offset_button_click(self):
  55. self.app.report_usage("obj_on_offset_button")
  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.app.report_usage("obj_on_scale_button")
  62. self.read_form()
  63. factor = self.ui.scale_entry.get_value()
  64. self.scale(factor)
  65. self.plot()
  66. def setup_axes(self, figure):
  67. """
  68. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  69. them to figure if not part of the figure. 4) Sets transparent
  70. background. 5) Sets 1:1 scale aspect ratio.
  71. :param figure: A Matplotlib.Figure on which to add/configure axes.
  72. :type figure: matplotlib.figure.Figure
  73. :return: None
  74. :rtype: None
  75. """
  76. if self.axes is None:
  77. FlatCAMApp.App.log.debug("setup_axes(): New axes")
  78. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  79. label=self.options["name"])
  80. elif self.axes not in figure.axes:
  81. FlatCAMApp.App.log.debug("setup_axes(): Clearing and attaching axes")
  82. self.axes.cla()
  83. figure.add_axes(self.axes)
  84. else:
  85. FlatCAMApp.App.log.debug("setup_axes(): Clearing Axes")
  86. self.axes.cla()
  87. # Remove all decoration. The app's axes will have
  88. # the ticks and grid.
  89. self.axes.set_frame_on(False) # No frame
  90. self.axes.set_xticks([]) # No tick
  91. self.axes.set_yticks([]) # No ticks
  92. self.axes.patch.set_visible(False) # No background
  93. self.axes.set_aspect(1)
  94. def to_form(self):
  95. """
  96. Copies options to the UI form.
  97. :return: None
  98. """
  99. for option in self.options:
  100. self.set_form_item(option)
  101. def read_form(self):
  102. """
  103. Reads form into ``self.options``.
  104. :return: None
  105. :rtype: None
  106. """
  107. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  108. for option in self.options:
  109. self.read_form_item(option)
  110. def build_ui(self):
  111. """
  112. Sets up the UI/form for this object.
  113. :return: None
  114. :rtype: None
  115. """
  116. self.muted_ui = True
  117. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  118. # Remove anything else in the box
  119. # box_children = self.app.ui.notebook.selected_contents.get_children()
  120. # for child in box_children:
  121. # self.app.ui.notebook.selected_contents.remove(child)
  122. # while self.app.ui.selected_layout.count():
  123. # self.app.ui.selected_layout.takeAt(0)
  124. # Put in the UI
  125. # box_selected.pack_start(sw, True, True, 0)
  126. # self.app.ui.notebook.selected_contents.add(self.ui)
  127. # self.app.ui.selected_layout.addWidget(self.ui)
  128. try:
  129. self.app.ui.selected_scroll_area.takeWidget()
  130. except:
  131. self.app.log.debug("Nothing to remove")
  132. self.app.ui.selected_scroll_area.setWidget(self.ui)
  133. self.to_form()
  134. self.muted_ui = False
  135. def set_form_item(self, option):
  136. """
  137. Copies the specified option to the UI form.
  138. :param option: Name of the option (Key in ``self.options``).
  139. :type option: str
  140. :return: None
  141. """
  142. try:
  143. self.form_fields[option].set_value(self.options[option])
  144. except KeyError:
  145. self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  146. def read_form_item(self, option):
  147. """
  148. Reads the specified option from the UI form into ``self.options``.
  149. :param option: Name of the option.
  150. :type option: str
  151. :return: None
  152. """
  153. try:
  154. self.options[option] = self.form_fields[option].get_value()
  155. except KeyError:
  156. self.app.log.warning("Failed to read option from field: %s" % option)
  157. def plot(self):
  158. """
  159. Plot this object (Extend this method to implement the actual plotting).
  160. Axes get created, appended to canvas and cleared before plotting.
  161. Call this in descendants before doing the plotting.
  162. :return: Whether to continue plotting or not depending on the "plot" option.
  163. :rtype: bool
  164. """
  165. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  166. # Axes must exist and be attached to canvas.
  167. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  168. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  169. if not self.options["plot"]:
  170. self.axes.cla()
  171. self.app.plotcanvas.auto_adjust_axes()
  172. return False
  173. # Clear axes or we will plot on top of them.
  174. self.axes.cla() # TODO: Thread safe?
  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. "combine_passes": True,
  211. "cutouttooldia": 0.07,
  212. "cutoutmargin": 0.2,
  213. "cutoutgapsize": 0.15,
  214. "gaps": "tb",
  215. "noncoppermargin": 0.0,
  216. "noncopperrounded": False,
  217. "bboxmargin": 0.0,
  218. "bboxrounded": False
  219. })
  220. # Attributes to be included in serialization
  221. # Always append to it because it carries contents
  222. # from predecessors.
  223. self.ser_attrs += ['options', 'kind']
  224. # assert isinstance(self.ui, GerberObjectUI)
  225. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  226. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  227. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  228. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  229. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  230. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  231. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  232. def set_ui(self, ui):
  233. FlatCAMObj.set_ui(self, ui)
  234. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  235. self.form_fields.update({
  236. "plot": self.ui.plot_cb,
  237. "multicolored": self.ui.multicolored_cb,
  238. "solid": self.ui.solid_cb,
  239. "isotooldia": self.ui.iso_tool_dia_entry,
  240. "isopasses": self.ui.iso_width_entry,
  241. "isooverlap": self.ui.iso_overlap_entry,
  242. "combine_passes":self.ui.combine_passes_cb,
  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, combine=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"]
  357. if combine is None:
  358. combine = self.options["combine_passes"]
  359. else:
  360. combine = bool(combine)
  361. base_name = self.options["name"] + "_iso"
  362. base_name = outname or base_name
  363. if (combine):
  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 = []
  370. for i in range(passes):
  371. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  372. geo_obj.solid_geometry.append(self.isolation_geometry(offset))
  373. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  374. # TODO: Do something if this is None. Offer changing name?
  375. self.app.new_object("geometry", iso_name, iso_init)
  376. else:
  377. for i in range(passes):
  378. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  379. if passes > 1:
  380. iso_name = base_name + str(i + 1)
  381. else:
  382. iso_name = base_name
  383. # TODO: This is ugly. Create way to pass data into init function.
  384. def iso_init(geo_obj, app_obj):
  385. # Propagate options
  386. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  387. geo_obj.solid_geometry = self.isolation_geometry(offset)
  388. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  389. # TODO: Do something if this is None. Offer changing name?
  390. self.app.new_object("geometry", iso_name, iso_init)
  391. def on_plot_cb_click(self, *args):
  392. if self.muted_ui:
  393. return
  394. self.read_form_item('plot')
  395. self.plot()
  396. def on_solid_cb_click(self, *args):
  397. if self.muted_ui:
  398. return
  399. self.read_form_item('solid')
  400. self.plot()
  401. def on_multicolored_cb_click(self, *args):
  402. if self.muted_ui:
  403. return
  404. self.read_form_item('multicolored')
  405. self.plot()
  406. def convert_units(self, units):
  407. """
  408. Converts the units of the object by scaling dimensions in all geometry
  409. and options.
  410. :param units: Units to which to convert the object: "IN" or "MM".
  411. :type units: str
  412. :return: None
  413. :rtype: None
  414. """
  415. factor = Gerber.convert_units(self, units)
  416. self.options['isotooldia'] *= factor
  417. self.options['cutoutmargin'] *= factor
  418. self.options['cutoutgapsize'] *= factor
  419. self.options['noncoppermargin'] *= factor
  420. self.options['bboxmargin'] *= factor
  421. def plot(self):
  422. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  423. # Does all the required setup and returns False
  424. # if the 'ptint' option is set to False.
  425. if not FlatCAMObj.plot(self):
  426. return
  427. geometry = self.solid_geometry
  428. # Make sure geometry is iterable.
  429. try:
  430. _ = iter(geometry)
  431. except TypeError:
  432. geometry = [geometry]
  433. if self.options["multicolored"]:
  434. linespec = '-'
  435. else:
  436. linespec = 'k-'
  437. if self.options["solid"]:
  438. for poly in geometry:
  439. # TODO: Too many things hardcoded.
  440. try:
  441. patch = PolygonPatch(poly,
  442. facecolor="#BBF268",
  443. edgecolor="#006E20",
  444. alpha=0.75,
  445. zorder=2)
  446. self.axes.add_patch(patch)
  447. except AssertionError:
  448. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  449. FlatCAMApp.App.log.warning(str(poly))
  450. else:
  451. for poly in geometry:
  452. x, y = poly.exterior.xy
  453. self.axes.plot(x, y, linespec)
  454. for ints in poly.interiors:
  455. x, y = ints.coords.xy
  456. self.axes.plot(x, y, linespec)
  457. self.app.plotcanvas.auto_adjust_axes()
  458. def serialize(self):
  459. return {
  460. "options": self.options,
  461. "kind": self.kind
  462. }
  463. class FlatCAMExcellon(FlatCAMObj, Excellon):
  464. """
  465. Represents Excellon/Drill code.
  466. """
  467. ui_type = ExcellonObjectUI
  468. def __init__(self, name):
  469. Excellon.__init__(self)
  470. FlatCAMObj.__init__(self, name)
  471. self.kind = "excellon"
  472. self.options.update({
  473. "plot": True,
  474. "solid": False,
  475. "drillz": -0.1,
  476. "travelz": 0.1,
  477. "feedrate": 5.0,
  478. # "toolselection": ""
  479. "tooldia": 0.1,
  480. "toolchange": False,
  481. "toolchangez": 1.0
  482. })
  483. # TODO: Document this.
  484. self.tool_cbs = {}
  485. # Attributes to be included in serialization
  486. # Always append to it because it carries contents
  487. # from predecessors.
  488. self.ser_attrs += ['options', 'kind']
  489. def build_ui(self):
  490. FlatCAMObj.build_ui(self)
  491. # Populate tool list
  492. n = len(self.tools)
  493. self.ui.tools_table.setColumnCount(2)
  494. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
  495. self.ui.tools_table.setRowCount(n)
  496. self.ui.tools_table.setSortingEnabled(False)
  497. i = 0
  498. for tool in self.tools:
  499. id = QtGui.QTableWidgetItem(tool)
  500. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  501. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  502. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  503. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  504. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  505. i += 1
  506. self.ui.tools_table.resizeColumnsToContents()
  507. self.ui.tools_table.resizeRowsToContents()
  508. self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
  509. self.ui.tools_table.verticalHeader().hide()
  510. self.ui.tools_table.setSortingEnabled(True)
  511. def set_ui(self, ui):
  512. """
  513. Configures the user interface for this object.
  514. Connects options to form fields.
  515. :param ui: User interface object.
  516. :type ui: ExcellonObjectUI
  517. :return: None
  518. """
  519. FlatCAMObj.set_ui(self, ui)
  520. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  521. self.form_fields.update({
  522. "plot": self.ui.plot_cb,
  523. "solid": self.ui.solid_cb,
  524. "drillz": self.ui.cutz_entry,
  525. "travelz": self.ui.travelz_entry,
  526. "feedrate": self.ui.feedrate_entry,
  527. "tooldia": self.ui.tooldia_entry,
  528. "toolchange": self.ui.toolchange_cb,
  529. "toolchangez": self.ui.toolchangez_entry
  530. })
  531. assert isinstance(self.ui, ExcellonObjectUI)
  532. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  533. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  534. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  535. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  536. def get_selected_tools_list(self):
  537. """
  538. Returns the keys to the self.tools dictionary corresponding
  539. to the selections on the tool list in the GUI.
  540. """
  541. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  542. def on_generate_milling_button_click(self, *args):
  543. self.app.report_usage("excellon_on_create_milling_button")
  544. self.read_form()
  545. # Get the tools from the list. These are keys
  546. # to self.tools
  547. tools = self.get_selected_tools_list()
  548. if len(tools) == 0:
  549. self.app.inform.emit("Please select one or more tools from the list and try again.")
  550. return
  551. for tool in tools:
  552. if self.tools[tool]["C"] < self.options["tooldia"]:
  553. self.app.inform.emit("[warning] Milling tool is larger than hole size. Cancelled.")
  554. return
  555. geo_name = self.options["name"] + "_mill"
  556. def geo_init(geo_obj, app_obj):
  557. assert isinstance(geo_obj, FlatCAMGeometry)
  558. app_obj.progress.emit(20)
  559. geo_obj.solid_geometry = []
  560. for hole in self.drills:
  561. if hole['tool'] in tools:
  562. geo_obj.solid_geometry.append(
  563. Point(hole['point']).buffer(self.tools[hole['tool']]["C"] / 2 -
  564. self.options["tooldia"] / 2).exterior
  565. )
  566. def geo_thread(app_obj):
  567. app_obj.new_object("geometry", geo_name, geo_init)
  568. app_obj.progress.emit(100)
  569. # Send to worker
  570. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  571. def on_create_cncjob_button_click(self, *args):
  572. self.app.report_usage("excellon_on_create_cncjob_button")
  573. self.read_form()
  574. # Get the tools from the list
  575. tools = self.get_selected_tools_list()
  576. if len(tools) == 0:
  577. self.app.inform.emit("Please select one or more tools from the list and try again.")
  578. return
  579. job_name = self.options["name"] + "_cnc"
  580. # Object initialization function for app.new_object()
  581. def job_init(job_obj, app_obj):
  582. assert isinstance(job_obj, FlatCAMCNCjob)
  583. app_obj.progress.emit(20)
  584. job_obj.z_cut = self.options["drillz"]
  585. job_obj.z_move = self.options["travelz"]
  586. job_obj.feedrate = self.options["feedrate"]
  587. # There could be more than one drill size...
  588. # job_obj.tooldia = # TODO: duplicate variable!
  589. # job_obj.options["tooldia"] =
  590. tools_csv = ','.join(tools)
  591. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  592. toolchange=self.options["toolchange"],
  593. toolchangez=self.options["toolchangez"])
  594. app_obj.progress.emit(50)
  595. job_obj.gcode_parse()
  596. app_obj.progress.emit(60)
  597. job_obj.create_geometry()
  598. app_obj.progress.emit(80)
  599. # To be run in separate thread
  600. def job_thread(app_obj):
  601. app_obj.new_object("cncjob", job_name, job_init)
  602. app_obj.progress.emit(100)
  603. # Send to worker
  604. # self.app.worker.add_task(job_thread, [self.app])
  605. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  606. def on_plot_cb_click(self, *args):
  607. if self.muted_ui:
  608. return
  609. self.read_form_item('plot')
  610. self.plot()
  611. def on_solid_cb_click(self, *args):
  612. if self.muted_ui:
  613. return
  614. self.read_form_item('solid')
  615. self.plot()
  616. def convert_units(self, units):
  617. factor = Excellon.convert_units(self, units)
  618. self.options['drillz'] *= factor
  619. self.options['travelz'] *= factor
  620. self.options['feedrate'] *= factor
  621. def plot(self):
  622. # Does all the required setup and returns False
  623. # if the 'ptint' option is set to False.
  624. if not FlatCAMObj.plot(self):
  625. return
  626. try:
  627. _ = iter(self.solid_geometry)
  628. except TypeError:
  629. self.solid_geometry = [self.solid_geometry]
  630. # Plot excellon (All polygons?)
  631. if self.options["solid"]:
  632. for geo in self.solid_geometry:
  633. patch = PolygonPatch(geo,
  634. facecolor="#C40000",
  635. edgecolor="#750000",
  636. alpha=0.75,
  637. zorder=3)
  638. self.axes.add_patch(patch)
  639. else:
  640. for geo in self.solid_geometry:
  641. x, y = geo.exterior.coords.xy
  642. self.axes.plot(x, y, 'r-')
  643. for ints in geo.interiors:
  644. x, y = ints.coords.xy
  645. self.axes.plot(x, y, 'g-')
  646. self.app.plotcanvas.auto_adjust_axes()
  647. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  648. """
  649. Represents G-Code.
  650. """
  651. ui_type = CNCObjectUI
  652. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  653. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  654. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  655. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  656. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia)
  657. FlatCAMObj.__init__(self, name)
  658. self.kind = "cncjob"
  659. self.options.update({
  660. "plot": True,
  661. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  662. "append": "",
  663. "prepend": ""
  664. })
  665. # Attributes to be included in serialization
  666. # Always append to it because it carries contents
  667. # from predecessors.
  668. self.ser_attrs += ['options', 'kind']
  669. def set_ui(self, ui):
  670. FlatCAMObj.set_ui(self, ui)
  671. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  672. assert isinstance(self.ui, CNCObjectUI)
  673. self.form_fields.update({
  674. "plot": self.ui.plot_cb,
  675. "tooldia": self.ui.tooldia_entry,
  676. "append": self.ui.append_text,
  677. "prepend": self.ui.prepend_text
  678. })
  679. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  680. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  681. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  682. def on_updateplot_button_click(self, *args):
  683. """
  684. Callback for the "Updata Plot" button. Reads the form for updates
  685. and plots the object.
  686. """
  687. self.read_form()
  688. self.plot()
  689. def on_exportgcode_button_click(self, *args):
  690. self.app.report_usage("cncjob_on_exportgcode_button")
  691. try:
  692. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  693. directory=self.app.defaults["last_folder"])
  694. except TypeError:
  695. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...")
  696. preamble = str(self.ui.prepend_text.get_value())
  697. postamble = str(self.ui.append_text.get_value())
  698. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  699. def export_gcode(self, filename, preamble='', postamble=''):
  700. f = open(filename, 'w')
  701. f.write(preamble + '\n' + self.gcode + "\n" + postamble)
  702. f.close()
  703. self.app.file_opened.emit("cncjob", filename)
  704. self.app.inform.emit("Saved to: " + filename)
  705. def on_plot_cb_click(self, *args):
  706. if self.muted_ui:
  707. return
  708. self.read_form_item('plot')
  709. self.plot()
  710. def plot(self):
  711. # Does all the required setup and returns False
  712. # if the 'ptint' option is set to False.
  713. if not FlatCAMObj.plot(self):
  714. return
  715. self.plot2(self.axes, tooldia=self.options["tooldia"])
  716. self.app.plotcanvas.auto_adjust_axes()
  717. def convert_units(self, units):
  718. factor = CNCjob.convert_units(self, units)
  719. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  720. self.options["tooldia"] *= factor
  721. class FlatCAMGeometry(FlatCAMObj, Geometry):
  722. """
  723. Geometric object not associated with a specific
  724. format.
  725. """
  726. ui_type = GeometryObjectUI
  727. @staticmethod
  728. def merge(geo_list, geo_final):
  729. """
  730. Merges the geometry of objects in geo_list into
  731. the geometry of geo_final.
  732. :param geo_list: List of FlatCAMGeometry Objects to join.
  733. :param geo_final: Destination FlatCAMGeometry object.
  734. :return: None
  735. """
  736. if geo_final.solid_geometry is None:
  737. geo_final.solid_geometry = []
  738. if type(geo_final.solid_geometry) is not list:
  739. geo_final.solid_geometry = [geo_final.solid_geometry]
  740. for geo in geo_list:
  741. # Expand lists
  742. if type(geo) is list:
  743. FlatCAMGeometry.merge(geo, geo_final)
  744. # If not list, just append
  745. else:
  746. geo_final.solid_geometry.append(geo.solid_geometry)
  747. # try: # Iterable
  748. # for shape in geo.solid_geometry:
  749. # geo_final.solid_geometry.append(shape)
  750. #
  751. # except TypeError: # Non-iterable
  752. # geo_final.solid_geometry.append(geo.solid_geometry)
  753. def __init__(self, name):
  754. FlatCAMObj.__init__(self, name)
  755. Geometry.__init__(self)
  756. self.kind = "geometry"
  757. self.options.update({
  758. "plot": True,
  759. "cutz": -0.002,
  760. "travelz": 0.1,
  761. "feedrate": 5.0,
  762. "cnctooldia": 0.4 / 25.4,
  763. "painttooldia": 0.0625,
  764. "paintoverlap": 0.15,
  765. "paintmargin": 0.01,
  766. "paintmethod": "standard"
  767. })
  768. # Attributes to be included in serialization
  769. # Always append to it because it carries contents
  770. # from predecessors.
  771. self.ser_attrs += ['options', 'kind']
  772. def build_ui(self):
  773. FlatCAMObj.build_ui(self)
  774. def set_ui(self, ui):
  775. FlatCAMObj.set_ui(self, ui)
  776. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  777. assert isinstance(self.ui, GeometryObjectUI)
  778. self.form_fields.update({
  779. "plot": self.ui.plot_cb,
  780. "cutz": self.ui.cutz_entry,
  781. "travelz": self.ui.travelz_entry,
  782. "feedrate": self.ui.cncfeedrate_entry,
  783. "cnctooldia": self.ui.cnctooldia_entry,
  784. "painttooldia": self.ui.painttooldia_entry,
  785. "paintoverlap": self.ui.paintoverlap_entry,
  786. "paintmargin": self.ui.paintmargin_entry,
  787. "paintmethod": self.ui.paintmethod_combo
  788. })
  789. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  790. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  791. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  792. def on_paint_button_click(self, *args):
  793. self.app.report_usage("geometry_on_paint_button")
  794. self.app.info("Click inside the desired polygon.")
  795. self.read_form()
  796. tooldia = self.options["painttooldia"]
  797. overlap = self.options["paintoverlap"]
  798. # Connection ID for the click event
  799. subscription = None
  800. # To be called after clicking on the plot.
  801. def doit(event):
  802. self.app.info("Painting polygon...")
  803. self.app.plotcanvas.mpl_disconnect(subscription)
  804. point = [event.xdata, event.ydata]
  805. self.paint_poly(point, tooldia, overlap)
  806. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  807. def paint_poly(self, inside_pt, tooldia, overlap):
  808. # Which polygon.
  809. #poly = find_polygon(self.solid_geometry, inside_pt)
  810. poly = self.find_polygon(inside_pt)
  811. # No polygon?
  812. if poly is None:
  813. self.app.log.warning('No polygon found.')
  814. self.app.inform.emit('[warning] No polygon found.')
  815. return
  816. proc = self.app.proc_container.new("Painting polygon.")
  817. # Initializes the new geometry object
  818. def gen_paintarea(geo_obj, app_obj):
  819. assert isinstance(geo_obj, FlatCAMGeometry)
  820. #assert isinstance(app_obj, App)
  821. if self.options["paintmethod"] == "seed":
  822. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]), tooldia, overlap=overlap)
  823. else:
  824. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]), tooldia, overlap=overlap)
  825. geo_obj.solid_geometry = list(cp.get_objects())
  826. geo_obj.options["cnctooldia"] = tooldia
  827. self.app.inform.emit("Done.")
  828. def job_thread(app_obj):
  829. try:
  830. name = self.options["name"] + "_paint"
  831. app_obj.new_object("geometry", name, gen_paintarea)
  832. except Exception as e:
  833. proc.done()
  834. raise e
  835. proc.done()
  836. self.app.inform.emit("Polygon Paint started ...")
  837. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  838. def on_generatecnc_button_click(self, *args):
  839. self.app.report_usage("geometry_on_generatecnc_button")
  840. self.read_form()
  841. self.generatecncjob()
  842. def generatecncjob(self, z_cut=None, z_move=None,
  843. feedrate=None, tooldia=None, outname=None):
  844. outname = outname if outname is not None else self.options["name"] + "_cnc"
  845. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  846. z_move = z_move if z_move is not None else self.options["travelz"]
  847. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  848. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  849. # Object initialization function for app.new_object()
  850. # RUNNING ON SEPARATE THREAD!
  851. def job_init(job_obj, app_obj):
  852. assert isinstance(job_obj, FlatCAMCNCjob)
  853. # Propagate options
  854. job_obj.options["tooldia"] = tooldia
  855. app_obj.progress.emit(20)
  856. job_obj.z_cut = z_cut
  857. job_obj.z_move = z_move
  858. job_obj.feedrate = feedrate
  859. app_obj.progress.emit(40)
  860. # TODO: The tolerance should not be hard coded. Just for testing.
  861. job_obj.generate_from_geometry_2(self, tolerance=0.0005)
  862. app_obj.progress.emit(50)
  863. job_obj.gcode_parse()
  864. app_obj.progress.emit(80)
  865. # To be run in separate thread
  866. def job_thread(app_obj):
  867. with self.app.proc_container.new("Generating CNC Job."):
  868. app_obj.new_object("cncjob", outname, job_init)
  869. app_obj.inform.emit("CNCjob created: %s" % outname)
  870. app_obj.progress.emit(100)
  871. # Send to worker
  872. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  873. def on_plot_cb_click(self, *args): # TODO: args not needed
  874. if self.muted_ui:
  875. return
  876. self.read_form_item('plot')
  877. self.plot()
  878. def scale(self, factor):
  879. """
  880. Scales all geometry by a given factor.
  881. :param factor: Factor by which to scale the object's geometry/
  882. :type factor: float
  883. :return: None
  884. :rtype: None
  885. """
  886. if type(self.solid_geometry) == list:
  887. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  888. for g in self.solid_geometry]
  889. else:
  890. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  891. origin=(0, 0))
  892. def offset(self, vect):
  893. """
  894. Offsets all geometry by a given vector/
  895. :param vect: (x, y) vector by which to offset the object's geometry.
  896. :type vect: tuple
  897. :return: None
  898. :rtype: None
  899. """
  900. dx, dy = vect
  901. if type(self.solid_geometry) == list:
  902. self.solid_geometry = [affinity.translate(g, xoff=dx, yoff=dy)
  903. for g in self.solid_geometry]
  904. else:
  905. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  906. def convert_units(self, units):
  907. factor = Geometry.convert_units(self, units)
  908. self.options['cutz'] *= factor
  909. self.options['travelz'] *= factor
  910. self.options['feedrate'] *= factor
  911. self.options['cnctooldia'] *= factor
  912. self.options['painttooldia'] *= factor
  913. self.options['paintmargin'] *= factor
  914. return factor
  915. def plot_element(self, element):
  916. try:
  917. for sub_el in element:
  918. self.plot_element(sub_el)
  919. except TypeError: # Element is not iterable...
  920. if type(element) == Polygon:
  921. x, y = element.exterior.coords.xy
  922. self.axes.plot(x, y, 'r-')
  923. for ints in element.interiors:
  924. x, y = ints.coords.xy
  925. self.axes.plot(x, y, 'r-')
  926. return
  927. if type(element) == LineString or type(element) == LinearRing:
  928. x, y = element.coords.xy
  929. self.axes.plot(x, y, 'r-')
  930. return
  931. FlatCAMApp.App.log.warning("Did not plot:" + str(type(element)))
  932. def plot(self):
  933. """
  934. Plots the object into its axes. If None, of if the axes
  935. are not part of the app's figure, it fetches new ones.
  936. :return: None
  937. """
  938. # Does all the required setup and returns False
  939. # if the 'ptint' option is set to False.
  940. if not FlatCAMObj.plot(self):
  941. return
  942. # Make sure solid_geometry is iterable.
  943. # TODO: This method should not modify the object !!!
  944. # try:
  945. # _ = iter(self.solid_geometry)
  946. # except TypeError:
  947. # if self.solid_geometry is None:
  948. # self.solid_geometry = []
  949. # else:
  950. # self.solid_geometry = [self.solid_geometry]
  951. #
  952. # for geo in self.solid_geometry:
  953. #
  954. # if type(geo) == Polygon:
  955. # x, y = geo.exterior.coords.xy
  956. # self.axes.plot(x, y, 'r-')
  957. # for ints in geo.interiors:
  958. # x, y = ints.coords.xy
  959. # self.axes.plot(x, y, 'r-')
  960. # continue
  961. #
  962. # if type(geo) == LineString or type(geo) == LinearRing:
  963. # x, y = geo.coords.xy
  964. # self.axes.plot(x, y, 'r-')
  965. # continue
  966. #
  967. # if type(geo) == MultiPolygon:
  968. # for poly in geo:
  969. # x, y = poly.exterior.coords.xy
  970. # self.axes.plot(x, y, 'r-')
  971. # for ints in poly.interiors:
  972. # x, y = ints.coords.xy
  973. # self.axes.plot(x, y, 'r-')
  974. # continue
  975. #
  976. # FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  977. self.plot_element(self.solid_geometry)
  978. self.app.plotcanvas.auto_adjust_axes()