FlatCAM.py 104 KB

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