FlatCAMObj.py 42 KB

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