FlatCAMObj.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 follow(self, outname=None):
  323. """
  324. Creates a geometry object "following" the gerber paths.
  325. :return: None
  326. """
  327. default_name = self.options["name"] + "_follow"
  328. follow_name = outname or default_name
  329. def follow_init(follow_obj, app_obj):
  330. # Propagate options
  331. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  332. follow_obj.solid_geometry = self.solid_geometry
  333. app_obj.info("Follow geometry created: %s" % follow_obj.options["name"])
  334. # TODO: Do something if this is None. Offer changing name?
  335. self.app.new_object("geometry", follow_name, follow_init)
  336. def isolate(self, dia=None, passes=None, overlap=None, outname=None):
  337. """
  338. Creates an isolation routing geometry object in the project.
  339. :param dia: Tool diameter
  340. :param passes: Number of tool widths to cut
  341. :param overlap: Overlap between passes in fraction of tool diameter
  342. :param outname: Base name of the output object
  343. :return: None
  344. """
  345. if dia is None:
  346. dia = self.options["isotooldia"]
  347. if passes is None:
  348. passes = int(self.options["isopasses"])
  349. if overlap is None:
  350. overlap = self.options["isooverlap"] * dia
  351. base_name = self.options["name"] + "_iso"
  352. base_name = outname or base_name
  353. for i in range(passes):
  354. offset = (2*i + 1)/2.0 * dia - i*overlap
  355. if passes > 1:
  356. iso_name = base_name + str(i+1)
  357. else:
  358. iso_name = base_name
  359. # TODO: This is ugly. Create way to pass data into init function.
  360. def iso_init(geo_obj, app_obj):
  361. # Propagate options
  362. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  363. geo_obj.solid_geometry = self.isolation_geometry(offset)
  364. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  365. # TODO: Do something if this is None. Offer changing name?
  366. self.app.new_object("geometry", iso_name, iso_init)
  367. def on_plot_cb_click(self, *args):
  368. if self.muted_ui:
  369. return
  370. self.read_form_item('plot')
  371. self.plot()
  372. def on_solid_cb_click(self, *args):
  373. if self.muted_ui:
  374. return
  375. self.read_form_item('solid')
  376. self.plot()
  377. def on_multicolored_cb_click(self, *args):
  378. if self.muted_ui:
  379. return
  380. self.read_form_item('multicolored')
  381. self.plot()
  382. def convert_units(self, units):
  383. """
  384. Converts the units of the object by scaling dimensions in all geometry
  385. and options.
  386. :param units: Units to which to convert the object: "IN" or "MM".
  387. :type units: str
  388. :return: None
  389. :rtype: None
  390. """
  391. factor = Gerber.convert_units(self, units)
  392. self.options['isotooldia'] *= factor
  393. self.options['cutoutmargin'] *= factor
  394. self.options['cutoutgapsize'] *= factor
  395. self.options['noncoppermargin'] *= factor
  396. self.options['bboxmargin'] *= factor
  397. def plot(self):
  398. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  399. # Does all the required setup and returns False
  400. # if the 'ptint' option is set to False.
  401. if not FlatCAMObj.plot(self):
  402. return
  403. geometry = self.solid_geometry
  404. # Make sure geometry is iterable.
  405. try:
  406. _ = iter(geometry)
  407. except TypeError:
  408. geometry = [geometry]
  409. if self.options["multicolored"]:
  410. linespec = '-'
  411. else:
  412. linespec = 'k-'
  413. if self.options["solid"]:
  414. for poly in geometry:
  415. # TODO: Too many things hardcoded.
  416. try:
  417. patch = PolygonPatch(poly,
  418. facecolor="#BBF268",
  419. edgecolor="#006E20",
  420. alpha=0.75,
  421. zorder=2)
  422. self.axes.add_patch(patch)
  423. except AssertionError:
  424. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  425. FlatCAMApp.App.log.warning(str(poly))
  426. else:
  427. for poly in geometry:
  428. x, y = poly.exterior.xy
  429. self.axes.plot(x, y, linespec)
  430. for ints in poly.interiors:
  431. x, y = ints.coords.xy
  432. self.axes.plot(x, y, linespec)
  433. self.app.plotcanvas.auto_adjust_axes()
  434. #GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  435. #self.emit(QtCore.SIGNAL("plotChanged"), self)
  436. def serialize(self):
  437. return {
  438. "options": self.options,
  439. "kind": self.kind
  440. }
  441. class FlatCAMExcellon(FlatCAMObj, Excellon):
  442. """
  443. Represents Excellon/Drill code.
  444. """
  445. ui_type = ExcellonObjectUI
  446. def __init__(self, name):
  447. Excellon.__init__(self)
  448. FlatCAMObj.__init__(self, name)
  449. self.kind = "excellon"
  450. self.options.update({
  451. "plot": True,
  452. "solid": False,
  453. "drillz": -0.1,
  454. "travelz": 0.1,
  455. "feedrate": 5.0,
  456. # "toolselection": ""
  457. })
  458. # TODO: Document this.
  459. self.tool_cbs = {}
  460. # Attributes to be included in serialization
  461. # Always append to it because it carries contents
  462. # from predecessors.
  463. self.ser_attrs += ['options', 'kind']
  464. def build_ui(self):
  465. FlatCAMObj.build_ui(self)
  466. # Populate tool list
  467. n = len(self.tools)
  468. self.ui.tools_table.setColumnCount(2)
  469. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
  470. self.ui.tools_table.setRowCount(n)
  471. self.ui.tools_table.setSortingEnabled(False)
  472. i = 0
  473. for tool in self.tools:
  474. id = QtGui.QTableWidgetItem(tool)
  475. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  476. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  477. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  478. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  479. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  480. i += 1
  481. self.ui.tools_table.resizeColumnsToContents()
  482. self.ui.tools_table.resizeRowsToContents()
  483. self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
  484. self.ui.tools_table.verticalHeader().hide()
  485. self.ui.tools_table.setSortingEnabled(True)
  486. def set_ui(self, ui):
  487. FlatCAMObj.set_ui(self, ui)
  488. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  489. self.form_fields.update({
  490. "plot": self.ui.plot_cb,
  491. "solid": self.ui.solid_cb,
  492. "drillz": self.ui.cutz_entry,
  493. "travelz": self.ui.travelz_entry,
  494. "feedrate": self.ui.feedrate_entry,
  495. # "toolselection": self.ui.tools_entry
  496. })
  497. assert isinstance(self.ui, ExcellonObjectUI)
  498. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  499. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  500. # self.ui.choose_tools_button.clicked.connect(self.show_tool_chooser)
  501. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  502. def on_create_cncjob_button_click(self, *args):
  503. self.read_form()
  504. # Get the tools from the list
  505. tools = [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  506. if len(tools) == 0:
  507. self.app.inform.emit("Please select one or more tools from the list and try again.")
  508. return
  509. job_name = self.options["name"] + "_cnc"
  510. # Object initialization function for app.new_object()
  511. def job_init(job_obj, app_obj):
  512. assert isinstance(job_obj, FlatCAMCNCjob)
  513. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  514. app_obj.progress.emit(20)
  515. job_obj.z_cut = self.options["drillz"]
  516. job_obj.z_move = self.options["travelz"]
  517. job_obj.feedrate = self.options["feedrate"]
  518. # There could be more than one drill size...
  519. # job_obj.tooldia = # TODO: duplicate variable!
  520. # job_obj.options["tooldia"] =
  521. tools_csv = ','.join(tools)
  522. # job_obj.generate_from_excellon_by_tool(self, self.options["toolselection"])
  523. job_obj.generate_from_excellon_by_tool(self, tools_csv)
  524. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  525. app_obj.progress.emit(50)
  526. job_obj.gcode_parse()
  527. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  528. app_obj.progress.emit(60)
  529. job_obj.create_geometry()
  530. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  531. app_obj.progress.emit(80)
  532. # To be run in separate thread
  533. def job_thread(app_obj):
  534. app_obj.new_object("cncjob", job_name, job_init)
  535. # GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  536. app_obj.progress.emit(100)
  537. # GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  538. # Send to worker
  539. # self.app.worker.add_task(job_thread, [self.app])
  540. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  541. def on_plot_cb_click(self, *args):
  542. if self.muted_ui:
  543. return
  544. self.read_form_item('plot')
  545. self.plot()
  546. def on_solid_cb_click(self, *args):
  547. if self.muted_ui:
  548. return
  549. self.read_form_item('solid')
  550. self.plot()
  551. def convert_units(self, units):
  552. factor = Excellon.convert_units(self, units)
  553. self.options['drillz'] *= factor
  554. self.options['travelz'] *= factor
  555. self.options['feedrate'] *= factor
  556. def plot(self):
  557. # Does all the required setup and returns False
  558. # if the 'ptint' option is set to False.
  559. if not FlatCAMObj.plot(self):
  560. return
  561. try:
  562. _ = iter(self.solid_geometry)
  563. except TypeError:
  564. self.solid_geometry = [self.solid_geometry]
  565. # Plot excellon (All polygons?)
  566. if self.options["solid"]:
  567. for geo in self.solid_geometry:
  568. patch = PolygonPatch(geo,
  569. facecolor="#C40000",
  570. edgecolor="#750000",
  571. alpha=0.75,
  572. zorder=3)
  573. self.axes.add_patch(patch)
  574. else:
  575. for geo in self.solid_geometry:
  576. x, y = geo.exterior.coords.xy
  577. self.axes.plot(x, y, 'r-')
  578. for ints in geo.interiors:
  579. x, y = ints.coords.xy
  580. self.axes.plot(x, y, 'g-')
  581. self.app.plotcanvas.auto_adjust_axes()
  582. # GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  583. # self.emit(QtCore.SIGNAL("plotChanged"), self)
  584. def show_tool_chooser(self):
  585. # win = Gtk.Window()
  586. # box = Gtk.Box(spacing=2)
  587. # box.set_orientation(Gtk.Orientation(1))
  588. # win.add(box)
  589. # for tool in self.tools:
  590. # self.tool_cbs[tool] = Gtk.CheckButton(label=tool + ": " + str(self.tools[tool]))
  591. # box.pack_start(self.tool_cbs[tool], False, False, 1)
  592. # button = Gtk.Button(label="Accept")
  593. # box.pack_start(button, False, False, 1)
  594. # win.show_all()
  595. #
  596. # def on_accept(widget):
  597. # win.destroy()
  598. # tool_list = []
  599. # for toolx in self.tool_cbs:
  600. # if self.tool_cbs[toolx].get_active():
  601. # tool_list.append(toolx)
  602. # self.options["toolselection"] = ", ".join(tool_list)
  603. # self.to_form()
  604. #
  605. # button.connect("activate", on_accept)
  606. # button.connect("clicked", on_accept)
  607. return
  608. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  609. """
  610. Represents G-Code.
  611. """
  612. ui_type = CNCObjectUI
  613. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  614. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  615. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  616. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  617. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia)
  618. FlatCAMObj.__init__(self, name)
  619. self.kind = "cncjob"
  620. self.options.update({
  621. "plot": True,
  622. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  623. "append": ""
  624. })
  625. # Attributes to be included in serialization
  626. # Always append to it because it carries contents
  627. # from predecessors.
  628. self.ser_attrs += ['options', 'kind']
  629. def set_ui(self, ui):
  630. FlatCAMObj.set_ui(self, ui)
  631. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  632. assert isinstance(self.ui, CNCObjectUI)
  633. self.form_fields.update({
  634. "plot": self.ui.plot_cb,
  635. "tooldia": self.ui.tooldia_entry,
  636. "append": self.ui.append_text
  637. })
  638. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  639. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  640. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  641. def on_updateplot_button_click(self, *args):
  642. """
  643. Callback for the "Updata Plot" button. Reads the form for updates
  644. and plots the object.
  645. """
  646. self.read_form()
  647. self.plot()
  648. def on_exportgcode_button_click(self, *args):
  649. try:
  650. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  651. directory=self.app.last_folder)
  652. except TypeError:
  653. filename = QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...")
  654. postamble = str(self.ui.append_text.get_value())
  655. self.export_gcode(filename, preamble='', postamble=postamble)
  656. def export_gcode(self, filename, preamble='', postamble=''):
  657. f = open(filename, 'w')
  658. f.write(preamble + '\n' + self.gcode + "\n" + postamble)
  659. f.close()
  660. self.app.file_opened.emit("cncjob", filename)
  661. self.app.inform.emit("Saved to: " + filename)
  662. def on_plot_cb_click(self, *args):
  663. if self.muted_ui:
  664. return
  665. self.read_form_item('plot')
  666. self.plot()
  667. def plot(self):
  668. # Does all the required setup and returns False
  669. # if the 'ptint' option is set to False.
  670. if not FlatCAMObj.plot(self):
  671. return
  672. self.plot2(self.axes, tooldia=self.options["tooldia"])
  673. self.app.plotcanvas.auto_adjust_axes()
  674. def convert_units(self, units):
  675. factor = CNCjob.convert_units(self, units)
  676. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  677. self.options["tooldia"] *= factor
  678. class FlatCAMGeometry(FlatCAMObj, Geometry):
  679. """
  680. Geometric object not associated with a specific
  681. format.
  682. """
  683. ui_type = GeometryObjectUI
  684. def __init__(self, name):
  685. FlatCAMObj.__init__(self, name)
  686. Geometry.__init__(self)
  687. self.kind = "geometry"
  688. self.options.update({
  689. "plot": True,
  690. # "solid": False,
  691. # "multicolored": False,
  692. "cutz": -0.002,
  693. "travelz": 0.1,
  694. "feedrate": 5.0,
  695. "cnctooldia": 0.4 / 25.4,
  696. "painttooldia": 0.0625,
  697. "paintoverlap": 0.15,
  698. "paintmargin": 0.01
  699. })
  700. # Attributes to be included in serialization
  701. # Always append to it because it carries contents
  702. # from predecessors.
  703. self.ser_attrs += ['options', 'kind']
  704. def set_ui(self, ui):
  705. FlatCAMObj.set_ui(self, ui)
  706. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  707. assert isinstance(self.ui, GeometryObjectUI)
  708. self.form_fields.update({
  709. "plot": self.ui.plot_cb,
  710. # "solid": self.ui.sol,
  711. # "multicolored": self.ui.,
  712. "cutz": self.ui.cutz_entry,
  713. "travelz": self.ui.travelz_entry,
  714. "feedrate": self.ui.cncfeedrate_entry,
  715. "cnctooldia": self.ui.cnctooldia_entry,
  716. "painttooldia": self.ui.painttooldia_entry,
  717. "paintoverlap": self.ui.paintoverlap_entry,
  718. "paintmargin": self.ui.paintmargin_entry
  719. })
  720. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  721. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  722. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  723. def on_paint_button_click(self, *args):
  724. self.app.info("Click inside the desired polygon.")
  725. self.read_form()
  726. tooldia = self.options["painttooldia"]
  727. overlap = self.options["paintoverlap"]
  728. # Connection ID for the click event
  729. subscription = None
  730. # To be called after clicking on the plot.
  731. def doit(event):
  732. self.app.plotcanvas.mpl_disconnect(subscription)
  733. point = [event.xdata, event.ydata]
  734. self.paint_poly(point, tooldia, overlap)
  735. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  736. def paint_poly(self, inside_pt, tooldia, overlap):
  737. poly = find_polygon(self.solid_geometry, inside_pt)
  738. # Initializes the new geometry object
  739. def gen_paintarea(geo_obj, app_obj):
  740. assert isinstance(geo_obj, FlatCAMGeometry)
  741. #assert isinstance(app_obj, App)
  742. cp = clear_poly(poly.buffer(-self.options["paintmargin"]), tooldia, overlap)
  743. geo_obj.solid_geometry = cp
  744. geo_obj.options["cnctooldia"] = tooldia
  745. name = self.options["name"] + "_paint"
  746. self.app.new_object("geometry", name, gen_paintarea)
  747. def on_generatecnc_button_click(self, *args):
  748. self.read_form()
  749. self.generatecncjob()
  750. def generatecncjob(self, z_cut=None, z_move=None,
  751. feedrate=None, tooldia=None, outname=None):
  752. outname = outname if outname is not None else self.options["name"] + "_cnc"
  753. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  754. z_move = z_move if z_move is not None else self.options["travelz"]
  755. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  756. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  757. # Object initialization function for app.new_object()
  758. # RUNNING ON SEPARATE THREAD!
  759. def job_init(job_obj, app_obj):
  760. assert isinstance(job_obj, FlatCAMCNCjob)
  761. # Propagate options
  762. job_obj.options["tooldia"] = tooldia
  763. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  764. app_obj.progress.emit(20)
  765. job_obj.z_cut = z_cut
  766. job_obj.z_move = z_move
  767. job_obj.feedrate = feedrate
  768. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry..."))
  769. app_obj.progress.emit(40)
  770. # TODO: The tolerance should not be hard coded. Just for testing.
  771. job_obj.generate_from_geometry(self, tolerance=0.0005)
  772. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  773. app_obj.progress.emit(50)
  774. job_obj.gcode_parse()
  775. # TODO: job_obj.create_geometry creates stuff that is not used.
  776. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  777. #job_obj.create_geometry()
  778. # GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  779. app_obj.progress.emit(80)
  780. # To be run in separate thread
  781. def job_thread(app_obj):
  782. app_obj.new_object("cncjob", outname, job_init)
  783. # GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name))
  784. # GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  785. # GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, "Idle"))
  786. app_obj.inform.emit("CNCjob created: %s" % outname)
  787. app_obj.progress.emit(100)
  788. # Send to worker
  789. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  790. def on_plot_cb_click(self, *args): # TODO: args not needed
  791. if self.muted_ui:
  792. return
  793. self.read_form_item('plot')
  794. self.plot()
  795. def scale(self, factor):
  796. """
  797. Scales all geometry by a given factor.
  798. :param factor: Factor by which to scale the object's geometry/
  799. :type factor: float
  800. :return: None
  801. :rtype: None
  802. """
  803. if type(self.solid_geometry) == list:
  804. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  805. for g in self.solid_geometry]
  806. else:
  807. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  808. origin=(0, 0))
  809. def offset(self, vect):
  810. """
  811. Offsets all geometry by a given vector/
  812. :param vect: (x, y) vector by which to offset the object's geometry.
  813. :type vect: tuple
  814. :return: None
  815. :rtype: None
  816. """
  817. dx, dy = vect
  818. if type(self.solid_geometry) == list:
  819. self.solid_geometry = [affinity.translate(g, xoff=dx, yoff=dy)
  820. for g in self.solid_geometry]
  821. else:
  822. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  823. def convert_units(self, units):
  824. factor = Geometry.convert_units(self, units)
  825. self.options['cutz'] *= factor
  826. self.options['travelz'] *= factor
  827. self.options['feedrate'] *= factor
  828. self.options['cnctooldia'] *= factor
  829. self.options['painttooldia'] *= factor
  830. self.options['paintmargin'] *= factor
  831. return factor
  832. def plot(self):
  833. """
  834. Plots the object into its axes. If None, of if the axes
  835. are not part of the app's figure, it fetches new ones.
  836. :return: None
  837. """
  838. # Does all the required setup and returns False
  839. # if the 'ptint' option is set to False.
  840. if not FlatCAMObj.plot(self):
  841. return
  842. # Make sure solid_geometry is iterable.
  843. # TODO: This method should not modify the object !!!
  844. try:
  845. _ = iter(self.solid_geometry)
  846. except TypeError:
  847. if self.solid_geometry is None:
  848. self.solid_geometry = []
  849. else:
  850. self.solid_geometry = [self.solid_geometry]
  851. for geo in self.solid_geometry:
  852. if type(geo) == Polygon:
  853. x, y = geo.exterior.coords.xy
  854. self.axes.plot(x, y, 'r-')
  855. for ints in geo.interiors:
  856. x, y = ints.coords.xy
  857. self.axes.plot(x, y, 'r-')
  858. continue
  859. if type(geo) == LineString or type(geo) == LinearRing:
  860. x, y = geo.coords.xy
  861. self.axes.plot(x, y, 'r-')
  862. continue
  863. if type(geo) == MultiPolygon:
  864. for poly in geo:
  865. x, y = poly.exterior.coords.xy
  866. self.axes.plot(x, y, 'r-')
  867. for ints in poly.interiors:
  868. x, y = ints.coords.xy
  869. self.axes.plot(x, y, 'r-')
  870. continue
  871. FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  872. self.app.plotcanvas.auto_adjust_axes()
  873. # GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  874. # self.emit(QtCore.SIGNAL("plotChanged"), self)