FlatCAM.py 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import threading
  9. # TODO: Bundle together. This is just for debugging.
  10. from gi.repository import Gtk
  11. from gi.repository import Gdk
  12. from gi.repository import GdkPixbuf
  13. from gi.repository import GLib
  14. from gi.repository import GObject
  15. import simplejson as json
  16. from matplotlib.figure import Figure
  17. from numpy import arange, sin, pi
  18. from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
  19. #from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
  20. from camlib import *
  21. import sys
  22. import urllib
  23. import copy
  24. import random
  25. ########################################
  26. ## FlatCAMObj ##
  27. ########################################
  28. class FlatCAMObj:
  29. """
  30. Base type of objects handled in FlatCAM. These become interactive
  31. in the GUI, can be plotted, and their options can be modified
  32. by the user in their respective forms.
  33. """
  34. # Instance of the application to which these are related.
  35. # The app should set this value.
  36. app = None
  37. def __init__(self, name):
  38. self.options = {"name": name}
  39. self.form_kinds = {"name": "entry_text"} # Kind of form element for each option
  40. self.radios = {} # Name value pairs for radio sets
  41. self.radios_inv = {} # Inverse of self.radios
  42. self.axes = None # Matplotlib axes
  43. self.kind = None # Override with proper name
  44. def setup_axes(self, figure):
  45. """
  46. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  47. them to figure if not part of the figure. 4) Sets transparent
  48. background. 5) Sets 1:1 scale aspect ratio.
  49. :param figure: A Matplotlib.Figure on which to add/configure axes.
  50. :type figure: matplotlib.figure.Figure
  51. :return: None
  52. :rtype: None
  53. """
  54. if self.axes is None:
  55. print "New axes"
  56. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  57. label=self.options["name"])
  58. elif self.axes not in figure.axes:
  59. print "Clearing and attaching axes"
  60. self.axes.cla()
  61. figure.add_axes(self.axes)
  62. else:
  63. print "Clearing Axes"
  64. self.axes.cla()
  65. # Remove all decoration. The app's axes will have
  66. # the ticks and grid.
  67. self.axes.set_frame_on(False) # No frame
  68. self.axes.set_xticks([]) # No tick
  69. self.axes.set_yticks([]) # No ticks
  70. self.axes.patch.set_visible(False) # No background
  71. self.axes.set_aspect(1)
  72. def to_form(self):
  73. """
  74. Copies options to the UI form.
  75. :return: None
  76. """
  77. for option in self.options:
  78. self.set_form_item(option)
  79. def read_form(self):
  80. """
  81. Reads form into ``self.options``.
  82. :return: None
  83. :rtype: None
  84. """
  85. for option in self.options:
  86. self.read_form_item(option)
  87. def build_ui(self):
  88. """
  89. Sets up the UI/form for this object.
  90. :return: None
  91. :rtype: None
  92. """
  93. # Where the UI for this object is drawn
  94. box_selected = self.app.builder.get_object("box_selected")
  95. # Remove anything else in the box
  96. box_children = box_selected.get_children()
  97. for child in box_children:
  98. box_selected.remove(child)
  99. osw = self.app.builder.get_object("offscrwindow_" + self.kind) # offscreenwindow
  100. sw = self.app.builder.get_object("sw_" + self.kind) # scrollwindows
  101. osw.remove(sw) # TODO: Is this needed ?
  102. vp = self.app.builder.get_object("vp_" + self.kind) # Viewport
  103. vp.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(1, 1, 1, 1))
  104. # Put in the UI
  105. box_selected.pack_start(sw, True, True, 0)
  106. entry_name = self.app.builder.get_object("entry_text_" + self.kind + "_name")
  107. entry_name.connect("activate", self.app.on_activate_name)
  108. self.to_form()
  109. sw.show()
  110. def set_form_item(self, option):
  111. """
  112. Copies the specified option to the UI form.
  113. :param option: Name of the option (Key in ``self.options``).
  114. :type option: str
  115. :return: None
  116. """
  117. fkind = self.form_kinds[option]
  118. fname = fkind + "_" + self.kind + "_" + option
  119. if fkind == 'entry_eval' or fkind == 'entry_text':
  120. self.app.builder.get_object(fname).set_text(str(self.options[option]))
  121. return
  122. if fkind == 'cb':
  123. self.app.builder.get_object(fname).set_active(self.options[option])
  124. return
  125. if fkind == 'radio':
  126. self.app.builder.get_object(self.radios_inv[option][self.options[option]]).set_active(True)
  127. return
  128. print "Unknown kind of form item:", fkind
  129. def read_form_item(self, option):
  130. """
  131. Reads the specified option from the UI form into ``self.options``.
  132. :param option: Name of the option.
  133. :type option: str
  134. :return: None
  135. """
  136. fkind = self.form_kinds[option]
  137. fname = fkind + "_" + self.kind + "_" + option
  138. if fkind == 'entry_text':
  139. self.options[option] = self.app.builder.get_object(fname).get_text()
  140. return
  141. if fkind == 'entry_eval':
  142. self.options[option] = self.app.get_eval(fname)
  143. return
  144. if fkind == 'cb':
  145. self.options[option] = self.app.builder.get_object(fname).get_active()
  146. return
  147. if fkind == 'radio':
  148. self.options[option] = self.app.get_radio_value(self.radios[option])
  149. return
  150. print "Unknown kind of form item:", fkind
  151. def plot(self):
  152. """
  153. Plot this object (Extend this method to implement the actual plotting).
  154. Axes get created, appended to canvas and cleared before plotting.
  155. Call this in descendants before doing the plotting.
  156. :return: Whether to continue plotting or not depending on the "plot" option.
  157. :rtype: bool
  158. """
  159. # Axes must exist and be attached to canvas.
  160. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  161. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  162. if not self.options["plot"]:
  163. self.axes.cla()
  164. self.app.plotcanvas.auto_adjust_axes()
  165. return False
  166. # Clear axes or we will plot on top of them.
  167. self.axes.cla()
  168. # GLib.idle_add(self.axes.cla)
  169. return True
  170. def serialize(self):
  171. """
  172. Returns a representation of the object as a dictionary so
  173. it can be later exported as JSON. Override this method.
  174. :return: Dictionary representing the object
  175. :rtype: dict
  176. """
  177. return
  178. def deserialize(self, obj_dict):
  179. """
  180. Re-builds an object from its serialized version.
  181. :param obj_dict: Dictionary representing a FlatCAMObj
  182. :type obj_dict: dict
  183. :return: None
  184. """
  185. return
  186. class FlatCAMGerber(FlatCAMObj, Gerber):
  187. """
  188. Represents Gerber code.
  189. """
  190. def __init__(self, name):
  191. Gerber.__init__(self)
  192. FlatCAMObj.__init__(self, name)
  193. self.kind = "gerber"
  194. # The 'name' is already in self.options from FlatCAMObj
  195. self.options.update({
  196. "plot": True,
  197. "mergepolys": True,
  198. "multicolored": False,
  199. "solid": False,
  200. "isotooldia": 0.016,
  201. "isopasses": 1,
  202. "isooverlap": 0.15,
  203. "cutouttooldia": 0.07,
  204. "cutoutmargin": 0.2,
  205. "cutoutgapsize": 0.15,
  206. "gaps": "tb",
  207. "noncoppermargin": 0.0,
  208. "noncopperrounded": False,
  209. "bboxmargin": 0.0,
  210. "bboxrounded": False
  211. })
  212. # The 'name' is already in self.form_kinds from FlatCAMObj
  213. self.form_kinds.update({
  214. "plot": "cb",
  215. "mergepolys": "cb",
  216. "multicolored": "cb",
  217. "solid": "cb",
  218. "isotooldia": "entry_eval",
  219. "isopasses": "entry_eval",
  220. "isooverlap": "entry_eval",
  221. "cutouttooldia": "entry_eval",
  222. "cutoutmargin": "entry_eval",
  223. "cutoutgapsize": "entry_eval",
  224. "gaps": "radio",
  225. "noncoppermargin": "entry_eval",
  226. "noncopperrounded": "cb",
  227. "bboxmargin": "entry_eval",
  228. "bboxrounded": "cb"
  229. })
  230. self.radios = {"gaps": {"rb_2tb": "tb", "rb_2lr": "lr", "rb_4": "4"}}
  231. self.radios_inv = {"gaps": {"tb": "rb_2tb", "lr": "rb_2lr", "4": "rb_4"}}
  232. # Attributes to be included in serialization
  233. # Always append to it because it carries contents
  234. # from predecessors.
  235. self.ser_attrs += ['options', 'kind']
  236. def convert_units(self, units):
  237. """
  238. Converts the units of the object by scaling dimensions in all geometry
  239. and options.
  240. :param units: Units to which to convert the object: "IN" or "MM".
  241. :type units: str
  242. :return: None
  243. :rtype: None
  244. """
  245. factor = Gerber.convert_units(self, units)
  246. self.options['isotooldia'] *= factor
  247. self.options['cutoutmargin'] *= factor
  248. self.options['cutoutgapsize'] *= factor
  249. self.options['noncoppermargin'] *= factor
  250. self.options['bboxmargin'] *= factor
  251. def plot(self):
  252. # Does all the required setup and returns False
  253. # if the 'ptint' option is set to False.
  254. if not FlatCAMObj.plot(self):
  255. return
  256. if self.options["mergepolys"]:
  257. geometry = self.solid_geometry
  258. else:
  259. geometry = self.buffered_paths + \
  260. [poly['polygon'] for poly in self.regions] + \
  261. self.flash_geometry
  262. if self.options["multicolored"]:
  263. linespec = '-'
  264. else:
  265. linespec = 'k-'
  266. if self.options["solid"]:
  267. for poly in geometry:
  268. # TODO: Too many things hardcoded.
  269. patch = PolygonPatch(poly,
  270. facecolor="#BBF268",
  271. edgecolor="#006E20",
  272. alpha=0.75,
  273. zorder=2)
  274. self.axes.add_patch(patch)
  275. else:
  276. for poly in geometry:
  277. x, y = poly.exterior.xy
  278. self.axes.plot(x, y, linespec)
  279. for ints in poly.interiors:
  280. x, y = ints.coords.xy
  281. self.axes.plot(x, y, linespec)
  282. # self.app.plotcanvas.auto_adjust_axes()
  283. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  284. def serialize(self):
  285. return {
  286. "options": self.options,
  287. "kind": self.kind
  288. }
  289. class FlatCAMExcellon(FlatCAMObj, Excellon):
  290. """
  291. Represents Excellon/Drill code.
  292. """
  293. def __init__(self, name):
  294. Excellon.__init__(self)
  295. FlatCAMObj.__init__(self, name)
  296. self.kind = "excellon"
  297. self.options.update({
  298. "plot": True,
  299. "solid": False,
  300. "drillz": -0.1,
  301. "travelz": 0.1,
  302. "feedrate": 5.0,
  303. "toolselection": ""
  304. })
  305. self.form_kinds.update({
  306. "plot": "cb",
  307. "solid": "cb",
  308. "drillz": "entry_eval",
  309. "travelz": "entry_eval",
  310. "feedrate": "entry_eval",
  311. "toolselection": "entry_text"
  312. })
  313. # TODO: Document this.
  314. self.tool_cbs = {}
  315. # Attributes to be included in serialization
  316. # Always append to it because it carries contents
  317. # from predecessors.
  318. self.ser_attrs += ['options', 'kind']
  319. def convert_units(self, units):
  320. factor = Excellon.convert_units(self, units)
  321. self.options['drillz'] *= factor
  322. self.options['travelz'] *= factor
  323. self.options['feedrate'] *= factor
  324. def plot(self):
  325. # Does all the required setup and returns False
  326. # if the 'ptint' option is set to False.
  327. if not FlatCAMObj.plot(self):
  328. return
  329. try:
  330. _ = iter(self.solid_geometry)
  331. except TypeError:
  332. self.solid_geometry = [self.solid_geometry]
  333. # Plot excellon (All polygons?)
  334. if self.options["solid"]:
  335. for geo in self.solid_geometry:
  336. patch = PolygonPatch(geo,
  337. facecolor="#C40000",
  338. edgecolor="#750000",
  339. alpha=0.75,
  340. zorder=3)
  341. self.axes.add_patch(patch)
  342. else:
  343. for geo in self.solid_geometry:
  344. x, y = geo.exterior.coords.xy
  345. self.axes.plot(x, y, 'r-')
  346. for ints in geo.interiors:
  347. x, y = ints.coords.xy
  348. self.axes.plot(x, y, 'g-')
  349. #self.app.plotcanvas.auto_adjust_axes()
  350. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  351. def show_tool_chooser(self):
  352. win = Gtk.Window()
  353. box = Gtk.Box(spacing=2)
  354. box.set_orientation(Gtk.Orientation(1))
  355. win.add(box)
  356. for tool in self.tools:
  357. self.tool_cbs[tool] = Gtk.CheckButton(label=tool + ": " + str(self.tools[tool]))
  358. box.pack_start(self.tool_cbs[tool], False, False, 1)
  359. button = Gtk.Button(label="Accept")
  360. box.pack_start(button, False, False, 1)
  361. win.show_all()
  362. def on_accept(widget):
  363. win.destroy()
  364. tool_list = []
  365. for toolx in self.tool_cbs:
  366. if self.tool_cbs[toolx].get_active():
  367. tool_list.append(toolx)
  368. self.options["toolselection"] = ", ".join(tool_list)
  369. self.to_form()
  370. button.connect("activate", on_accept)
  371. button.connect("clicked", on_accept)
  372. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  373. """
  374. Represents G-Code.
  375. """
  376. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  377. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  378. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  379. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia)
  380. FlatCAMObj.__init__(self, name)
  381. self.kind = "cncjob"
  382. self.options.update({
  383. "plot": True,
  384. "tooldia": 0.4 / 25.4 # 0.4mm in inches
  385. })
  386. self.form_kinds.update({
  387. "plot": "cb",
  388. "tooldia": "entry_eval"
  389. })
  390. # Attributes to be included in serialization
  391. # Always append to it because it carries contents
  392. # from predecessors.
  393. self.ser_attrs += ['options', 'kind']
  394. def plot(self):
  395. # Does all the required setup and returns False
  396. # if the 'ptint' option is set to False.
  397. if not FlatCAMObj.plot(self):
  398. return
  399. self.plot2(self.axes, tooldia=self.options["tooldia"])
  400. self.app.plotcanvas.auto_adjust_axes()
  401. def convert_units(self, units):
  402. factor = CNCjob.convert_units(self, units)
  403. print "FlatCAMCNCjob.convert_units()"
  404. self.options["tooldia"] *= factor
  405. class FlatCAMGeometry(FlatCAMObj, Geometry):
  406. """
  407. Geometric object not associated with a specific
  408. format.
  409. """
  410. def __init__(self, name):
  411. FlatCAMObj.__init__(self, name)
  412. Geometry.__init__(self)
  413. self.kind = "geometry"
  414. self.options.update({
  415. "plot": True,
  416. "solid": False,
  417. "multicolored": False,
  418. "cutz": -0.002,
  419. "travelz": 0.1,
  420. "feedrate": 5.0,
  421. "cnctooldia": 0.4 / 25.4,
  422. "painttooldia": 0.0625,
  423. "paintoverlap": 0.15,
  424. "paintmargin": 0.01
  425. })
  426. self.form_kinds.update({
  427. "plot": "cb",
  428. "solid": "cb",
  429. "multicolored": "cb",
  430. "cutz": "entry_eval",
  431. "travelz": "entry_eval",
  432. "feedrate": "entry_eval",
  433. "cnctooldia": "entry_eval",
  434. "painttooldia": "entry_eval",
  435. "paintoverlap": "entry_eval",
  436. "paintmargin": "entry_eval"
  437. })
  438. # Attributes to be included in serialization
  439. # Always append to it because it carries contents
  440. # from predecessors.
  441. self.ser_attrs += ['options', 'kind']
  442. def scale(self, factor):
  443. """
  444. Scales all geometry by a given factor.
  445. :param factor: Factor by which to scale the object's geometry/
  446. :type factor: float
  447. :return: None
  448. :rtype: None
  449. """
  450. if type(self.solid_geometry) == list:
  451. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  452. for g in self.solid_geometry]
  453. else:
  454. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  455. origin=(0, 0))
  456. def offset(self, vect):
  457. """
  458. Offsets all geometry by a given vector/
  459. :param vect: (x, y) vector by which to offset the object's geometry.
  460. :type vect: tuple
  461. :return: None
  462. :rtype: None
  463. """
  464. dx, dy = vect
  465. if type(self.solid_geometry) == list:
  466. self.solid_geometry = [affinity.translate(g, xoff=dx, yoff=dy)
  467. for g in self.solid_geometry]
  468. else:
  469. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  470. def convert_units(self, units):
  471. factor = Geometry.convert_units(self, units)
  472. self.options['cutz'] *= factor
  473. self.options['travelz'] *= factor
  474. self.options['feedrate'] *= factor
  475. self.options['cnctooldia'] *= factor
  476. self.options['painttooldia'] *= factor
  477. self.options['paintmargin'] *= factor
  478. return factor
  479. def plot(self):
  480. """
  481. Plots the object into its axes. If None, of if the axes
  482. are not part of the app's figure, it fetches new ones.
  483. :return: None
  484. """
  485. # Does all the required setup and returns False
  486. # if the 'ptint' option is set to False.
  487. if not FlatCAMObj.plot(self):
  488. return
  489. # Make sure solid_geometry is iterable.
  490. try:
  491. _ = iter(self.solid_geometry)
  492. except TypeError:
  493. self.solid_geometry = [self.solid_geometry]
  494. for geo in self.solid_geometry:
  495. if type(geo) == Polygon:
  496. x, y = geo.exterior.coords.xy
  497. self.axes.plot(x, y, 'r-')
  498. for ints in geo.interiors:
  499. x, y = ints.coords.xy
  500. self.axes.plot(x, y, 'r-')
  501. continue
  502. if type(geo) == LineString or type(geo) == LinearRing:
  503. x, y = geo.coords.xy
  504. self.axes.plot(x, y, 'r-')
  505. continue
  506. if type(geo) == MultiPolygon:
  507. for poly in geo:
  508. x, y = poly.exterior.coords.xy
  509. self.axes.plot(x, y, 'r-')
  510. for ints in poly.interiors:
  511. x, y = ints.coords.xy
  512. self.axes.plot(x, y, 'r-')
  513. continue
  514. print "WARNING: Did not plot:", str(type(geo))
  515. self.app.plotcanvas.auto_adjust_axes()
  516. ########################################
  517. ## App ##
  518. ########################################
  519. class App:
  520. """
  521. The main application class. The constructor starts the GUI.
  522. """
  523. def __init__(self):
  524. """
  525. Starts the application. Takes no parameters.
  526. :return: app
  527. :rtype: App
  528. """
  529. # Needed to interact with the GUI from other threads.
  530. GObject.threads_init()
  531. # GLib.log_set_handler()
  532. #### GUI ####
  533. self.gladefile = "FlatCAM.ui"
  534. self.builder = Gtk.Builder()
  535. self.builder.add_from_file(self.gladefile)
  536. self.window = self.builder.get_object("window1")
  537. self.position_label = self.builder.get_object("label3")
  538. self.grid = self.builder.get_object("grid1")
  539. self.notebook = self.builder.get_object("notebook1")
  540. self.info_label = self.builder.get_object("label_status")
  541. self.progress_bar = self.builder.get_object("progressbar")
  542. self.progress_bar.set_show_text(True)
  543. self.units_label = self.builder.get_object("label_units")
  544. self.toolbar = self.builder.get_object("toolbar_main")
  545. # White (transparent) background on the "Options" tab.
  546. self.builder.get_object("vp_options").override_background_color(Gtk.StateType.NORMAL,
  547. Gdk.RGBA(1, 1, 1, 1))
  548. # Combo box to choose between project and application options.
  549. self.combo_options = self.builder.get_object("combo_options")
  550. self.combo_options.set_active(1)
  551. self.setup_project_list() # The "Project" tab
  552. self.setup_component_editor() # The "Selected" tab
  553. self.setup_toolbar()
  554. #### Event handling ####
  555. self.builder.connect_signals(self)
  556. #### Make plot area ####
  557. self.plotcanvas = PlotCanvas(self.grid)
  558. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  559. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  560. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  561. self.setup_tooltips()
  562. #### DATA ####
  563. self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
  564. self.setup_obj_classes()
  565. self.stuff = {} # FlatCAMObj's by name
  566. self.mouse = None # Mouse coordinates over plot
  567. # What is selected by the user. It is
  568. # a key if self.stuff
  569. self.selected_item_name = None
  570. # Used to inhibit the on_options_update callback when
  571. # the options are being changed by the program and not the user.
  572. self.options_update_ignore = False
  573. self.toggle_units_ignore = False
  574. self.defaults = {
  575. "units": "in"
  576. } # Application defaults
  577. ## Current Project ##
  578. self.options = {} # Project options
  579. self.project_filename = None
  580. self.form_kinds = {
  581. "units": "radio"
  582. }
  583. self.radios = {"units": {"rb_inch": "IN", "rb_mm": "MM"},
  584. "gerber_gaps": {"rb_app_2tb": "tb", "rb_app_2lr": "lr", "rb_app_4": "4"}}
  585. self.radios_inv = {"units": {"IN": "rb_inch", "MM": "rb_mm"},
  586. "gerber_gaps": {"tb": "rb_app_2tb", "lr": "rb_app_2lr", "4": "rb_app_4"}}
  587. # Options for each kind of FlatCAMObj.
  588. # Example: 'gerber_plot': 'cb'. The widget name would be: 'cb_app_gerber_plot'
  589. for FlatCAMClass in [FlatCAMExcellon, FlatCAMGeometry, FlatCAMGerber, FlatCAMCNCjob]:
  590. obj = FlatCAMClass("no_name")
  591. for option in obj.form_kinds:
  592. self.form_kinds[obj.kind + "_" + option] = obj.form_kinds[option]
  593. # if obj.form_kinds[option] == "radio":
  594. # self.radios.update({obj.kind + "_" + option: obj.radios[option]})
  595. # self.radios_inv.update({obj.kind + "_" + option: obj.radios_inv[option]})
  596. ## Event subscriptions ##
  597. self.plot_click_subscribers = {}
  598. self.plot_mousemove_subscribers = {}
  599. ## Tools ##
  600. self.measure = Measurement(self.builder.get_object("box39"), self.plotcanvas.axes,
  601. self.plot_click_subscribers, self.plot_mousemove_subscribers)
  602. # Toolbar icon
  603. # TODO: Where should I put this? Tool should have a method to add to toolbar?
  604. meas_ico = Gtk.Image.new_from_file('share/measure32.png')
  605. measure = Gtk.ToolButton.new(meas_ico, "")
  606. measure.connect("clicked", self.measure.toggle_active)
  607. measure.set_tooltip_markup("<b>Measure Tool:</b> Enable/disable tool.\n" +
  608. "Click on point to set reference.\n" +
  609. "(Click on plot and hit <b>m</b>)")
  610. self.toolbar.insert(measure, -1)
  611. #### Initialization ####
  612. self.load_defaults()
  613. self.options.update(self.defaults) # Copy app defaults to project options
  614. self.options2form() # Populate the app defaults form
  615. self.units_label.set_text("[" + self.options["units"] + "]")
  616. #### Check for updates ####
  617. self.version = 2
  618. t1 = threading.Thread(target=self.versionCheck)
  619. t1.daemon = True
  620. t1.start()
  621. #### For debugging only ###
  622. def somethreadfunc(app_obj):
  623. print "Hello World!"
  624. t = threading.Thread(target=somethreadfunc, args=(self,))
  625. t.daemon = True
  626. t.start()
  627. ########################################
  628. ## START ##
  629. ########################################
  630. self.icon256 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon256.png')
  631. self.icon48 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon48.png')
  632. self.icon16 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon16.png')
  633. Gtk.Window.set_default_icon_list([self.icon16, self.icon48, self.icon256])
  634. self.window.set_title("FlatCAM - Alpha 3 UNSTABLE - Check for updates!")
  635. self.window.set_default_size(900, 600)
  636. self.window.show_all()
  637. def setup_toolbar(self):
  638. # Zoom fit
  639. zf_ico = Gtk.Image.new_from_file('share/zoom_fit32.png')
  640. zoom_fit = Gtk.ToolButton.new(zf_ico, "")
  641. zoom_fit.connect("clicked", self.on_zoom_fit)
  642. zoom_fit.set_tooltip_markup("Zoom Fit.\n(Click on plot and hit <b>1</b>)")
  643. self.toolbar.insert(zoom_fit, -1)
  644. # Zoom out
  645. zo_ico = Gtk.Image.new_from_file('share/zoom_out32.png')
  646. zoom_out = Gtk.ToolButton.new(zo_ico, "")
  647. zoom_out.connect("clicked", self.on_zoom_out)
  648. zoom_out.set_tooltip_markup("Zoom Out.\n(Click on plot and hit <b>2</b>)")
  649. self.toolbar.insert(zoom_out, -1)
  650. # Zoom in
  651. zi_ico = Gtk.Image.new_from_file('share/zoom_in32.png')
  652. zoom_in = Gtk.ToolButton.new(zi_ico, "")
  653. zoom_in.connect("clicked", self.on_zoom_in)
  654. zoom_in.set_tooltip_markup("Zoom In.\n(Click on plot and hit <b>3</b>)")
  655. self.toolbar.insert(zoom_in, -1)
  656. # Clear plot
  657. cp_ico = Gtk.Image.new_from_file('share/clear_plot32.png')
  658. clear_plot = Gtk.ToolButton.new(cp_ico, "")
  659. clear_plot.connect("clicked", self.on_clear_plots)
  660. clear_plot.set_tooltip_markup("Clear Plot")
  661. self.toolbar.insert(clear_plot, -1)
  662. # Replot
  663. rp_ico = Gtk.Image.new_from_file('share/replot32.png')
  664. replot = Gtk.ToolButton.new(rp_ico, "")
  665. replot.connect("clicked", self.on_toolbar_replot)
  666. replot.set_tooltip_markup("Re-plot all")
  667. self.toolbar.insert(replot, -1)
  668. # Delete item
  669. del_ico = Gtk.Image.new_from_file('share/delete32.png')
  670. delete = Gtk.ToolButton.new(del_ico, "")
  671. delete.connect("clicked", self.on_delete)
  672. delete.set_tooltip_markup("Delete selected\nobject.")
  673. self.toolbar.insert(delete, -1)
  674. def setup_obj_classes(self):
  675. """
  676. Sets up application specifics on the FlatCAMObj class.
  677. :return: None
  678. """
  679. FlatCAMObj.app = self
  680. def setup_project_list(self):
  681. """
  682. Sets up list or Tree where whatever has been loaded or created is
  683. displayed.
  684. :return: None
  685. """
  686. self.store = Gtk.ListStore(str)
  687. self.tree = Gtk.TreeView(self.store)
  688. #self.list = Gtk.ListBox()
  689. self.tree.connect("row_activated", self.on_row_activated)
  690. self.tree_select = self.tree.get_selection()
  691. self.signal_id = self.tree_select.connect("changed", self.on_tree_selection_changed)
  692. renderer = Gtk.CellRendererText()
  693. column = Gtk.TreeViewColumn("Objects", renderer, text=0)
  694. self.tree.append_column(column)
  695. self.builder.get_object("box_project").pack_start(self.tree, False, False, 1)
  696. def setup_component_editor(self):
  697. """
  698. Initial configuration of the component editor. Creates
  699. a page titled "Selection" on the notebook on the left
  700. side of the main window.
  701. :return: None
  702. """
  703. box_selected = self.builder.get_object("box_selected")
  704. # Remove anything else in the box
  705. box_children = box_selected.get_children()
  706. for child in box_children:
  707. box_selected.remove(child)
  708. box1 = Gtk.Box(Gtk.Orientation.VERTICAL)
  709. label1 = Gtk.Label("Choose an item from Project")
  710. box1.pack_start(label1, True, False, 1)
  711. box_selected.pack_start(box1, True, True, 0)
  712. #box_selected.show()
  713. box1.show()
  714. label1.show()
  715. def info(self, text):
  716. """
  717. Show text on the status bar.
  718. :param text: Text to display.
  719. :type text: str
  720. :return: None
  721. """
  722. self.info_label.set_text(text)
  723. def build_list(self):
  724. """
  725. Clears and re-populates the list of objects in currently
  726. in the project.
  727. :return: None
  728. """
  729. print "build_list(): clearing"
  730. self.tree_select.unselect_all()
  731. self.store.clear()
  732. print "repopulating...",
  733. for key in self.stuff:
  734. print key,
  735. self.store.append([key])
  736. print
  737. def get_radio_value(self, radio_set):
  738. """
  739. Returns the radio_set[key] of the radiobutton
  740. whose name is key is active.
  741. :param radio_set: A dictionary containing widget_name: value pairs.
  742. :type radio_set: dict
  743. :return: radio_set[key]
  744. """
  745. for name in radio_set:
  746. if self.builder.get_object(name).get_active():
  747. return radio_set[name]
  748. def plot_all(self):
  749. """
  750. Re-generates all plots from all objects.
  751. :return: None
  752. """
  753. self.plotcanvas.clear()
  754. self.set_progress_bar(0.1, "Re-plotting...")
  755. def thread_func(app_obj):
  756. percentage = 0.1
  757. try:
  758. delta = 0.9 / len(self.stuff)
  759. except ZeroDivisionError:
  760. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  761. return
  762. for i in self.stuff:
  763. self.stuff[i].plot()
  764. percentage += delta
  765. GLib.idle_add(lambda: app_obj.set_progress_bar(percentage, "Re-plotting..."))
  766. #app_obj.plotcanvas.auto_adjust_axes()
  767. #self.on_zoom_fit(None)
  768. GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes)
  769. GLib.idle_add(lambda: self.on_zoom_fit(None))
  770. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  771. t = threading.Thread(target=thread_func, args=(self,))
  772. t.daemon = True
  773. t.start()
  774. def get_eval(self, widget_name):
  775. """
  776. Runs eval() on the on the text entry of name 'widget_name'
  777. and returns the results.
  778. :param widget_name: Name of Gtk.Entry
  779. :type widget_name: str
  780. :return: Depends on contents of the entry text.
  781. """
  782. value = self.builder.get_object(widget_name).get_text()
  783. if value == "":
  784. value = "None"
  785. try:
  786. evald = eval(value)
  787. return evald
  788. except:
  789. self.info("Could not evaluate: " + value)
  790. return None
  791. def set_list_selection(self, name):
  792. """
  793. Marks a given object as selected in the list ob objects
  794. in the GUI. This selection will in turn trigger
  795. ``self.on_tree_selection_changed()``.
  796. :param name: Name of the object.
  797. :type name: str
  798. :return: None
  799. """
  800. iter = self.store.get_iter_first()
  801. while iter is not None and self.store[iter][0] != name:
  802. iter = self.store.iter_next(iter)
  803. self.tree_select.unselect_all()
  804. self.tree_select.select_iter(iter)
  805. # Need to return False such that GLib.idle_add
  806. # or .timeout_add do not repeat.
  807. return False
  808. def new_object(self, kind, name, initialize):
  809. """
  810. Creates a new specalized FlatCAMObj and attaches it to the application,
  811. this is, updates the GUI accordingly, any other records and plots it.
  812. :param kind: The kind of object to create. One of 'gerber',
  813. 'excellon', 'cncjob' and 'geometry'.
  814. :type kind: str
  815. :param name: Name for the object.
  816. :type name: str
  817. :param initialize: Function to run after creation of the object
  818. but before it is attached to the application. The function is
  819. called with 2 parameters: the new object and the App instance.
  820. :type initialize: function
  821. :return: None
  822. :rtype: None
  823. """
  824. ### Check for existing name
  825. if name in self.stuff:
  826. ## Create a new name
  827. # Ends with number?
  828. match = re.search(r'(.*[^\d])?(\d+)$', name)
  829. if match: # Yes: Increment the number!
  830. base = match.group(1) or ''
  831. num = int(match.group(2))
  832. name = base + str(num + 1)
  833. else: # No: add a number!
  834. name += "_1"
  835. # Create object
  836. classdict = {
  837. "gerber": FlatCAMGerber,
  838. "excellon": FlatCAMExcellon,
  839. "cncjob": FlatCAMCNCjob,
  840. "geometry": FlatCAMGeometry
  841. }
  842. obj = classdict[kind](name)
  843. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  844. # Initialize as per user request
  845. # User must take care to implement initialize
  846. # in a thread-safe way as is is likely that we
  847. # have been invoked in a separate thread.
  848. #initialize(obj, self)
  849. # Set default options from self.options
  850. for option in self.options:
  851. if option.find(kind + "_") == 0:
  852. oname = option[len(kind)+1:]
  853. obj.options[oname] = self.options[option]
  854. # Initialize as per user request
  855. # User must take care to implement initialize
  856. # in a thread-safe way as is is likely that we
  857. # have been invoked in a separate thread.
  858. initialize(obj, self)
  859. # Check units and convert if necessary
  860. if self.options["units"].upper() != obj.units.upper():
  861. GLib.idle_add(lambda: self.info("Converting units to " + self.options["units"] + "."))
  862. obj.convert_units(self.options["units"])
  863. # Add to our records
  864. self.stuff[name] = obj
  865. # Update GUI list and select it (Thread-safe?)
  866. self.store.append([name])
  867. #self.build_list()
  868. GLib.idle_add(lambda: self.set_list_selection(name))
  869. # TODO: Gtk.notebook.set_current_page is not known to
  870. # TODO: return False. Fix this??
  871. GLib.timeout_add(100, lambda: self.notebook.set_current_page(1))
  872. # Plot
  873. # TODO: (Thread-safe?)
  874. obj.plot()
  875. # TODO: Threading dissaster!
  876. GLib.idle_add(lambda: self.on_zoom_fit(None))
  877. return obj
  878. def set_progress_bar(self, percentage, text=""):
  879. """
  880. Sets the application's progress bar to a given frac_digits and text.
  881. :param percentage: The frac_digits (0.0-1.0) of the progress.
  882. :type percentage: float
  883. :param text: Text to display on the progress bar.
  884. :type text: str
  885. :return: None
  886. """
  887. self.progress_bar.set_text(text)
  888. self.progress_bar.set_fraction(percentage)
  889. return False
  890. def get_current(self):
  891. """
  892. Returns the currently selected FlatCAMObj in the application.
  893. :return: Currently selected FlatCAMObj in the application.
  894. :rtype: FlatCAMObj or None
  895. """
  896. # TODO: Could possibly read the form into the object here.
  897. # But there are some cases when the form for the object
  898. # is not up yet. See on_tree_selection_changed.
  899. try:
  900. return self.stuff[self.selected_item_name]
  901. except:
  902. return None
  903. def load_defaults(self):
  904. """
  905. Loads the aplication's default settings from defaults.json into
  906. ``self.defaults``.
  907. :return: None
  908. """
  909. try:
  910. f = open("defaults.json")
  911. options = f.read()
  912. f.close()
  913. except:
  914. self.info("ERROR: Could not load defaults file.")
  915. return
  916. try:
  917. defaults = json.loads(options)
  918. except:
  919. e = sys.exc_info()[0]
  920. print e
  921. self.info("ERROR: Failed to parse defaults file.")
  922. return
  923. self.defaults.update(defaults)
  924. def read_form(self):
  925. """
  926. Reads the options form into self.defaults/self.options.
  927. :return: None
  928. :rtype: None
  929. """
  930. combo_sel = self.combo_options.get_active()
  931. options_set = [self.options, self.defaults][combo_sel]
  932. for option in options_set:
  933. self.read_form_item(option, options_set)
  934. def read_form_item(self, name, dest):
  935. """
  936. Reads the value of a form item in the defaults/options form and
  937. saves it to the corresponding dictionary.
  938. :param name: Name of the form item. A key in ``self.defaults`` or
  939. ``self.options``.
  940. :type name: str
  941. :param dest: Dictionary to which to save the value.
  942. :type dest: dict
  943. :return: None
  944. """
  945. fkind = self.form_kinds[name]
  946. fname = fkind + "_" + "app" + "_" + name
  947. if fkind == 'entry_text':
  948. dest[name] = self.builder.get_object(fname).get_text()
  949. return
  950. if fkind == 'entry_eval':
  951. dest[name] = self.get_eval(fname)
  952. return
  953. if fkind == 'cb':
  954. dest[name] = self.builder.get_object(fname).get_active()
  955. return
  956. if fkind == 'radio':
  957. dest[name] = self.get_radio_value(self.radios[name])
  958. return
  959. print "Unknown kind of form item:", fkind
  960. def options2form(self):
  961. """
  962. Sets the 'Project Options' or 'Application Defaults' form with values from
  963. ``self.options`` or ``self.defaults``.
  964. :return: None
  965. :rtype: None
  966. """
  967. # Set the on-change callback to do nothing while we do the changes.
  968. self.options_update_ignore = True
  969. self.toggle_units_ignore = True
  970. combo_sel = self.combo_options.get_active()
  971. options_set = [self.options, self.defaults][combo_sel]
  972. for option in options_set:
  973. self.set_form_item(option, options_set[option])
  974. self.options_update_ignore = False
  975. self.toggle_units_ignore = False
  976. def set_form_item(self, name, value):
  977. """
  978. Sets a form item 'name' in the GUI with the given 'value'. The syntax of
  979. form names in the GUI is <kind>_app_<name>, where kind is one of: rb (radio button),
  980. cb (check button), entry_eval or entry_text (entry), combo (combo box). name is
  981. whatever name it's been given. For self.defaults, name is a key in the dictionary.
  982. :param name: Name of the form field.
  983. :type name: str
  984. :param value: The value to set the form field to.
  985. :type value: Depends on field kind.
  986. :return: None
  987. """
  988. if name not in self.form_kinds:
  989. print "WARNING: Tried to set unknown option/form item:", name
  990. return
  991. fkind = self.form_kinds[name]
  992. fname = fkind + "_" + "app" + "_" + name
  993. if fkind == 'entry_eval' or fkind == 'entry_text':
  994. try:
  995. self.builder.get_object(fname).set_text(str(value))
  996. except:
  997. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  998. return
  999. if fkind == 'cb':
  1000. try:
  1001. self.builder.get_object(fname).set_active(value)
  1002. except:
  1003. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1004. return
  1005. if fkind == 'radio':
  1006. try:
  1007. self.builder.get_object(self.radios_inv[name][value]).set_active(True)
  1008. except:
  1009. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1010. return
  1011. print "Unknown kind of form item:", fkind
  1012. def save_project(self, filename):
  1013. """
  1014. Saves the current project to the specified file.
  1015. :param filename: Name of the file in which to save.
  1016. :type filename: str
  1017. :return: None
  1018. """
  1019. # Capture the latest changes
  1020. try:
  1021. self.get_current().read_form()
  1022. except:
  1023. pass
  1024. d = {"objs": [self.stuff[o].to_dict() for o in self.stuff],
  1025. "options": self.options}
  1026. try:
  1027. f = open(filename, 'w')
  1028. except:
  1029. print "ERROR: Failed to open file for saving:", filename
  1030. return
  1031. try:
  1032. json.dump(d, f, default=to_dict)
  1033. except:
  1034. print "ERROR: File open but failed to write:", filename
  1035. f.close()
  1036. return
  1037. f.close()
  1038. def open_project(self, filename):
  1039. """
  1040. Loads a project from the specified file.
  1041. :param filename: Name of the file from which to load.
  1042. :type filename: str
  1043. :return: None
  1044. """
  1045. try:
  1046. f = open(filename, 'r')
  1047. except:
  1048. print "WARNING: Failed to open project file:", filename
  1049. return
  1050. try:
  1051. d = json.load(f, object_hook=dict2obj)
  1052. except:
  1053. print "WARNING: Failed to parse project file:", filename
  1054. f.close()
  1055. return
  1056. # Clear the current project
  1057. self.on_file_new(None)
  1058. # Project options
  1059. self.options.update(d['options'])
  1060. self.project_filename = filename
  1061. self.units_label.set_text(self.options["units"])
  1062. # Re create objects
  1063. for obj in d['objs']:
  1064. def obj_init(obj_inst, app_inst):
  1065. obj_inst.from_dict(obj)
  1066. self.new_object(obj['kind'], obj['options']['name'], obj_init)
  1067. self.info("Project loaded from: " + filename)
  1068. def populate_objects_combo(self, combo):
  1069. """
  1070. Populates a Gtk.Comboboxtext with the list of the object in the project.
  1071. :param combo: Name or instance of the comboboxtext.
  1072. :type combo: str or Gtk.ComboBoxText
  1073. :return: None
  1074. """
  1075. print "Populating combo!"
  1076. if type(combo) == str:
  1077. combo = self.builder.get_object(combo)
  1078. combo.remove_all()
  1079. for obj in self.stuff:
  1080. combo.append_text(obj)
  1081. def versionCheck(self, *args):
  1082. """
  1083. Checks for the latest version of the program. Alerts the
  1084. user if theirs is outdated. This method is meant to be run
  1085. in a saeparate thread.
  1086. :return: None
  1087. """
  1088. try:
  1089. f = urllib.urlopen("http://caram.cl/flatcam/VERSION") # TODO: Hardcoded.
  1090. except:
  1091. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1092. return
  1093. try:
  1094. data = json.load(f)
  1095. except:
  1096. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1097. f.close()
  1098. return
  1099. f.close()
  1100. if self.version >= data["version"]:
  1101. GLib.idle_add(lambda: self.info("FlatCAM is up to date!"))
  1102. return
  1103. label = Gtk.Label("There is a newer version of FlatCAM\n" +
  1104. "available for download:\n\n" +
  1105. data["name"] + "\n\n" + data["message"])
  1106. dialog = Gtk.Dialog("Newer Version Available", self.window, 0,
  1107. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1108. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1109. dialog.set_default_size(150, 100)
  1110. dialog.set_modal(True)
  1111. box = dialog.get_content_area()
  1112. box.set_border_width(10)
  1113. box.add(label)
  1114. def do_dialog():
  1115. dialog.show_all()
  1116. response = dialog.run()
  1117. dialog.destroy()
  1118. GLib.idle_add(lambda: do_dialog())
  1119. return
  1120. def setup_tooltips(self):
  1121. tooltips = {
  1122. "cb_gerber_plot": "Plot this object on the main window.",
  1123. "cb_gerber_mergepolys": "Show overlapping polygons as single.",
  1124. "cb_gerber_solid": "Paint inside polygons.",
  1125. "cb_gerber_multicolored": "Draw polygons with different colors."
  1126. }
  1127. for widget in tooltips:
  1128. self.builder.get_object(widget).set_tooltip_markup(tooltips[widget])
  1129. def do_nothing(self, param):
  1130. return
  1131. ########################################
  1132. ## EVENT HANDLERS ##
  1133. ########################################
  1134. def on_offset_object(self, widget):
  1135. """
  1136. Offsets the object's geometry by the vector specified
  1137. in the form. Re-plots.
  1138. :param widget: Ignored
  1139. :return: None
  1140. """
  1141. obj = self.get_current()
  1142. obj.read_form()
  1143. assert isinstance(obj, FlatCAMObj)
  1144. try:
  1145. vect = self.get_eval("entry_eval_" + obj.kind + "_offset")
  1146. except:
  1147. self.info("ERROR: Vector is not in (x, y) format.")
  1148. return
  1149. assert isinstance(obj, Geometry)
  1150. obj.offset(vect)
  1151. obj.plot()
  1152. return
  1153. def on_cb_plot_toggled(self, widget):
  1154. """
  1155. Callback for toggling the "Plot" checkbox. Re-plots.
  1156. :param widget: Ignored.
  1157. :return: None
  1158. """
  1159. self.get_current().read_form()
  1160. self.get_current().plot()
  1161. def on_about(self, widget):
  1162. """
  1163. Opens the 'About' dialog box.
  1164. :param widget: Ignored.
  1165. :return: None
  1166. """
  1167. about = self.builder.get_object("aboutdialog")
  1168. response = about.run()
  1169. #about.destroy()
  1170. about.hide()
  1171. def on_create_mirror(self, widget):
  1172. """
  1173. Creates a mirror image of an object to be used as a bottom layer.
  1174. :param widget: Ignored.
  1175. :return: None
  1176. """
  1177. # TODO: Move (some of) this to camlib!
  1178. # Object to mirror
  1179. try:
  1180. obj_name = self.builder.get_object("comboboxtext_bottomlayer").get_active_text()
  1181. fcobj = self.stuff[obj_name]
  1182. except KeyError:
  1183. self.info("WARNING: Cannot mirror that object.")
  1184. return
  1185. # For now, lets limit to Gerbers and Excellons.
  1186. # assert isinstance(gerb, FlatCAMGerber)
  1187. if not isinstance(fcobj, FlatCAMGerber) and not isinstance(fcobj, FlatCAMExcellon):
  1188. self.info("ERROR: Only Gerber and Excellon objects can be mirrored.")
  1189. return
  1190. # Mirror axis "X" or "Y
  1191. axis = self.get_radio_value({"rb_mirror_x": "X",
  1192. "rb_mirror_y": "Y"})
  1193. mode = self.get_radio_value({"rb_mirror_box": "box",
  1194. "rb_mirror_point": "point"})
  1195. if mode == "point": # A single point defines the mirror axis
  1196. # TODO: Error handling
  1197. px, py = eval(self.point_entry.get_text())
  1198. else: # The axis is the line dividing the box in the middle
  1199. name = self.box_combo.get_active_text()
  1200. bb_obj = self.stuff[name]
  1201. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1202. px = 0.5*(xmin+xmax)
  1203. py = 0.5*(ymin+ymax)
  1204. # Do the mirroring
  1205. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1206. # mirrored = affinity.scale(fcobj.solid_geometry, xscale, yscale, origin=(px, py))
  1207. #
  1208. # def obj_init(obj_inst, app_inst):
  1209. # obj_inst.solid_geometry = mirrored
  1210. #
  1211. # self.new_object("gerber", fcobj.options["name"] + "_mirror", obj_init)
  1212. fcobj.mirror(axis, [px, py])
  1213. fcobj.plot()
  1214. #self.on_update_plot(None)
  1215. def on_create_aligndrill(self, widget):
  1216. """
  1217. Creates alignment holes Excellon object. Creates mirror duplicates
  1218. of the specified holes around the specified axis.
  1219. :param widget: Ignored.
  1220. :return: None
  1221. """
  1222. # Mirror axis. Same as in on_create_mirror.
  1223. axis = self.get_radio_value({"rb_mirror_x": "X",
  1224. "rb_mirror_y": "Y"})
  1225. # TODO: Error handling
  1226. mode = self.get_radio_value({"rb_mirror_box": "box",
  1227. "rb_mirror_point": "point"})
  1228. if mode == "point":
  1229. px, py = eval(self.point_entry.get_text())
  1230. else:
  1231. name = self.box_combo.get_active_text()
  1232. bb_obj = self.stuff[name]
  1233. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1234. px = 0.5*(xmin+xmax)
  1235. py = 0.5*(ymin+ymax)
  1236. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1237. # Tools
  1238. dia = self.get_eval("entry_dblsided_alignholediam")
  1239. tools = {"1": {"C": dia}}
  1240. # Parse hole list
  1241. # TODO: Better parsing
  1242. holes = self.builder.get_object("entry_dblsided_alignholes").get_text()
  1243. holes = eval("[" + holes + "]")
  1244. drills = []
  1245. for hole in holes:
  1246. point = Point(hole)
  1247. point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  1248. drills.append({"point": point, "tool": "1"})
  1249. drills.append({"point": point_mirror, "tool": "1"})
  1250. def obj_init(obj_inst, app_inst):
  1251. obj_inst.tools = tools
  1252. obj_inst.drills = drills
  1253. obj_inst.create_geometry()
  1254. self.new_object("excellon", "Alignment Drills", obj_init)
  1255. def on_toggle_pointbox(self, widget):
  1256. """
  1257. Callback for radio selection change between point and box in the
  1258. Double-sided PCB tool. Updates the UI accordingly.
  1259. :param widget: Ignored.
  1260. :return: None
  1261. """
  1262. # Where the entry or combo go
  1263. box = self.builder.get_object("box_pointbox")
  1264. # Clear contents
  1265. children = box.get_children()
  1266. for child in children:
  1267. box.remove(child)
  1268. choice = self.get_radio_value({"rb_mirror_point": "point",
  1269. "rb_mirror_box": "box"})
  1270. if choice == "point":
  1271. self.point_entry = Gtk.Entry()
  1272. self.builder.get_object("box_pointbox").pack_start(self.point_entry,
  1273. False, False, 1)
  1274. self.point_entry.show()
  1275. else:
  1276. self.box_combo = Gtk.ComboBoxText()
  1277. self.builder.get_object("box_pointbox").pack_start(self.box_combo,
  1278. False, False, 1)
  1279. self.populate_objects_combo(self.box_combo)
  1280. self.box_combo.show()
  1281. def on_tools_doublesided(self, param):
  1282. """
  1283. Callback for menu item Tools->Double Sided PCB Tool. Launches the
  1284. tool placing its UI in the "Tool" tab in the notebook.
  1285. :param param: Ignored.
  1286. :return: None
  1287. """
  1288. # Were are we drawing the UI
  1289. box_tool = self.builder.get_object("box_tool")
  1290. # Remove anything else in the box
  1291. box_children = box_tool.get_children()
  1292. for child in box_children:
  1293. box_tool.remove(child)
  1294. # Get the UI
  1295. osw = self.builder.get_object("offscreenwindow_dblsided")
  1296. sw = self.builder.get_object("sw_dblsided")
  1297. osw.remove(sw)
  1298. vp = self.builder.get_object("vp_dblsided")
  1299. vp.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(1, 1, 1, 1))
  1300. # Put in the UI
  1301. box_tool.pack_start(sw, True, True, 0)
  1302. # INITIALIZATION
  1303. # Populate combo box
  1304. self.populate_objects_combo("comboboxtext_bottomlayer")
  1305. # Point entry
  1306. self.point_entry = Gtk.Entry()
  1307. box = self.builder.get_object("box_pointbox")
  1308. for child in box.get_children():
  1309. box.remove(child)
  1310. box.pack_start(self.point_entry, False, False, 1)
  1311. # Show the "Tool" tab
  1312. self.notebook.set_current_page(3)
  1313. sw.show_all()
  1314. def on_toggle_units(self, widget):
  1315. """
  1316. Callback for the Units radio-button change in the Options tab.
  1317. Changes the application's default units or the current project's units.
  1318. If changing the project's units, the change propagates to all of
  1319. the objects in the project.
  1320. :param widget: Ignored.
  1321. :return: None
  1322. """
  1323. if self.toggle_units_ignore:
  1324. return
  1325. combo_sel = self.combo_options.get_active()
  1326. options_set = [self.options, self.defaults][combo_sel]
  1327. # Options to scale
  1328. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1329. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1330. 'excellon_travelz', 'excellon_feedrate', 'cncjob_tooldia',
  1331. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1332. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1333. 'geometry_paintmargin']
  1334. def scale_options(factor):
  1335. for dim in dimensions:
  1336. options_set[dim] *= factor
  1337. # The scaling factor depending on choice of units.
  1338. factor = 1/25.4
  1339. if self.builder.get_object('rb_mm').get_active():
  1340. factor = 25.4
  1341. # App units. Convert without warning.
  1342. if combo_sel == 1:
  1343. self.read_form()
  1344. scale_options(factor)
  1345. self.options2form()
  1346. return
  1347. # Changing project units. Warn user.
  1348. label = Gtk.Label("Changing the units of the project causes all geometrical \n" + \
  1349. "properties of all objects to be scaled accordingly. Continue?")
  1350. dialog = Gtk.Dialog("Changing Project Units", self.window, 0,
  1351. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1352. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1353. dialog.set_default_size(150, 100)
  1354. dialog.set_modal(True)
  1355. box = dialog.get_content_area()
  1356. box.set_border_width(10)
  1357. box.add(label)
  1358. dialog.show_all()
  1359. response = dialog.run()
  1360. dialog.destroy()
  1361. if response == Gtk.ResponseType.OK:
  1362. #print "Converting units..."
  1363. #print "Converting options..."
  1364. self.read_form()
  1365. scale_options(factor)
  1366. self.options2form()
  1367. for obj in self.stuff:
  1368. units = self.get_radio_value({"rb_mm": "MM", "rb_inch": "IN"})
  1369. #print "Converting ", obj, " to ", units
  1370. self.stuff[obj].convert_units(units)
  1371. current = self.get_current()
  1372. if current is not None:
  1373. current.to_form()
  1374. self.plot_all()
  1375. else:
  1376. # Undo toggling
  1377. self.toggle_units_ignore = True
  1378. if self.builder.get_object('rb_mm').get_active():
  1379. self.builder.get_object('rb_inch').set_active(True)
  1380. else:
  1381. self.builder.get_object('rb_mm').set_active(True)
  1382. self.toggle_units_ignore = False
  1383. self.read_form()
  1384. self.info("Converted units to %s" % self.options["units"])
  1385. self.units_label.set_text("[" + self.options["units"] + "]")
  1386. def on_file_openproject(self, param):
  1387. """
  1388. Callback for menu item File->Open Project. Opens a file chooser and calls
  1389. ``self.open_project()`` after successful selection of a filename.
  1390. :param param: Ignored.
  1391. :return: None
  1392. """
  1393. def on_success(app_obj, filename):
  1394. app_obj.open_project(filename)
  1395. self.file_chooser_action(on_success)
  1396. def on_file_saveproject(self, param):
  1397. """
  1398. Callback for menu item File->Save Project. Saves the project to
  1399. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1400. if set to None. The project is saved by calling ``self.save_project()``.
  1401. :param param: Ignored.
  1402. :return: None
  1403. """
  1404. if self.project_filename is None:
  1405. self.on_file_saveprojectas(None)
  1406. else:
  1407. self.save_project(self.project_filename)
  1408. self.info("Project saved to: " + self.project_filename)
  1409. def on_file_saveprojectas(self, param):
  1410. """
  1411. Callback for menu item File->Save Project As... Opens a file
  1412. chooser and saves the project to the given file via
  1413. ``self.save_project()``.
  1414. :param param: Ignored.
  1415. :return: None
  1416. """
  1417. def on_success(app_obj, filename):
  1418. assert isinstance(app_obj, App)
  1419. app_obj.save_project(filename)
  1420. self.project_filename = filename
  1421. app_obj.info("Project saved to: " + filename)
  1422. self.file_chooser_save_action(on_success)
  1423. def on_file_saveprojectcopy(self, param):
  1424. """
  1425. Callback for menu item File->Save Project Copy... Opens a file
  1426. chooser and saves the project to the given file via
  1427. ``self.save_project``. It does not update ``self.project_filename`` so
  1428. subsequent save requests are done on the previous known filename.
  1429. :param param: Ignore.
  1430. :return: None
  1431. """
  1432. def on_success(app_obj, filename):
  1433. assert isinstance(app_obj, App)
  1434. app_obj.save_project(filename)
  1435. app_obj.info("Project copy saved to: " + filename)
  1436. self.file_chooser_save_action(on_success)
  1437. def on_options_app2project(self, param):
  1438. """
  1439. Callback for Options->Transfer Options->App=>Project. Copies options
  1440. from application defaults to project defaults.
  1441. :param param: Ignored.
  1442. :return: None
  1443. """
  1444. self.options.update(self.defaults)
  1445. self.options2form() # Update UI
  1446. def on_options_project2app(self, param):
  1447. """
  1448. Callback for Options->Transfer Options->Project=>App. Copies options
  1449. from project defaults to application defaults.
  1450. :param param: Ignored.
  1451. :return: None
  1452. """
  1453. self.defaults.update(self.options)
  1454. self.options2form() # Update UI
  1455. def on_options_project2object(self, param):
  1456. """
  1457. Callback for Options->Transfer Options->Project=>Object. Copies options
  1458. from project defaults to the currently selected object.
  1459. :param param: Ignored.
  1460. :return: None
  1461. """
  1462. obj = self.get_current()
  1463. if obj is None:
  1464. self.info("WARNING: No object selected.")
  1465. return
  1466. for option in self.options:
  1467. if option.find(obj.kind + "_") == 0:
  1468. oname = option[len(obj.kind)+1:]
  1469. obj.options[oname] = self.options[option]
  1470. obj.to_form() # Update UI
  1471. def on_options_object2project(self, param):
  1472. """
  1473. Callback for Options->Transfer Options->Object=>Project. Copies options
  1474. from the currently selected object to project defaults.
  1475. :param param: Ignored.
  1476. :return: None
  1477. """
  1478. obj = self.get_current()
  1479. if obj is None:
  1480. self.info("WARNING: No object selected.")
  1481. return
  1482. obj.read_form()
  1483. for option in obj.options:
  1484. if option in ['name']: # TODO: Handle this better...
  1485. continue
  1486. self.options[obj.kind + "_" + option] = obj.options[option]
  1487. self.options2form() # Update UI
  1488. def on_options_object2app(self, param):
  1489. """
  1490. Callback for Options->Transfer Options->Object=>App. Copies options
  1491. from the currently selected object to application defaults.
  1492. :param param: Ignored.
  1493. :return: None
  1494. """
  1495. obj = self.get_current()
  1496. if obj is None:
  1497. self.info("WARNING: No object selected.")
  1498. return
  1499. obj.read_form()
  1500. for option in obj.options:
  1501. if option in ['name']: # TODO: Handle this better...
  1502. continue
  1503. self.defaults[obj.kind + "_" + option] = obj.options[option]
  1504. self.options2form() # Update UI
  1505. def on_options_app2object(self, param):
  1506. """
  1507. Callback for Options->Transfer Options->App=>Object. Copies options
  1508. from application defaults to the currently selected object.
  1509. :param param: Ignored.
  1510. :return: None
  1511. """
  1512. obj = self.get_current()
  1513. if obj is None:
  1514. self.info("WARNING: No object selected.")
  1515. return
  1516. for option in self.defaults:
  1517. if option.find(obj.kind + "_") == 0:
  1518. oname = option[len(obj.kind)+1:]
  1519. obj.options[oname] = self.defaults[option]
  1520. obj.to_form() # Update UI
  1521. def on_file_savedefaults(self, param):
  1522. """
  1523. Callback for menu item File->Save Defaults. Saves application default options
  1524. ``self.defaults`` to defaults.json.
  1525. :param param: Ignored.
  1526. :return: None
  1527. """
  1528. # Read options from file
  1529. try:
  1530. f = open("defaults.json")
  1531. options = f.read()
  1532. f.close()
  1533. except:
  1534. self.info("ERROR: Could not load defaults file.")
  1535. return
  1536. try:
  1537. defaults = json.loads(options)
  1538. except:
  1539. e = sys.exc_info()[0]
  1540. print e
  1541. self.info("ERROR: Failed to parse defaults file.")
  1542. return
  1543. # Update options
  1544. assert isinstance(defaults, dict)
  1545. defaults.update(self.defaults)
  1546. # Save update options
  1547. try:
  1548. f = open("defaults.json", "w")
  1549. json.dump(defaults, f)
  1550. f.close()
  1551. except:
  1552. self.info("ERROR: Failed to write defaults to file.")
  1553. return
  1554. self.info("Defaults saved.")
  1555. def on_options_combo_change(self, widget):
  1556. """
  1557. Called when the combo box to choose between application defaults and
  1558. project option changes value. The corresponding variables are
  1559. copied to the UI.
  1560. :param widget: The widget from which this was called. Ignore.
  1561. :return: None
  1562. """
  1563. #combo_sel = self.combo_options.get_active()
  1564. #print "Options --> ", combo_sel
  1565. self.options2form()
  1566. def on_options_update(self, widget):
  1567. """
  1568. Called whenever a value in the options/defaults form changes.
  1569. All values are updated. Can be inhibited by setting ``self.options_update_ignore = True``,
  1570. which may be necessary when updating the UI from code and not by the user.
  1571. :param widget: The widget from which this was called. Ignore.
  1572. :return: None
  1573. """
  1574. if self.options_update_ignore:
  1575. return
  1576. self.read_form()
  1577. def on_scale_object(self, widget):
  1578. """
  1579. Callback for request to change an objects geometry scale. The object
  1580. is re-scaled and replotted.
  1581. :param widget: Ignored.
  1582. :return: None
  1583. """
  1584. obj = self.get_current()
  1585. factor = self.get_eval("entry_eval_" + obj.kind + "_scalefactor")
  1586. obj.scale(factor)
  1587. obj.to_form()
  1588. self.on_update_plot(None)
  1589. def on_canvas_configure(self, widget, event):
  1590. """
  1591. Called whenever the canvas changes size. The axes are updated such
  1592. as to use the whole canvas.
  1593. :param widget: Ignored.
  1594. :param event: Ignored.
  1595. :return: None
  1596. """
  1597. self.plotcanvas.auto_adjust_axes()
  1598. def on_row_activated(self, widget, path, col):
  1599. """
  1600. Callback for selection activation (Enter or double-click) on the Project list.
  1601. Switches the notebook page to the object properties form. Calls
  1602. ``self.notebook.set_current_page(1)``.
  1603. :param widget: Ignored.
  1604. :param path: Ignored.
  1605. :param col: Ignored.
  1606. :return: None
  1607. """
  1608. self.notebook.set_current_page(1)
  1609. def on_generate_gerber_bounding_box(self, widget):
  1610. """
  1611. Callback for request from the Gerber form to generate a bounding box for the
  1612. geometry in the object. Creates a FlatCAMGeometry with the bounding box.
  1613. The box can have rounded corners if specified in the form.
  1614. :param widget: Ignored.
  1615. :return: None
  1616. """
  1617. # TODO: Use Gerber.get_bounding_box(...)
  1618. gerber = self.get_current()
  1619. gerber.read_form()
  1620. name = gerber.options["name"] + "_bbox"
  1621. def geo_init(geo_obj, app_obj):
  1622. assert isinstance(geo_obj, FlatCAMGeometry)
  1623. # Bounding box with rounded corners
  1624. bounding_box = gerber.solid_geometry.envelope.buffer(gerber.options["bboxmargin"])
  1625. if not gerber.options["bboxrounded"]: # Remove rounded corners
  1626. bounding_box = bounding_box.envelope
  1627. geo_obj.solid_geometry = bounding_box
  1628. self.new_object("geometry", name, geo_init)
  1629. def on_update_plot(self, widget):
  1630. """
  1631. Callback for button on form for all kinds of objects.
  1632. Re-plots the current object only.
  1633. :param widget: The widget from which this was called. Ignored.
  1634. :return: None
  1635. """
  1636. obj = self.get_current()
  1637. obj.read_form()
  1638. self.set_progress_bar(0.5, "Plotting...")
  1639. def thread_func(app_obj):
  1640. assert isinstance(app_obj, App)
  1641. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Plotting..."))
  1642. #GLib.idle_add(lambda: app_obj.get_current().plot(app_obj.figure))
  1643. obj.plot()
  1644. #GLib.idle_add(lambda: app_obj.on_zoom_fit(None))
  1645. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "Idle"))
  1646. t = threading.Thread(target=thread_func, args=(self,))
  1647. t.daemon = True
  1648. t.start()
  1649. def on_generate_excellon_cncjob(self, widget):
  1650. """
  1651. Callback for button active/click on Excellon form to
  1652. create a CNC Job for the Excellon file.
  1653. :param widget: Ignored
  1654. :return: None
  1655. """
  1656. excellon = self.get_current()
  1657. excellon.read_form()
  1658. job_name = excellon.options["name"] + "_cnc"
  1659. # Object initialization function for app.new_object()
  1660. def job_init(job_obj, app_obj):
  1661. # excellon_ = self.get_current()
  1662. # assert isinstance(excellon_, FlatCAMExcellon)
  1663. assert isinstance(job_obj, FlatCAMCNCjob)
  1664. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1665. job_obj.z_cut = excellon.options["drillz"]
  1666. job_obj.z_move = excellon.options["travelz"]
  1667. job_obj.feedrate = excellon.options["feedrate"]
  1668. # There could be more than one drill size...
  1669. # job_obj.tooldia = # TODO: duplicate variable!
  1670. # job_obj.options["tooldia"] =
  1671. job_obj.generate_from_excellon_by_tool(excellon, excellon.options["toolselection"])
  1672. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1673. job_obj.gcode_parse()
  1674. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1675. job_obj.create_geometry()
  1676. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1677. # To be run in separate thread
  1678. def job_thread(app_obj):
  1679. app_obj.new_object("cncjob", job_name, job_init)
  1680. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1681. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1682. # Start the thread
  1683. t = threading.Thread(target=job_thread, args=(self,))
  1684. t.daemon = True
  1685. t.start()
  1686. def on_excellon_tool_choose(self, widget):
  1687. """
  1688. Callback for button on Excellon form to open up a window for
  1689. selecting tools.
  1690. :param widget: The widget from which this was called.
  1691. :return: None
  1692. """
  1693. excellon = self.get_current()
  1694. assert isinstance(excellon, FlatCAMExcellon)
  1695. excellon.show_tool_chooser()
  1696. def on_entry_eval_activate(self, widget):
  1697. """
  1698. Called when an entry is activated (eg. by hitting enter) if
  1699. set to do so. Its text is eval()'d and set to the returned value.
  1700. The current object is updated.
  1701. :param widget:
  1702. :return:
  1703. """
  1704. self.on_eval_update(widget)
  1705. obj = self.get_current()
  1706. assert isinstance(obj, FlatCAMObj)
  1707. obj.read_form()
  1708. def on_gerber_generate_noncopper(self, widget):
  1709. """
  1710. Callback for button on Gerber form to create a geometry object
  1711. with polygons covering the area without copper or negative of the
  1712. Gerber.
  1713. :param widget: The widget from which this was called.
  1714. :return: None
  1715. """
  1716. gerb = self.get_current()
  1717. gerb.read_form()
  1718. name = gerb.options["name"] + "_noncopper"
  1719. def geo_init(geo_obj, app_obj):
  1720. assert isinstance(geo_obj, FlatCAMGeometry)
  1721. bounding_box = gerb.solid_geometry.envelope.buffer(gerb.options["noncoppermargin"])
  1722. if not gerb.options["noncopperrounded"]:
  1723. bounding_box = bounding_box.envelope
  1724. non_copper = bounding_box.difference(gerb.solid_geometry)
  1725. geo_obj.solid_geometry = non_copper
  1726. # TODO: Check for None
  1727. self.new_object("geometry", name, geo_init)
  1728. def on_gerber_generate_cutout(self, widget):
  1729. """
  1730. Callback for button on Gerber form to create geometry with lines
  1731. for cutting off the board.
  1732. :param widget: The widget from which this was called.
  1733. :return: None
  1734. """
  1735. gerb = self.get_current()
  1736. gerb.read_form()
  1737. name = gerb.options["name"] + "_cutout"
  1738. def geo_init(geo_obj, app_obj):
  1739. margin = gerb.options["cutoutmargin"] + gerb.options["cutouttooldia"]/2
  1740. gap_size = gerb.options["cutoutgapsize"] + gerb.options["cutouttooldia"]
  1741. minx, miny, maxx, maxy = gerb.bounds()
  1742. minx -= margin
  1743. maxx += margin
  1744. miny -= margin
  1745. maxy += margin
  1746. midx = 0.5 * (minx + maxx)
  1747. midy = 0.5 * (miny + maxy)
  1748. hgap = 0.5 * gap_size
  1749. pts = [[midx - hgap, maxy],
  1750. [minx, maxy],
  1751. [minx, midy + hgap],
  1752. [minx, midy - hgap],
  1753. [minx, miny],
  1754. [midx - hgap, miny],
  1755. [midx + hgap, miny],
  1756. [maxx, miny],
  1757. [maxx, midy - hgap],
  1758. [maxx, midy + hgap],
  1759. [maxx, maxy],
  1760. [midx + hgap, maxy]]
  1761. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  1762. [pts[6], pts[7], pts[10], pts[11]]],
  1763. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  1764. [pts[3], pts[4], pts[7], pts[8]]],
  1765. "4": [[pts[0], pts[1], pts[2]],
  1766. [pts[3], pts[4], pts[5]],
  1767. [pts[6], pts[7], pts[8]],
  1768. [pts[9], pts[10], pts[11]]]}
  1769. cuts = cases[app.get_radio_value({"rb_2tb": "tb", "rb_2lr": "lr", "rb_4": "4"})]
  1770. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  1771. # TODO: Check for None
  1772. self.new_object("geometry", name, geo_init)
  1773. def on_eval_update(self, widget):
  1774. """
  1775. Modifies the content of a Gtk.Entry by running
  1776. eval() on its contents and puting it back as a
  1777. string.
  1778. :param widget: The widget from which this was called.
  1779. :return: None
  1780. """
  1781. # TODO: error handling here
  1782. widget.set_text(str(eval(widget.get_text())))
  1783. def on_generate_isolation(self, widget):
  1784. """
  1785. Callback for button on Gerber form to create isolation routing geometry.
  1786. :param widget: The widget from which this was called.
  1787. :return: None
  1788. """
  1789. gerb = self.get_current()
  1790. gerb.read_form()
  1791. dia = gerb.options["isotooldia"]
  1792. passes = int(gerb.options["isopasses"])
  1793. overlap = gerb.options["isooverlap"] * dia
  1794. for i in range(passes):
  1795. offset = (2*i + 1)/2.0 * dia - i*overlap
  1796. iso_name = gerb.options["name"] + "_iso%d" % (i+1)
  1797. # TODO: This is ugly. Create way to pass data into init function.
  1798. def iso_init(geo_obj, app_obj):
  1799. # Propagate options
  1800. geo_obj.options["cnctooldia"] = gerb.options["isotooldia"]
  1801. geo_obj.solid_geometry = gerb.isolation_geometry(offset)
  1802. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  1803. # TODO: Do something if this is None. Offer changing name?
  1804. self.new_object("geometry", iso_name, iso_init)
  1805. def on_generate_cncjob(self, widget):
  1806. """
  1807. Callback for button on geometry form to generate CNC job.
  1808. :param widget: The widget from which this was called.
  1809. :return: None
  1810. """
  1811. source_geo = self.get_current()
  1812. source_geo.read_form()
  1813. job_name = source_geo.options["name"] + "_cnc"
  1814. # Object initialization function for app.new_object()
  1815. # RUNNING ON SEPARATE THREAD!
  1816. def job_init(job_obj, app_obj):
  1817. assert isinstance(job_obj, FlatCAMCNCjob)
  1818. # Propagate options
  1819. job_obj.options["tooldia"] = source_geo.options["cnctooldia"]
  1820. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1821. job_obj.z_cut = source_geo.options["cutz"]
  1822. job_obj.z_move = source_geo.options["travelz"]
  1823. job_obj.feedrate = source_geo.options["feedrate"]
  1824. GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry..."))
  1825. # TODO: The tolerance should not be hard coded. Just for testing.
  1826. job_obj.generate_from_geometry(source_geo, tolerance=0.0005)
  1827. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1828. job_obj.gcode_parse()
  1829. # TODO: job_obj.create_geometry creates stuff that is not used.
  1830. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1831. #job_obj.create_geometry()
  1832. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1833. # To be run in separate thread
  1834. def job_thread(app_obj):
  1835. app_obj.new_object("cncjob", job_name, job_init)
  1836. GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name))
  1837. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1838. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1839. # Start the thread
  1840. t = threading.Thread(target=job_thread, args=(self,))
  1841. t.daemon = True
  1842. t.start()
  1843. def on_generate_paintarea(self, widget):
  1844. """
  1845. Callback for button on geometry form.
  1846. Subscribes to the "Click on plot" event and continues
  1847. after the click. Finds the polygon containing
  1848. the clicked point and runs clear_poly() on it, resulting
  1849. in a new FlatCAMGeometry object.
  1850. :param widget: The widget from which this was called.
  1851. :return: None
  1852. """
  1853. self.info("Click inside the desired polygon.")
  1854. geo = self.get_current()
  1855. geo.read_form()
  1856. assert isinstance(geo, FlatCAMGeometry)
  1857. tooldia = geo.options["painttooldia"]
  1858. overlap = geo.options["paintoverlap"]
  1859. # To be called after clicking on the plot.
  1860. def doit(event):
  1861. self.plot_click_subscribers.pop("generate_paintarea")
  1862. self.info("")
  1863. point = [event.xdata, event.ydata]
  1864. poly = find_polygon(geo.solid_geometry, point)
  1865. # Initializes the new geometry object
  1866. def gen_paintarea(geo_obj, app_obj):
  1867. assert isinstance(geo_obj, FlatCAMGeometry)
  1868. assert isinstance(app_obj, App)
  1869. cp = clear_poly(poly.buffer(-geo.options["paintmargin"]), tooldia, overlap)
  1870. geo_obj.solid_geometry = cp
  1871. geo_obj.options["cnctooldia"] = tooldia
  1872. name = self.selected_item_name + "_paint"
  1873. self.new_object("geometry", name, gen_paintarea)
  1874. self.plot_click_subscribers["generate_paintarea"] = doit
  1875. def on_cncjob_exportgcode(self, widget):
  1876. """
  1877. Called from button on CNCjob form to save the G-Code from the object.
  1878. :param widget: The widget from which this was called.
  1879. :return: None
  1880. """
  1881. def on_success(app_obj, filename):
  1882. cncjob = app_obj.get_current()
  1883. f = open(filename, 'w')
  1884. f.write(cncjob.gcode)
  1885. f.close()
  1886. app_obj.info("Saved to: " + filename)
  1887. self.file_chooser_save_action(on_success)
  1888. def on_delete(self, widget):
  1889. """
  1890. Delete the currently selected FlatCAMObj.
  1891. :param widget: The widget from which this was called.
  1892. :return: None
  1893. """
  1894. # Keep this for later
  1895. name = copy.copy(self.selected_item_name)
  1896. # Remove plot
  1897. self.plotcanvas.figure.delaxes(self.get_current().axes)
  1898. self.plotcanvas.auto_adjust_axes()
  1899. # Remove from dictionary
  1900. self.stuff.pop(self.selected_item_name)
  1901. # Update UI
  1902. self.build_list() # Update the items list
  1903. self.info("Object deleted: %s" % name)
  1904. def on_toolbar_replot(self, widget):
  1905. """
  1906. Callback for toolbar button. Re-plots all objects.
  1907. :param widget: The widget from which this was called.
  1908. :return: None
  1909. """
  1910. self.get_current().read_form()
  1911. self.plot_all()
  1912. def on_clear_plots(self, widget):
  1913. """
  1914. Callback for toolbar button. Clears all plots.
  1915. :param widget: The widget from which this was called.
  1916. :return: None
  1917. """
  1918. self.plotcanvas.clear()
  1919. def on_activate_name(self, entry):
  1920. """
  1921. Hitting 'Enter' after changing the name of an item
  1922. updates the item dictionary and re-builds the item list.
  1923. :param entry: The widget from which this was called.
  1924. :return: None
  1925. """
  1926. # Disconnect event listener
  1927. self.tree.get_selection().disconnect(self.signal_id)
  1928. new_name = entry.get_text() # Get from form
  1929. self.stuff[new_name] = self.stuff.pop(self.selected_item_name) # Update dictionary
  1930. self.stuff[new_name].options["name"] = new_name # update object
  1931. self.info('Name change: ' + self.selected_item_name + " to " + new_name)
  1932. self.selected_item_name = new_name # Update selection name
  1933. self.build_list() # Update the items list
  1934. # Reconnect event listener
  1935. self.signal_id = self.tree.get_selection().connect(
  1936. "changed", self.on_tree_selection_changed)
  1937. def on_tree_selection_changed(self, selection):
  1938. """
  1939. Callback for selection change in the project list. This changes
  1940. the currently selected FlatCAMObj.
  1941. :param selection: Selection associated to the project tree or list
  1942. :type selection: Gtk.TreeSelection
  1943. :return: None
  1944. """
  1945. print "DEBUG: on_tree_selection_change(): ",
  1946. model, treeiter = selection.get_selected()
  1947. if treeiter is not None:
  1948. # Save data for previous selection
  1949. obj = self.get_current()
  1950. if obj is not None:
  1951. obj.read_form()
  1952. print "DEBUG: You selected", model[treeiter][0]
  1953. self.selected_item_name = model[treeiter][0]
  1954. obj_new = self.get_current()
  1955. if obj_new is not None:
  1956. GLib.idle_add(lambda: obj_new.build_ui())
  1957. else:
  1958. print "DEBUG: Nothing selected"
  1959. self.selected_item_name = None
  1960. self.setup_component_editor()
  1961. def on_file_new(self, param):
  1962. """
  1963. Callback for menu item File->New. Returns the application to its
  1964. startup state.
  1965. :param param: Whatever is passed by the event. Ignore.
  1966. :return: None
  1967. """
  1968. # Remove everythong from memory
  1969. # Clear plot
  1970. self.plotcanvas.clear()
  1971. # Clear object editor
  1972. #self.setup_component_editor()
  1973. # Clear data
  1974. self.stuff = {}
  1975. # Clear list
  1976. #self.tree_select.unselect_all()
  1977. self.build_list()
  1978. # Clear project filename
  1979. self.project_filename = None
  1980. # Re-fresh project options
  1981. self.on_options_app2project(None)
  1982. def on_filequit(self, param):
  1983. """
  1984. Callback for menu item File->Quit. Closes the application.
  1985. :param param: Whatever is passed by the event. Ignore.
  1986. :return: None
  1987. """
  1988. self.window.destroy()
  1989. Gtk.main_quit()
  1990. def on_closewindow(self, param):
  1991. """
  1992. Callback for closing the main window.
  1993. :param param: Whatever is passed by the event. Ignore.
  1994. :return: None
  1995. """
  1996. self.window.destroy()
  1997. Gtk.main_quit()
  1998. def file_chooser_action(self, on_success):
  1999. """
  2000. Opens the file chooser and runs on_success on a separate thread
  2001. upon completion of valid file choice.
  2002. :param on_success: A function to run upon completion of a valid file
  2003. selection. Takes 2 parameters: The app instance and the filename.
  2004. Note that it is run on a separate thread, therefore it must take the
  2005. appropriate precautions when accessing shared resources.
  2006. :type on_success: func
  2007. :return: None
  2008. """
  2009. dialog = Gtk.FileChooserDialog("Please choose a file", self.window,
  2010. Gtk.FileChooserAction.OPEN,
  2011. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2012. Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
  2013. response = dialog.run()
  2014. if response == Gtk.ResponseType.OK:
  2015. filename = dialog.get_filename()
  2016. dialog.destroy()
  2017. t = threading.Thread(target=on_success, args=(self, filename))
  2018. t.daemon = True
  2019. t.start()
  2020. #on_success(self, filename)
  2021. elif response == Gtk.ResponseType.CANCEL:
  2022. self.info("Open cancelled.") # print("Cancel clicked")
  2023. dialog.destroy()
  2024. def file_chooser_save_action(self, on_success):
  2025. """
  2026. Opens the file chooser and runs on_success upon completion of valid file choice.
  2027. :param on_success: A function to run upon selection of a filename. Takes 2
  2028. parameters: The instance of the application (App) and the chosen filename. This
  2029. gets run immediately in the same thread.
  2030. :return: None
  2031. """
  2032. dialog = Gtk.FileChooserDialog("Save file", self.window,
  2033. Gtk.FileChooserAction.SAVE,
  2034. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2035. Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
  2036. dialog.set_current_name("Untitled")
  2037. response = dialog.run()
  2038. if response == Gtk.ResponseType.OK:
  2039. filename = dialog.get_filename()
  2040. dialog.destroy()
  2041. on_success(self, filename)
  2042. elif response == Gtk.ResponseType.CANCEL:
  2043. self.info("Save cancelled.") # print("Cancel clicked")
  2044. dialog.destroy()
  2045. def on_fileopengerber(self, param):
  2046. """
  2047. Callback for menu item File->Open Gerber. Defines a function that is then passed
  2048. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMGerber object
  2049. and updates the progress bar throughout the process.
  2050. :param param: Ignore
  2051. :return: None
  2052. """
  2053. # IMPORTANT: on_success will run on a separate thread. Use
  2054. # GLib.idle_add(function, **kwargs) to launch actions that will
  2055. # updata the GUI.
  2056. def on_success(app_obj, filename):
  2057. assert isinstance(app_obj, App)
  2058. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Gerber ..."))
  2059. def obj_init(gerber_obj, app_obj):
  2060. assert isinstance(gerber_obj, FlatCAMGerber)
  2061. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2062. gerber_obj.parse_file(filename)
  2063. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Creating Geometry ..."))
  2064. gerber_obj.create_geometry()
  2065. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2066. name = filename.split('/')[-1].split('\\')[-1]
  2067. app_obj.new_object("gerber", name, obj_init)
  2068. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2069. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2070. # on_success gets run on a separate thread
  2071. self.file_chooser_action(on_success)
  2072. def on_fileopenexcellon(self, param):
  2073. """
  2074. Callback for menu item File->Open Excellon. Defines a function that is then passed
  2075. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMExcellon object
  2076. and updates the progress bar throughout the process.
  2077. :param param: Ignore
  2078. :return: None
  2079. """
  2080. # IMPORTANT: on_success will run on a separate thread. Use
  2081. # GLib.idle_add(function, **kwargs) to launch actions that will
  2082. # updata the GUI.
  2083. def on_success(app_obj, filename):
  2084. assert isinstance(app_obj, App)
  2085. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Excellon ..."))
  2086. def obj_init(excellon_obj, app_obj):
  2087. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2088. excellon_obj.parse_file(filename)
  2089. excellon_obj.create_geometry()
  2090. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2091. name = filename.split('/')[-1].split('\\')[-1]
  2092. app_obj.new_object("excellon", name, obj_init)
  2093. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2094. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2095. # on_success gets run on a separate thread
  2096. self.file_chooser_action(on_success)
  2097. def on_fileopengcode(self, param):
  2098. """
  2099. Callback for menu item File->Open G-Code. Defines a function that is then passed
  2100. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMCNCjob object
  2101. and updates the progress bar throughout the process.
  2102. :param param: Ignore
  2103. :return: None
  2104. """
  2105. # IMPORTANT: on_success will run on a separate thread. Use
  2106. # GLib.idle_add(function, **kwargs) to launch actions that will
  2107. # updata the GUI.
  2108. def on_success(app_obj, filename):
  2109. assert isinstance(app_obj, App)
  2110. def obj_init(job_obj, app_obj_):
  2111. """
  2112. :type app_obj_: App
  2113. """
  2114. assert isinstance(app_obj_, App)
  2115. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.1, "Opening G-Code ..."))
  2116. f = open(filename)
  2117. gcode = f.read()
  2118. f.close()
  2119. job_obj.gcode = gcode
  2120. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.2, "Parsing ..."))
  2121. job_obj.gcode_parse()
  2122. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Creating geometry ..."))
  2123. job_obj.create_geometry()
  2124. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Plotting ..."))
  2125. name = filename.split('/')[-1].split('\\')[-1]
  2126. app_obj.new_object("cncjob", name, obj_init)
  2127. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2128. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2129. # on_success gets run on a separate thread
  2130. self.file_chooser_action(on_success)
  2131. def on_mouse_move_over_plot(self, event):
  2132. """
  2133. Callback for the mouse motion event over the plot. This event is generated
  2134. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2135. For details, see: http://matplotlib.org/users/event_handling.html
  2136. :param event: Contains information about the event.
  2137. :return: None
  2138. """
  2139. try: # May fail in case mouse not within axes
  2140. self.position_label.set_label("X: %.4f Y: %.4f" % (
  2141. event.xdata, event.ydata))
  2142. self.mouse = [event.xdata, event.ydata]
  2143. for subscriber in self.plot_mousemove_subscribers:
  2144. self.plot_mousemove_subscribers[subscriber](event)
  2145. except:
  2146. self.position_label.set_label("")
  2147. self.mouse = None
  2148. def on_click_over_plot(self, event):
  2149. """
  2150. Callback for the mouse click event over the plot. This event is generated
  2151. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2152. For details, see: http://matplotlib.org/users/event_handling.html
  2153. Default actions are:
  2154. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  2155. :param event: Contains information about the event, like which button
  2156. was clicked, the pixel coordinates and the axes coordinates.
  2157. :return: None
  2158. """
  2159. # For key presses
  2160. self.plotcanvas.canvas.grab_focus()
  2161. try:
  2162. print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  2163. event.button, event.x, event.y, event.xdata, event.ydata)
  2164. # TODO: This custom subscription mechanism is probably not necessary.
  2165. for subscriber in self.plot_click_subscribers:
  2166. self.plot_click_subscribers[subscriber](event)
  2167. self.clipboard.set_text("(%.4f, %.4f)" % (event.xdata, event.ydata), -1)
  2168. except Exception, e:
  2169. print "Outside plot!"
  2170. def on_zoom_in(self, event):
  2171. """
  2172. Callback for zoom-in request. This can be either from the corresponding
  2173. toolbar button or the '3' key when the canvas is focused. Calls ``self.zoom()``.
  2174. :param event: Ignored.
  2175. :return: None
  2176. """
  2177. self.plotcanvas.zoom(1.5)
  2178. return
  2179. def on_zoom_out(self, event):
  2180. """
  2181. Callback for zoom-out request. This can be either from the corresponding
  2182. toolbar button or the '2' key when the canvas is focused. Calls ``self.zoom()``.
  2183. :param event: Ignored.
  2184. :return: None
  2185. """
  2186. self.plotcanvas.zoom(1 / 1.5)
  2187. def on_zoom_fit(self, event):
  2188. """
  2189. Callback for zoom-out request. This can be either from the corresponding
  2190. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2191. with axes limits from the geometry bounds of all objects.
  2192. :param event: Ignored.
  2193. :return: None
  2194. """
  2195. xmin, ymin, xmax, ymax = get_bounds(self.stuff)
  2196. width = xmax - xmin
  2197. height = ymax - ymin
  2198. xmin -= 0.05 * width
  2199. xmax += 0.05 * width
  2200. ymin -= 0.05 * height
  2201. ymax += 0.05 * height
  2202. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  2203. def on_key_over_plot(self, event):
  2204. """
  2205. Callback for the key pressed event when the canvas is focused. Keyboard
  2206. shortcuts are handled here. So far, these are the shortcuts:
  2207. ========== ============================================
  2208. Key Action
  2209. ========== ============================================
  2210. '1' Zoom-fit. Fits the axes limits to the data.
  2211. '2' Zoom-out.
  2212. '3' Zoom-in.
  2213. ========== ============================================
  2214. :param event: Ignored.
  2215. :return: None
  2216. """
  2217. #print 'you pressed', event.key, event.xdata, event.ydata
  2218. if event.key == '1': # 1
  2219. self.on_zoom_fit(None)
  2220. return
  2221. if event.key == '2': # 2
  2222. self.plotcanvas.zoom(1 / 1.5, self.mouse)
  2223. return
  2224. if event.key == '3': # 3
  2225. self.plotcanvas.zoom(1.5, self.mouse)
  2226. return
  2227. if event.key == 'm':
  2228. if self.measure.toggle_active():
  2229. self.info("Measuring tool ON")
  2230. else:
  2231. self.info("Measuring tool OFF")
  2232. return
  2233. class BaseDraw:
  2234. def __init__(self, plotcanvas, name=None):
  2235. """
  2236. :param plotcanvas: The PlotCanvas where the drawing tool will operate.
  2237. :type plotcanvas: PlotCanvas
  2238. """
  2239. self.plotcanvas = plotcanvas
  2240. # Must have unique axes
  2241. charset = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
  2242. self.name = name or [random.choice(charset) for i in range(20)]
  2243. self.axes = self.plotcanvas.new_axes(self.name)
  2244. class DrawingObject(BaseDraw):
  2245. def __init__(self, plotcanvas, name=None):
  2246. """
  2247. Possible objects are:
  2248. * Point
  2249. * Line
  2250. * Rectangle
  2251. * Circle
  2252. * Polygon
  2253. """
  2254. BaseDraw.__init__(self, plotcanvas)
  2255. self.properties = {}
  2256. def plot(self):
  2257. return
  2258. def update_plot(self):
  2259. self.axes.cla()
  2260. self.plot()
  2261. self.plotcanvas.auto_adjust_axes()
  2262. class DrawingPoint(DrawingObject):
  2263. def __init__(self, plotcanvas, name=None, coord=None):
  2264. DrawingObject.__init__(self, plotcanvas)
  2265. self.properties.update({
  2266. "coordinate": coord
  2267. })
  2268. def plot(self):
  2269. x, y = self.properties["coordinate"]
  2270. self.axes.plot(x, y, 'o')
  2271. class Measurement:
  2272. def __init__(self, container, axes, click_subscibers, move_subscribers, update=None):
  2273. self.update = update
  2274. self.container = container
  2275. self.frame = None
  2276. self.label = None
  2277. self.click_subscribers = click_subscibers
  2278. self.move_subscribers = move_subscribers
  2279. self.point1 = None
  2280. self.point2 = None
  2281. self.active = False
  2282. def toggle_active(self, *args):
  2283. if self.active: # Deactivate
  2284. self.active = False
  2285. self.move_subscribers.pop("meas")
  2286. self.click_subscribers.pop("meas")
  2287. self.container.remove(self.frame)
  2288. if self.update is not None:
  2289. self.update()
  2290. return False
  2291. else: # Activate
  2292. print "DEBUG: Activating Measurement Tool..."
  2293. self.active = True
  2294. self.click_subscribers["meas"] = self.on_click
  2295. self.move_subscribers["meas"] = self.on_move
  2296. self.frame = Gtk.Frame()
  2297. self.frame.set_margin_right(5)
  2298. self.frame.set_margin_top(3)
  2299. align = Gtk.Alignment()
  2300. align.set(0, 0.5, 0, 0)
  2301. align.set_padding(4, 4, 4, 4)
  2302. self.label = Gtk.Label()
  2303. self.label.set_label("Click on a reference point...")
  2304. abox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
  2305. abox.pack_start(Gtk.Image.new_from_file('share/measure16.png'), False, False, 0)
  2306. abox.pack_start(self.label, False, False, 0)
  2307. align.add(abox)
  2308. self.frame.add(align)
  2309. self.container.pack_end(self.frame, False, True, 1)
  2310. self.frame.show_all()
  2311. return True
  2312. def on_move(self, event):
  2313. if self.point1 is None:
  2314. self.label.set_label("Click on a reference point...")
  2315. else:
  2316. dx = event.xdata - self.point1[0]
  2317. dy = event.ydata - self.point1[1]
  2318. d = sqrt(dx**2 + dy**2)
  2319. self.label.set_label("D = %.4f D(x) = %.4f D(y) = %.4f" % (d, dx, dy))
  2320. if self.update is not None:
  2321. self.update()
  2322. def on_click(self, event):
  2323. if self.point1 is None:
  2324. self.point1 = (event.xdata, event.ydata)
  2325. return
  2326. else:
  2327. self.point2 = copy.copy(self.point1)
  2328. self.point1 = (event.xdata, event.ydata)
  2329. self.on_move(event)
  2330. class PlotCanvas:
  2331. """
  2332. Class handling the plotting area in the application.
  2333. """
  2334. def __init__(self, container):
  2335. """
  2336. The constructor configures the Matplotlib figure that
  2337. will contain all plots, creates the base axes and connects
  2338. events to the plotting area.
  2339. :param container: The parent container in which to draw plots.
  2340. :rtype: PlotCanvas
  2341. """
  2342. # Options
  2343. self.x_margin = 15 # pixels
  2344. self.y_margin = 25 # Pixels
  2345. # Parent container
  2346. self.container = container
  2347. # Plots go onto a single matplotlib.figure
  2348. self.figure = Figure(dpi=50) # TODO: dpi needed?
  2349. self.figure.patch.set_visible(False)
  2350. # These axes show the ticks and grid. No plotting done here.
  2351. # New axes must have a label, otherwise mpl returns an existing one.
  2352. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  2353. self.axes.set_aspect(1)
  2354. self.axes.grid(True)
  2355. # The canvas is the top level container (Gtk.DrawingArea)
  2356. self.canvas = FigureCanvas(self.figure)
  2357. self.canvas.set_hexpand(1)
  2358. self.canvas.set_vexpand(1)
  2359. self.canvas.set_can_focus(True) # For key press
  2360. # Attach to parent
  2361. self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  2362. # Events
  2363. self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
  2364. self.canvas.connect('configure-event', self.auto_adjust_axes)
  2365. self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  2366. self.canvas.connect("scroll-event", self.on_scroll)
  2367. self.mouse = [0,0]
  2368. def mpl_connect(self, event_name, callback):
  2369. """
  2370. Attach an event handler to the canvas through the Matplotlib interface.
  2371. :param event_name: Name of the event
  2372. :type event_name: str
  2373. :param callback: Function to call
  2374. :type callback: func
  2375. :return: Nothing
  2376. """
  2377. self.canvas.mpl_connect(event_name, callback)
  2378. def connect(self, event_name, callback):
  2379. """
  2380. Attach an event handler to the canvas through the native GTK interface.
  2381. :param event_name: Name of the event
  2382. :type event_name: str
  2383. :param callback: Function to call
  2384. :type callback: function
  2385. :return: Nothing
  2386. """
  2387. self.canvas.connect(event_name, callback)
  2388. def clear(self):
  2389. """
  2390. Clears axes and figure.
  2391. :return: None
  2392. """
  2393. # Clear
  2394. self.axes.cla()
  2395. self.figure.clf()
  2396. # Re-build
  2397. self.figure.add_axes(self.axes)
  2398. self.axes.set_aspect(1)
  2399. self.axes.grid(True)
  2400. # Re-draw
  2401. self.canvas.queue_draw()
  2402. def adjust_axes(self, xmin, ymin, xmax, ymax):
  2403. """
  2404. Adjusts all axes while maintaining the use of the whole canvas
  2405. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  2406. request that will be modified to fit these restrictions.
  2407. :param xmin: Requested minimum value for the X axis.
  2408. :type xmin: float
  2409. :param ymin: Requested minimum value for the Y axis.
  2410. :type ymin: float
  2411. :param xmax: Requested maximum value for the X axis.
  2412. :type xmax: float
  2413. :param ymax: Requested maximum value for the Y axis.
  2414. :type ymax: float
  2415. :return: None
  2416. """
  2417. width = xmax - xmin
  2418. height = ymax - ymin
  2419. try:
  2420. r = width / height
  2421. except:
  2422. print "ERROR: Height is", height
  2423. return
  2424. canvas_w, canvas_h = self.canvas.get_width_height()
  2425. canvas_r = float(canvas_w) / canvas_h
  2426. x_ratio = float(self.x_margin) / canvas_w
  2427. y_ratio = float(self.y_margin) / canvas_h
  2428. if r > canvas_r:
  2429. ycenter = (ymin + ymax) / 2.0
  2430. newheight = height * r / canvas_r
  2431. ymin = ycenter - newheight / 2.0
  2432. ymax = ycenter + newheight / 2.0
  2433. else:
  2434. xcenter = (xmax + ymin) / 2.0
  2435. newwidth = width * canvas_r / r
  2436. xmin = xcenter - newwidth / 2.0
  2437. xmax = xcenter + newwidth / 2.0
  2438. # Adjust axes
  2439. for ax in self.figure.get_axes():
  2440. if ax._label != 'base':
  2441. ax.set_frame_on(False) # No frame
  2442. ax.set_xticks([]) # No tick
  2443. ax.set_yticks([]) # No ticks
  2444. ax.patch.set_visible(False) # No background
  2445. ax.set_aspect(1)
  2446. ax.set_xlim((xmin, xmax))
  2447. ax.set_ylim((ymin, ymax))
  2448. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  2449. # Re-draw
  2450. self.canvas.queue_draw()
  2451. def auto_adjust_axes(self, *args):
  2452. """
  2453. Calls ``adjust_axes()`` using the extents of the base axes.
  2454. :rtype : None
  2455. :return: None
  2456. """
  2457. xmin, xmax = self.axes.get_xlim()
  2458. ymin, ymax = self.axes.get_ylim()
  2459. self.adjust_axes(xmin, ymin, xmax, ymax)
  2460. def zoom(self, factor, center=None):
  2461. """
  2462. Zooms the plot by factor around a given
  2463. center point. Takes care of re-drawing.
  2464. :param factor: Number by which to scale the plot.
  2465. :type factor: float
  2466. :param center: Coordinates [x, y] of the point around which to scale the plot.
  2467. :type center: list
  2468. :return: None
  2469. """
  2470. xmin, xmax = self.axes.get_xlim()
  2471. ymin, ymax = self.axes.get_ylim()
  2472. width = xmax - xmin
  2473. height = ymax - ymin
  2474. if center is None or center == [None, None]:
  2475. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  2476. # For keeping the point at the pointer location
  2477. relx = (xmax - center[0]) / width
  2478. rely = (ymax - center[1]) / height
  2479. new_width = width / factor
  2480. new_height = height / factor
  2481. xmin = center[0] - new_width * (1 - relx)
  2482. xmax = center[0] + new_width * relx
  2483. ymin = center[1] - new_height * (1 - rely)
  2484. ymax = center[1] + new_height * rely
  2485. # Adjust axes
  2486. for ax in self.figure.get_axes():
  2487. ax.set_xlim((xmin, xmax))
  2488. ax.set_ylim((ymin, ymax))
  2489. # Re-draw
  2490. self.canvas.queue_draw()
  2491. def new_axes(self, name):
  2492. """
  2493. Creates and returns an Axes object attached to this object's Figure.
  2494. :param name: Unique label for the axes.
  2495. :return: Axes attached to the figure.
  2496. :rtype: Axes
  2497. """
  2498. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  2499. # def plot_axes(self, axes):
  2500. #
  2501. # if axes not in self.figure.axes:
  2502. # self.figure.add_axes(axes)
  2503. #
  2504. # # Basic configuration
  2505. # axes.set_frame_on(False) # No frame
  2506. # axes.set_xticks([]) # No tick
  2507. # axes.set_yticks([]) # No ticks
  2508. # axes.patch.set_visible(False) # No background
  2509. # axes.set_aspect(1)
  2510. #
  2511. # # Adjust limits
  2512. # self.auto_adjust_axes()
  2513. def on_scroll(self, canvas, event):
  2514. """
  2515. Scroll event handler.
  2516. :param canvas: The widget generating the event. Ignored.
  2517. :param event: Event object containing the event information.
  2518. :return: None
  2519. """
  2520. z, direction = event.get_scroll_direction()
  2521. if direction is Gdk.ScrollDirection.UP:
  2522. self.zoom(1.5, self.mouse)
  2523. else:
  2524. self.zoom(1/1.5, self.mouse)
  2525. def on_mouse_move(self, event):
  2526. """
  2527. Mouse movement event hadler.
  2528. :param event: Contains information about the event.
  2529. :return: None
  2530. """
  2531. self.mouse = [event.xdata, event.ydata]
  2532. app = App()
  2533. Gtk.main()