FlatCAM.py 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110
  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 = 2
  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. #app_obj.plotcanvas.auto_adjust_axes()
  770. #self.on_zoom_fit(None)
  771. GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes)
  772. GLib.idle_add(lambda: self.on_zoom_fit(None))
  773. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  774. t = threading.Thread(target=thread_func, args=(self,))
  775. t.daemon = True
  776. t.start()
  777. def get_eval(self, widget_name):
  778. """
  779. Runs eval() on the on the text entry of name 'widget_name'
  780. and returns the results.
  781. :param widget_name: Name of Gtk.Entry
  782. :type widget_name: str
  783. :return: Depends on contents of the entry text.
  784. """
  785. value = self.builder.get_object(widget_name).get_text()
  786. if value == "":
  787. value = "None"
  788. try:
  789. evald = eval(value)
  790. return evald
  791. except:
  792. self.info("Could not evaluate: " + value)
  793. return None
  794. def set_list_selection(self, name):
  795. """
  796. Marks a given object as selected in the list ob objects
  797. in the GUI. This selection will in turn trigger
  798. ``self.on_tree_selection_changed()``.
  799. :param name: Name of the object.
  800. :type name: str
  801. :return: None
  802. """
  803. iter = self.store.get_iter_first()
  804. while iter is not None and self.store[iter][0] != name:
  805. iter = self.store.iter_next(iter)
  806. self.tree_select.unselect_all()
  807. self.tree_select.select_iter(iter)
  808. # Need to return False such that GLib.idle_add
  809. # or .timeout_add do not repeat.
  810. return False
  811. def new_object(self, kind, name, initialize):
  812. """
  813. Creates a new specalized FlatCAMObj and attaches it to the application,
  814. this is, updates the GUI accordingly, any other records and plots it.
  815. :param kind: The kind of object to create. One of 'gerber',
  816. 'excellon', 'cncjob' and 'geometry'.
  817. :type kind: str
  818. :param name: Name for the object.
  819. :type name: str
  820. :param initialize: Function to run after creation of the object
  821. but before it is attached to the application. The function is
  822. called with 2 parameters: the new object and the App instance.
  823. :type initialize: function
  824. :return: None
  825. :rtype: None
  826. """
  827. ### Check for existing name
  828. if name in self.stuff:
  829. ## Create a new name
  830. # Ends with number?
  831. match = re.search(r'(.*[^\d])?(\d+)$', name)
  832. if match: # Yes: Increment the number!
  833. base = match.group(1) or ''
  834. num = int(match.group(2))
  835. name = base + str(num + 1)
  836. else: # No: add a number!
  837. name += "_1"
  838. # Create object
  839. classdict = {
  840. "gerber": FlatCAMGerber,
  841. "excellon": FlatCAMExcellon,
  842. "cncjob": FlatCAMCNCjob,
  843. "geometry": FlatCAMGeometry
  844. }
  845. obj = classdict[kind](name)
  846. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  847. # Initialize as per user request
  848. # User must take care to implement initialize
  849. # in a thread-safe way as is is likely that we
  850. # have been invoked in a separate thread.
  851. #initialize(obj, self)
  852. # Set default options from self.options
  853. for option in self.options:
  854. if option.find(kind + "_") == 0:
  855. oname = option[len(kind)+1:]
  856. obj.options[oname] = self.options[option]
  857. # Initialize as per user request
  858. # User must take care to implement initialize
  859. # in a thread-safe way as is is likely that we
  860. # have been invoked in a separate thread.
  861. initialize(obj, self)
  862. # Check units and convert if necessary
  863. if self.options["units"].upper() != obj.units.upper():
  864. GLib.idle_add(lambda: self.info("Converting units to " + self.options["units"] + "."))
  865. obj.convert_units(self.options["units"])
  866. # Add to our records
  867. self.stuff[name] = obj
  868. # Update GUI list and select it (Thread-safe?)
  869. self.store.append([name])
  870. #self.build_list()
  871. GLib.idle_add(lambda: self.set_list_selection(name))
  872. # TODO: Gtk.notebook.set_current_page is not known to
  873. # TODO: return False. Fix this??
  874. GLib.timeout_add(100, lambda: self.notebook.set_current_page(1))
  875. # Plot
  876. # TODO: (Thread-safe?)
  877. obj.plot()
  878. # TODO: Threading dissaster!
  879. GLib.idle_add(lambda: self.on_zoom_fit(None))
  880. return obj
  881. def set_progress_bar(self, percentage, text=""):
  882. """
  883. Sets the application's progress bar to a given frac_digits and text.
  884. :param percentage: The frac_digits (0.0-1.0) of the progress.
  885. :type percentage: float
  886. :param text: Text to display on the progress bar.
  887. :type text: str
  888. :return: None
  889. """
  890. self.progress_bar.set_text(text)
  891. self.progress_bar.set_fraction(percentage)
  892. return False
  893. def get_current(self):
  894. """
  895. Returns the currently selected FlatCAMObj in the application.
  896. :return: Currently selected FlatCAMObj in the application.
  897. :rtype: FlatCAMObj or None
  898. """
  899. # TODO: Could possibly read the form into the object here.
  900. # But there are some cases when the form for the object
  901. # is not up yet. See on_tree_selection_changed.
  902. try:
  903. return self.stuff[self.selected_item_name]
  904. except:
  905. return None
  906. def load_defaults(self):
  907. """
  908. Loads the aplication's default settings from defaults.json into
  909. ``self.defaults``.
  910. :return: None
  911. """
  912. try:
  913. f = open("defaults.json")
  914. options = f.read()
  915. f.close()
  916. except:
  917. self.info("ERROR: Could not load defaults file.")
  918. return
  919. try:
  920. defaults = json.loads(options)
  921. except:
  922. e = sys.exc_info()[0]
  923. print e
  924. self.info("ERROR: Failed to parse defaults file.")
  925. return
  926. self.defaults.update(defaults)
  927. def read_form(self):
  928. """
  929. Reads the options form into self.defaults/self.options.
  930. :return: None
  931. :rtype: None
  932. """
  933. combo_sel = self.combo_options.get_active()
  934. options_set = [self.options, self.defaults][combo_sel]
  935. for option in options_set:
  936. self.read_form_item(option, options_set)
  937. def read_form_item(self, name, dest):
  938. """
  939. Reads the value of a form item in the defaults/options form and
  940. saves it to the corresponding dictionary.
  941. :param name: Name of the form item. A key in ``self.defaults`` or
  942. ``self.options``.
  943. :type name: str
  944. :param dest: Dictionary to which to save the value.
  945. :type dest: dict
  946. :return: None
  947. """
  948. fkind = self.form_kinds[name]
  949. fname = fkind + "_" + "app" + "_" + name
  950. if fkind == 'entry_text':
  951. dest[name] = self.builder.get_object(fname).get_text()
  952. return
  953. if fkind == 'entry_eval':
  954. dest[name] = self.get_eval(fname)
  955. return
  956. if fkind == 'cb':
  957. dest[name] = self.builder.get_object(fname).get_active()
  958. return
  959. if fkind == 'radio':
  960. dest[name] = self.get_radio_value(self.radios[name])
  961. return
  962. print "Unknown kind of form item:", fkind
  963. def options2form(self):
  964. """
  965. Sets the 'Project Options' or 'Application Defaults' form with values from
  966. ``self.options`` or ``self.defaults``.
  967. :return: None
  968. :rtype: None
  969. """
  970. # Set the on-change callback to do nothing while we do the changes.
  971. self.options_update_ignore = True
  972. self.toggle_units_ignore = True
  973. combo_sel = self.combo_options.get_active()
  974. options_set = [self.options, self.defaults][combo_sel]
  975. for option in options_set:
  976. self.set_form_item(option, options_set[option])
  977. self.options_update_ignore = False
  978. self.toggle_units_ignore = False
  979. def set_form_item(self, name, value):
  980. """
  981. Sets a form item 'name' in the GUI with the given 'value'. The syntax of
  982. form names in the GUI is <kind>_app_<name>, where kind is one of: rb (radio button),
  983. cb (check button), entry_eval or entry_text (entry), combo (combo box). name is
  984. whatever name it's been given. For self.defaults, name is a key in the dictionary.
  985. :param name: Name of the form field.
  986. :type name: str
  987. :param value: The value to set the form field to.
  988. :type value: Depends on field kind.
  989. :return: None
  990. """
  991. if name not in self.form_kinds:
  992. print "WARNING: Tried to set unknown option/form item:", name
  993. return
  994. fkind = self.form_kinds[name]
  995. fname = fkind + "_" + "app" + "_" + name
  996. if fkind == 'entry_eval' or fkind == 'entry_text':
  997. try:
  998. self.builder.get_object(fname).set_text(str(value))
  999. except:
  1000. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1001. return
  1002. if fkind == 'cb':
  1003. try:
  1004. self.builder.get_object(fname).set_active(value)
  1005. except:
  1006. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1007. return
  1008. if fkind == 'radio':
  1009. try:
  1010. self.builder.get_object(self.radios_inv[name][value]).set_active(True)
  1011. except:
  1012. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1013. return
  1014. print "Unknown kind of form item:", fkind
  1015. def save_project(self, filename):
  1016. """
  1017. Saves the current project to the specified file.
  1018. :param filename: Name of the file in which to save.
  1019. :type filename: str
  1020. :return: None
  1021. """
  1022. # Capture the latest changes
  1023. try:
  1024. self.get_current().read_form()
  1025. except:
  1026. pass
  1027. d = {"objs": [self.stuff[o].to_dict() for o in self.stuff],
  1028. "options": self.options}
  1029. try:
  1030. f = open(filename, 'w')
  1031. except:
  1032. print "ERROR: Failed to open file for saving:", filename
  1033. return
  1034. try:
  1035. json.dump(d, f, default=to_dict)
  1036. except:
  1037. print "ERROR: File open but failed to write:", filename
  1038. f.close()
  1039. return
  1040. f.close()
  1041. def open_project(self, filename):
  1042. """
  1043. Loads a project from the specified file.
  1044. :param filename: Name of the file from which to load.
  1045. :type filename: str
  1046. :return: None
  1047. """
  1048. try:
  1049. f = open(filename, 'r')
  1050. except:
  1051. #print "WARNING: Failed to open project file:", filename
  1052. self.info("ERROR: Failed to open project file: %s" % filename)
  1053. return
  1054. try:
  1055. d = json.load(f, object_hook=dict2obj)
  1056. except:
  1057. #print sys.exc_info()
  1058. #print "WARNING: Failed to parse project file:", filename
  1059. self.info("ERROR: Failed to parse project file: %s" % filename)
  1060. f.close()
  1061. return
  1062. # Clear the current project
  1063. self.on_file_new(None)
  1064. # Project options
  1065. self.options.update(d['options'])
  1066. self.project_filename = filename
  1067. self.units_label.set_text(self.options["units"])
  1068. # Re create objects
  1069. for obj in d['objs']:
  1070. def obj_init(obj_inst, app_inst):
  1071. obj_inst.from_dict(obj)
  1072. self.new_object(obj['kind'], obj['options']['name'], obj_init)
  1073. self.info("Project loaded from: " + filename)
  1074. def populate_objects_combo(self, combo):
  1075. """
  1076. Populates a Gtk.Comboboxtext with the list of the object in the project.
  1077. :param combo: Name or instance of the comboboxtext.
  1078. :type combo: str or Gtk.ComboBoxText
  1079. :return: None
  1080. """
  1081. print "Populating combo!"
  1082. if type(combo) == str:
  1083. combo = self.builder.get_object(combo)
  1084. combo.remove_all()
  1085. for obj in self.stuff:
  1086. combo.append_text(obj)
  1087. def versionCheck(self, *args):
  1088. """
  1089. Checks for the latest version of the program. Alerts the
  1090. user if theirs is outdated. This method is meant to be run
  1091. in a saeparate thread.
  1092. :return: None
  1093. """
  1094. try:
  1095. f = urllib.urlopen("http://caram.cl/flatcam/VERSION") # TODO: Hardcoded.
  1096. except:
  1097. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1098. return
  1099. try:
  1100. data = json.load(f)
  1101. except:
  1102. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1103. f.close()
  1104. return
  1105. f.close()
  1106. if self.version >= data["version"]:
  1107. GLib.idle_add(lambda: self.info("FlatCAM is up to date!"))
  1108. return
  1109. label = Gtk.Label("There is a newer version of FlatCAM\n" +
  1110. "available for download:\n\n" +
  1111. data["name"] + "\n\n" + data["message"])
  1112. dialog = Gtk.Dialog("Newer Version Available", self.window, 0,
  1113. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1114. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1115. dialog.set_default_size(150, 100)
  1116. dialog.set_modal(True)
  1117. box = dialog.get_content_area()
  1118. box.set_border_width(10)
  1119. box.add(label)
  1120. def do_dialog():
  1121. dialog.show_all()
  1122. response = dialog.run()
  1123. dialog.destroy()
  1124. GLib.idle_add(lambda: do_dialog())
  1125. return
  1126. def setup_tooltips(self):
  1127. tooltips = {
  1128. "cb_gerber_plot": "Plot this object on the main window.",
  1129. "cb_gerber_mergepolys": "Show overlapping polygons as single.",
  1130. "cb_gerber_solid": "Paint inside polygons.",
  1131. "cb_gerber_multicolored": "Draw polygons with different colors."
  1132. }
  1133. for widget in tooltips:
  1134. self.builder.get_object(widget).set_tooltip_markup(tooltips[widget])
  1135. def do_nothing(self, param):
  1136. return
  1137. ########################################
  1138. ## EVENT HANDLERS ##
  1139. ########################################
  1140. def on_offset_object(self, widget):
  1141. """
  1142. Offsets the object's geometry by the vector specified
  1143. in the form. Re-plots.
  1144. :param widget: Ignored
  1145. :return: None
  1146. """
  1147. obj = self.get_current()
  1148. obj.read_form()
  1149. assert isinstance(obj, FlatCAMObj)
  1150. try:
  1151. vect = self.get_eval("entry_eval_" + obj.kind + "_offset")
  1152. except:
  1153. self.info("ERROR: Vector is not in (x, y) format.")
  1154. return
  1155. assert isinstance(obj, Geometry)
  1156. obj.offset(vect)
  1157. obj.plot()
  1158. return
  1159. def on_cb_plot_toggled(self, widget):
  1160. """
  1161. Callback for toggling the "Plot" checkbox. Re-plots.
  1162. :param widget: Ignored.
  1163. :return: None
  1164. """
  1165. self.get_current().read_form()
  1166. self.get_current().plot()
  1167. def on_about(self, widget):
  1168. """
  1169. Opens the 'About' dialog box.
  1170. :param widget: Ignored.
  1171. :return: None
  1172. """
  1173. about = self.builder.get_object("aboutdialog")
  1174. response = about.run()
  1175. #about.destroy()
  1176. about.hide()
  1177. def on_create_mirror(self, widget):
  1178. """
  1179. Creates a mirror image of an object to be used as a bottom layer.
  1180. :param widget: Ignored.
  1181. :return: None
  1182. """
  1183. # TODO: Move (some of) this to camlib!
  1184. # Object to mirror
  1185. try:
  1186. obj_name = self.builder.get_object("comboboxtext_bottomlayer").get_active_text()
  1187. fcobj = self.stuff[obj_name]
  1188. except KeyError:
  1189. self.info("WARNING: Cannot mirror that object.")
  1190. return
  1191. # For now, lets limit to Gerbers and Excellons.
  1192. # assert isinstance(gerb, FlatCAMGerber)
  1193. if not isinstance(fcobj, FlatCAMGerber) and not isinstance(fcobj, FlatCAMExcellon):
  1194. self.info("ERROR: Only Gerber and Excellon objects can be mirrored.")
  1195. return
  1196. # Mirror axis "X" or "Y
  1197. axis = self.get_radio_value({"rb_mirror_x": "X",
  1198. "rb_mirror_y": "Y"})
  1199. mode = self.get_radio_value({"rb_mirror_box": "box",
  1200. "rb_mirror_point": "point"})
  1201. if mode == "point": # A single point defines the mirror axis
  1202. # TODO: Error handling
  1203. px, py = eval(self.point_entry.get_text())
  1204. else: # The axis is the line dividing the box in the middle
  1205. name = self.box_combo.get_active_text()
  1206. bb_obj = self.stuff[name]
  1207. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1208. px = 0.5*(xmin+xmax)
  1209. py = 0.5*(ymin+ymax)
  1210. # Do the mirroring
  1211. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1212. # mirrored = affinity.scale(fcobj.solid_geometry, xscale, yscale, origin=(px, py))
  1213. #
  1214. # def obj_init(obj_inst, app_inst):
  1215. # obj_inst.solid_geometry = mirrored
  1216. #
  1217. # self.new_object("gerber", fcobj.options["name"] + "_mirror", obj_init)
  1218. fcobj.mirror(axis, [px, py])
  1219. fcobj.plot()
  1220. #self.on_update_plot(None)
  1221. def on_create_aligndrill(self, widget):
  1222. """
  1223. Creates alignment holes Excellon object. Creates mirror duplicates
  1224. of the specified holes around the specified axis.
  1225. :param widget: Ignored.
  1226. :return: None
  1227. """
  1228. # Mirror axis. Same as in on_create_mirror.
  1229. axis = self.get_radio_value({"rb_mirror_x": "X",
  1230. "rb_mirror_y": "Y"})
  1231. # TODO: Error handling
  1232. mode = self.get_radio_value({"rb_mirror_box": "box",
  1233. "rb_mirror_point": "point"})
  1234. if mode == "point":
  1235. px, py = eval(self.point_entry.get_text())
  1236. else:
  1237. name = self.box_combo.get_active_text()
  1238. bb_obj = self.stuff[name]
  1239. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1240. px = 0.5*(xmin+xmax)
  1241. py = 0.5*(ymin+ymax)
  1242. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1243. # Tools
  1244. dia = self.get_eval("entry_dblsided_alignholediam")
  1245. tools = {"1": {"C": dia}}
  1246. # Parse hole list
  1247. # TODO: Better parsing
  1248. holes = self.builder.get_object("entry_dblsided_alignholes").get_text()
  1249. holes = eval("[" + holes + "]")
  1250. drills = []
  1251. for hole in holes:
  1252. point = Point(hole)
  1253. point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  1254. drills.append({"point": point, "tool": "1"})
  1255. drills.append({"point": point_mirror, "tool": "1"})
  1256. def obj_init(obj_inst, app_inst):
  1257. obj_inst.tools = tools
  1258. obj_inst.drills = drills
  1259. obj_inst.create_geometry()
  1260. self.new_object("excellon", "Alignment Drills", obj_init)
  1261. def on_toggle_pointbox(self, widget):
  1262. """
  1263. Callback for radio selection change between point and box in the
  1264. Double-sided PCB tool. Updates the UI accordingly.
  1265. :param widget: Ignored.
  1266. :return: None
  1267. """
  1268. # Where the entry or combo go
  1269. box = self.builder.get_object("box_pointbox")
  1270. # Clear contents
  1271. children = box.get_children()
  1272. for child in children:
  1273. box.remove(child)
  1274. choice = self.get_radio_value({"rb_mirror_point": "point",
  1275. "rb_mirror_box": "box"})
  1276. if choice == "point":
  1277. self.point_entry = Gtk.Entry()
  1278. self.builder.get_object("box_pointbox").pack_start(self.point_entry,
  1279. False, False, 1)
  1280. self.point_entry.show()
  1281. else:
  1282. self.box_combo = Gtk.ComboBoxText()
  1283. self.builder.get_object("box_pointbox").pack_start(self.box_combo,
  1284. False, False, 1)
  1285. self.populate_objects_combo(self.box_combo)
  1286. self.box_combo.show()
  1287. def on_tools_doublesided(self, param):
  1288. """
  1289. Callback for menu item Tools->Double Sided PCB Tool. Launches the
  1290. tool placing its UI in the "Tool" tab in the notebook.
  1291. :param param: Ignored.
  1292. :return: None
  1293. """
  1294. # Were are we drawing the UI
  1295. box_tool = self.builder.get_object("box_tool")
  1296. # Remove anything else in the box
  1297. box_children = box_tool.get_children()
  1298. for child in box_children:
  1299. box_tool.remove(child)
  1300. # Get the UI
  1301. osw = self.builder.get_object("offscreenwindow_dblsided")
  1302. sw = self.builder.get_object("sw_dblsided")
  1303. osw.remove(sw)
  1304. vp = self.builder.get_object("vp_dblsided")
  1305. vp.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(1, 1, 1, 1))
  1306. # Put in the UI
  1307. box_tool.pack_start(sw, True, True, 0)
  1308. # INITIALIZATION
  1309. # Populate combo box
  1310. self.populate_objects_combo("comboboxtext_bottomlayer")
  1311. # Point entry
  1312. self.point_entry = Gtk.Entry()
  1313. box = self.builder.get_object("box_pointbox")
  1314. for child in box.get_children():
  1315. box.remove(child)
  1316. box.pack_start(self.point_entry, False, False, 1)
  1317. # Show the "Tool" tab
  1318. self.notebook.set_current_page(3)
  1319. sw.show_all()
  1320. def on_toggle_units(self, widget):
  1321. """
  1322. Callback for the Units radio-button change in the Options tab.
  1323. Changes the application's default units or the current project's units.
  1324. If changing the project's units, the change propagates to all of
  1325. the objects in the project.
  1326. :param widget: Ignored.
  1327. :return: None
  1328. """
  1329. if self.toggle_units_ignore:
  1330. return
  1331. combo_sel = self.combo_options.get_active()
  1332. options_set = [self.options, self.defaults][combo_sel]
  1333. # Options to scale
  1334. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1335. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1336. 'excellon_travelz', 'excellon_feedrate', 'cncjob_tooldia',
  1337. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1338. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1339. 'geometry_paintmargin']
  1340. def scale_options(factor):
  1341. for dim in dimensions:
  1342. options_set[dim] *= factor
  1343. # The scaling factor depending on choice of units.
  1344. factor = 1/25.4
  1345. if self.builder.get_object('rb_mm').get_active():
  1346. factor = 25.4
  1347. # App units. Convert without warning.
  1348. if combo_sel == 1:
  1349. self.read_form()
  1350. scale_options(factor)
  1351. self.options2form()
  1352. return
  1353. # Changing project units. Warn user.
  1354. label = Gtk.Label("Changing the units of the project causes all geometrical \n" + \
  1355. "properties of all objects to be scaled accordingly. Continue?")
  1356. dialog = Gtk.Dialog("Changing Project Units", self.window, 0,
  1357. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1358. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1359. dialog.set_default_size(150, 100)
  1360. dialog.set_modal(True)
  1361. box = dialog.get_content_area()
  1362. box.set_border_width(10)
  1363. box.add(label)
  1364. dialog.show_all()
  1365. response = dialog.run()
  1366. dialog.destroy()
  1367. if response == Gtk.ResponseType.OK:
  1368. #print "Converting units..."
  1369. #print "Converting options..."
  1370. self.read_form()
  1371. scale_options(factor)
  1372. self.options2form()
  1373. for obj in self.stuff:
  1374. units = self.get_radio_value({"rb_mm": "MM", "rb_inch": "IN"})
  1375. #print "Converting ", obj, " to ", units
  1376. self.stuff[obj].convert_units(units)
  1377. current = self.get_current()
  1378. if current is not None:
  1379. current.to_form()
  1380. self.plot_all()
  1381. else:
  1382. # Undo toggling
  1383. self.toggle_units_ignore = True
  1384. if self.builder.get_object('rb_mm').get_active():
  1385. self.builder.get_object('rb_inch').set_active(True)
  1386. else:
  1387. self.builder.get_object('rb_mm').set_active(True)
  1388. self.toggle_units_ignore = False
  1389. self.read_form()
  1390. self.info("Converted units to %s" % self.options["units"])
  1391. self.units_label.set_text("[" + self.options["units"] + "]")
  1392. def on_file_openproject(self, param):
  1393. """
  1394. Callback for menu item File->Open Project. Opens a file chooser and calls
  1395. ``self.open_project()`` after successful selection of a filename.
  1396. :param param: Ignored.
  1397. :return: None
  1398. """
  1399. def on_success(app_obj, filename):
  1400. app_obj.open_project(filename)
  1401. self.file_chooser_action(on_success)
  1402. def on_file_saveproject(self, param):
  1403. """
  1404. Callback for menu item File->Save Project. Saves the project to
  1405. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1406. if set to None. The project is saved by calling ``self.save_project()``.
  1407. :param param: Ignored.
  1408. :return: None
  1409. """
  1410. if self.project_filename is None:
  1411. self.on_file_saveprojectas(None)
  1412. else:
  1413. self.save_project(self.project_filename)
  1414. self.info("Project saved to: " + self.project_filename)
  1415. def on_file_saveprojectas(self, param):
  1416. """
  1417. Callback for menu item File->Save Project As... Opens a file
  1418. chooser and saves the project to the given file via
  1419. ``self.save_project()``.
  1420. :param param: Ignored.
  1421. :return: None
  1422. """
  1423. def on_success(app_obj, filename):
  1424. assert isinstance(app_obj, App)
  1425. app_obj.save_project(filename)
  1426. self.project_filename = filename
  1427. app_obj.info("Project saved to: " + filename)
  1428. self.file_chooser_save_action(on_success)
  1429. def on_file_saveprojectcopy(self, param):
  1430. """
  1431. Callback for menu item File->Save Project Copy... Opens a file
  1432. chooser and saves the project to the given file via
  1433. ``self.save_project``. It does not update ``self.project_filename`` so
  1434. subsequent save requests are done on the previous known filename.
  1435. :param param: Ignore.
  1436. :return: None
  1437. """
  1438. def on_success(app_obj, filename):
  1439. assert isinstance(app_obj, App)
  1440. app_obj.save_project(filename)
  1441. app_obj.info("Project copy saved to: " + filename)
  1442. self.file_chooser_save_action(on_success)
  1443. def on_options_app2project(self, param):
  1444. """
  1445. Callback for Options->Transfer Options->App=>Project. Copies options
  1446. from application defaults to project defaults.
  1447. :param param: Ignored.
  1448. :return: None
  1449. """
  1450. self.options.update(self.defaults)
  1451. self.options2form() # Update UI
  1452. def on_options_project2app(self, param):
  1453. """
  1454. Callback for Options->Transfer Options->Project=>App. Copies options
  1455. from project defaults to application defaults.
  1456. :param param: Ignored.
  1457. :return: None
  1458. """
  1459. self.defaults.update(self.options)
  1460. self.options2form() # Update UI
  1461. def on_options_project2object(self, param):
  1462. """
  1463. Callback for Options->Transfer Options->Project=>Object. Copies options
  1464. from project defaults to the currently selected object.
  1465. :param param: Ignored.
  1466. :return: None
  1467. """
  1468. obj = self.get_current()
  1469. if obj is None:
  1470. self.info("WARNING: No object selected.")
  1471. return
  1472. for option in self.options:
  1473. if option.find(obj.kind + "_") == 0:
  1474. oname = option[len(obj.kind)+1:]
  1475. obj.options[oname] = self.options[option]
  1476. obj.to_form() # Update UI
  1477. def on_options_object2project(self, param):
  1478. """
  1479. Callback for Options->Transfer Options->Object=>Project. Copies options
  1480. from the currently selected object to project defaults.
  1481. :param param: Ignored.
  1482. :return: None
  1483. """
  1484. obj = self.get_current()
  1485. if obj is None:
  1486. self.info("WARNING: No object selected.")
  1487. return
  1488. obj.read_form()
  1489. for option in obj.options:
  1490. if option in ['name']: # TODO: Handle this better...
  1491. continue
  1492. self.options[obj.kind + "_" + option] = obj.options[option]
  1493. self.options2form() # Update UI
  1494. def on_options_object2app(self, param):
  1495. """
  1496. Callback for Options->Transfer Options->Object=>App. Copies options
  1497. from the currently selected object to application defaults.
  1498. :param param: Ignored.
  1499. :return: None
  1500. """
  1501. obj = self.get_current()
  1502. if obj is None:
  1503. self.info("WARNING: No object selected.")
  1504. return
  1505. obj.read_form()
  1506. for option in obj.options:
  1507. if option in ['name']: # TODO: Handle this better...
  1508. continue
  1509. self.defaults[obj.kind + "_" + option] = obj.options[option]
  1510. self.options2form() # Update UI
  1511. def on_options_app2object(self, param):
  1512. """
  1513. Callback for Options->Transfer Options->App=>Object. Copies options
  1514. from application defaults to the currently selected object.
  1515. :param param: Ignored.
  1516. :return: None
  1517. """
  1518. obj = self.get_current()
  1519. if obj is None:
  1520. self.info("WARNING: No object selected.")
  1521. return
  1522. for option in self.defaults:
  1523. if option.find(obj.kind + "_") == 0:
  1524. oname = option[len(obj.kind)+1:]
  1525. obj.options[oname] = self.defaults[option]
  1526. obj.to_form() # Update UI
  1527. def on_file_savedefaults(self, param):
  1528. """
  1529. Callback for menu item File->Save Defaults. Saves application default options
  1530. ``self.defaults`` to defaults.json.
  1531. :param param: Ignored.
  1532. :return: None
  1533. """
  1534. # Read options from file
  1535. try:
  1536. f = open("defaults.json")
  1537. options = f.read()
  1538. f.close()
  1539. except:
  1540. self.info("ERROR: Could not load defaults file.")
  1541. return
  1542. try:
  1543. defaults = json.loads(options)
  1544. except:
  1545. e = sys.exc_info()[0]
  1546. print e
  1547. self.info("ERROR: Failed to parse defaults file.")
  1548. return
  1549. # Update options
  1550. assert isinstance(defaults, dict)
  1551. defaults.update(self.defaults)
  1552. # Save update options
  1553. try:
  1554. f = open("defaults.json", "w")
  1555. json.dump(defaults, f)
  1556. f.close()
  1557. except:
  1558. self.info("ERROR: Failed to write defaults to file.")
  1559. return
  1560. self.info("Defaults saved.")
  1561. def on_options_combo_change(self, widget):
  1562. """
  1563. Called when the combo box to choose between application defaults and
  1564. project option changes value. The corresponding variables are
  1565. copied to the UI.
  1566. :param widget: The widget from which this was called. Ignore.
  1567. :return: None
  1568. """
  1569. #combo_sel = self.combo_options.get_active()
  1570. #print "Options --> ", combo_sel
  1571. self.options2form()
  1572. def on_options_update(self, widget):
  1573. """
  1574. Called whenever a value in the options/defaults form changes.
  1575. All values are updated. Can be inhibited by setting ``self.options_update_ignore = True``,
  1576. which may be necessary when updating the UI from code and not by the user.
  1577. :param widget: The widget from which this was called. Ignore.
  1578. :return: None
  1579. """
  1580. if self.options_update_ignore:
  1581. return
  1582. self.read_form()
  1583. def on_scale_object(self, widget):
  1584. """
  1585. Callback for request to change an objects geometry scale. The object
  1586. is re-scaled and replotted.
  1587. :param widget: Ignored.
  1588. :return: None
  1589. """
  1590. obj = self.get_current()
  1591. factor = self.get_eval("entry_eval_" + obj.kind + "_scalefactor")
  1592. obj.scale(factor)
  1593. obj.to_form()
  1594. self.on_update_plot(None)
  1595. def on_canvas_configure(self, widget, event):
  1596. """
  1597. Called whenever the canvas changes size. The axes are updated such
  1598. as to use the whole canvas.
  1599. :param widget: Ignored.
  1600. :param event: Ignored.
  1601. :return: None
  1602. """
  1603. self.plotcanvas.auto_adjust_axes()
  1604. def on_row_activated(self, widget, path, col):
  1605. """
  1606. Callback for selection activation (Enter or double-click) on the Project list.
  1607. Switches the notebook page to the object properties form. Calls
  1608. ``self.notebook.set_current_page(1)``.
  1609. :param widget: Ignored.
  1610. :param path: Ignored.
  1611. :param col: Ignored.
  1612. :return: None
  1613. """
  1614. self.notebook.set_current_page(1)
  1615. def on_generate_gerber_bounding_box(self, widget):
  1616. """
  1617. Callback for request from the Gerber form to generate a bounding box for the
  1618. geometry in the object. Creates a FlatCAMGeometry with the bounding box.
  1619. The box can have rounded corners if specified in the form.
  1620. :param widget: Ignored.
  1621. :return: None
  1622. """
  1623. # TODO: Use Gerber.get_bounding_box(...)
  1624. gerber = self.get_current()
  1625. gerber.read_form()
  1626. name = gerber.options["name"] + "_bbox"
  1627. def geo_init(geo_obj, app_obj):
  1628. assert isinstance(geo_obj, FlatCAMGeometry)
  1629. # Bounding box with rounded corners
  1630. bounding_box = gerber.solid_geometry.envelope.buffer(gerber.options["bboxmargin"])
  1631. if not gerber.options["bboxrounded"]: # Remove rounded corners
  1632. bounding_box = bounding_box.envelope
  1633. geo_obj.solid_geometry = bounding_box
  1634. self.new_object("geometry", name, geo_init)
  1635. def on_update_plot(self, widget):
  1636. """
  1637. Callback for button on form for all kinds of objects.
  1638. Re-plots the current object only.
  1639. :param widget: The widget from which this was called. Ignored.
  1640. :return: None
  1641. """
  1642. obj = self.get_current()
  1643. obj.read_form()
  1644. self.set_progress_bar(0.5, "Plotting...")
  1645. def thread_func(app_obj):
  1646. assert isinstance(app_obj, App)
  1647. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Plotting..."))
  1648. #GLib.idle_add(lambda: app_obj.get_current().plot(app_obj.figure))
  1649. obj.plot()
  1650. #GLib.idle_add(lambda: app_obj.on_zoom_fit(None))
  1651. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "Idle"))
  1652. t = threading.Thread(target=thread_func, args=(self,))
  1653. t.daemon = True
  1654. t.start()
  1655. def on_generate_excellon_cncjob(self, widget):
  1656. """
  1657. Callback for button active/click on Excellon form to
  1658. create a CNC Job for the Excellon file.
  1659. :param widget: Ignored
  1660. :return: None
  1661. """
  1662. excellon = self.get_current()
  1663. excellon.read_form()
  1664. job_name = excellon.options["name"] + "_cnc"
  1665. # Object initialization function for app.new_object()
  1666. def job_init(job_obj, app_obj):
  1667. # excellon_ = self.get_current()
  1668. # assert isinstance(excellon_, FlatCAMExcellon)
  1669. assert isinstance(job_obj, FlatCAMCNCjob)
  1670. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1671. job_obj.z_cut = excellon.options["drillz"]
  1672. job_obj.z_move = excellon.options["travelz"]
  1673. job_obj.feedrate = excellon.options["feedrate"]
  1674. # There could be more than one drill size...
  1675. # job_obj.tooldia = # TODO: duplicate variable!
  1676. # job_obj.options["tooldia"] =
  1677. job_obj.generate_from_excellon_by_tool(excellon, excellon.options["toolselection"])
  1678. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1679. job_obj.gcode_parse()
  1680. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1681. job_obj.create_geometry()
  1682. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1683. # To be run in separate thread
  1684. def job_thread(app_obj):
  1685. app_obj.new_object("cncjob", job_name, job_init)
  1686. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1687. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1688. # Start the thread
  1689. t = threading.Thread(target=job_thread, args=(self,))
  1690. t.daemon = True
  1691. t.start()
  1692. def on_excellon_tool_choose(self, widget):
  1693. """
  1694. Callback for button on Excellon form to open up a window for
  1695. selecting tools.
  1696. :param widget: The widget from which this was called.
  1697. :return: None
  1698. """
  1699. excellon = self.get_current()
  1700. assert isinstance(excellon, FlatCAMExcellon)
  1701. excellon.show_tool_chooser()
  1702. def on_entry_eval_activate(self, widget):
  1703. """
  1704. Called when an entry is activated (eg. by hitting enter) if
  1705. set to do so. Its text is eval()'d and set to the returned value.
  1706. The current object is updated.
  1707. :param widget:
  1708. :return:
  1709. """
  1710. self.on_eval_update(widget)
  1711. obj = self.get_current()
  1712. assert isinstance(obj, FlatCAMObj)
  1713. obj.read_form()
  1714. def on_gerber_generate_noncopper(self, widget):
  1715. """
  1716. Callback for button on Gerber form to create a geometry object
  1717. with polygons covering the area without copper or negative of the
  1718. Gerber.
  1719. :param widget: The widget from which this was called.
  1720. :return: None
  1721. """
  1722. gerb = self.get_current()
  1723. gerb.read_form()
  1724. name = gerb.options["name"] + "_noncopper"
  1725. def geo_init(geo_obj, app_obj):
  1726. assert isinstance(geo_obj, FlatCAMGeometry)
  1727. bounding_box = gerb.solid_geometry.envelope.buffer(gerb.options["noncoppermargin"])
  1728. if not gerb.options["noncopperrounded"]:
  1729. bounding_box = bounding_box.envelope
  1730. non_copper = bounding_box.difference(gerb.solid_geometry)
  1731. geo_obj.solid_geometry = non_copper
  1732. # TODO: Check for None
  1733. self.new_object("geometry", name, geo_init)
  1734. def on_gerber_generate_cutout(self, widget):
  1735. """
  1736. Callback for button on Gerber form to create geometry with lines
  1737. for cutting off the board.
  1738. :param widget: The widget from which this was called.
  1739. :return: None
  1740. """
  1741. gerb = self.get_current()
  1742. gerb.read_form()
  1743. name = gerb.options["name"] + "_cutout"
  1744. def geo_init(geo_obj, app_obj):
  1745. margin = gerb.options["cutoutmargin"] + gerb.options["cutouttooldia"]/2
  1746. gap_size = gerb.options["cutoutgapsize"] + gerb.options["cutouttooldia"]
  1747. minx, miny, maxx, maxy = gerb.bounds()
  1748. minx -= margin
  1749. maxx += margin
  1750. miny -= margin
  1751. maxy += margin
  1752. midx = 0.5 * (minx + maxx)
  1753. midy = 0.5 * (miny + maxy)
  1754. hgap = 0.5 * gap_size
  1755. pts = [[midx - hgap, maxy],
  1756. [minx, maxy],
  1757. [minx, midy + hgap],
  1758. [minx, midy - hgap],
  1759. [minx, miny],
  1760. [midx - hgap, miny],
  1761. [midx + hgap, miny],
  1762. [maxx, miny],
  1763. [maxx, midy - hgap],
  1764. [maxx, midy + hgap],
  1765. [maxx, maxy],
  1766. [midx + hgap, maxy]]
  1767. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  1768. [pts[6], pts[7], pts[10], pts[11]]],
  1769. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  1770. [pts[3], pts[4], pts[7], pts[8]]],
  1771. "4": [[pts[0], pts[1], pts[2]],
  1772. [pts[3], pts[4], pts[5]],
  1773. [pts[6], pts[7], pts[8]],
  1774. [pts[9], pts[10], pts[11]]]}
  1775. cuts = cases[app.get_radio_value({"rb_2tb": "tb", "rb_2lr": "lr", "rb_4": "4"})]
  1776. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  1777. # TODO: Check for None
  1778. self.new_object("geometry", name, geo_init)
  1779. def on_eval_update(self, widget):
  1780. """
  1781. Modifies the content of a Gtk.Entry by running
  1782. eval() on its contents and puting it back as a
  1783. string.
  1784. :param widget: The widget from which this was called.
  1785. :return: None
  1786. """
  1787. # TODO: error handling here
  1788. widget.set_text(str(eval(widget.get_text())))
  1789. def on_generate_isolation(self, widget):
  1790. """
  1791. Callback for button on Gerber form to create isolation routing geometry.
  1792. :param widget: The widget from which this was called.
  1793. :return: None
  1794. """
  1795. gerb = self.get_current()
  1796. gerb.read_form()
  1797. dia = gerb.options["isotooldia"]
  1798. passes = int(gerb.options["isopasses"])
  1799. overlap = gerb.options["isooverlap"] * dia
  1800. for i in range(passes):
  1801. offset = (2*i + 1)/2.0 * dia - i*overlap
  1802. iso_name = gerb.options["name"] + "_iso%d" % (i+1)
  1803. # TODO: This is ugly. Create way to pass data into init function.
  1804. def iso_init(geo_obj, app_obj):
  1805. # Propagate options
  1806. geo_obj.options["cnctooldia"] = gerb.options["isotooldia"]
  1807. geo_obj.solid_geometry = gerb.isolation_geometry(offset)
  1808. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  1809. # TODO: Do something if this is None. Offer changing name?
  1810. self.new_object("geometry", iso_name, iso_init)
  1811. def on_generate_cncjob(self, widget):
  1812. """
  1813. Callback for button on geometry form to generate CNC job.
  1814. :param widget: The widget from which this was called.
  1815. :return: None
  1816. """
  1817. source_geo = self.get_current()
  1818. source_geo.read_form()
  1819. job_name = source_geo.options["name"] + "_cnc"
  1820. # Object initialization function for app.new_object()
  1821. # RUNNING ON SEPARATE THREAD!
  1822. def job_init(job_obj, app_obj):
  1823. assert isinstance(job_obj, FlatCAMCNCjob)
  1824. # Propagate options
  1825. job_obj.options["tooldia"] = source_geo.options["cnctooldia"]
  1826. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1827. job_obj.z_cut = source_geo.options["cutz"]
  1828. job_obj.z_move = source_geo.options["travelz"]
  1829. job_obj.feedrate = source_geo.options["feedrate"]
  1830. GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry..."))
  1831. # TODO: The tolerance should not be hard coded. Just for testing.
  1832. job_obj.generate_from_geometry(source_geo, tolerance=0.0005)
  1833. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1834. job_obj.gcode_parse()
  1835. # TODO: job_obj.create_geometry creates stuff that is not used.
  1836. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1837. #job_obj.create_geometry()
  1838. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1839. # To be run in separate thread
  1840. def job_thread(app_obj):
  1841. app_obj.new_object("cncjob", job_name, job_init)
  1842. GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name))
  1843. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1844. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1845. # Start the thread
  1846. t = threading.Thread(target=job_thread, args=(self,))
  1847. t.daemon = True
  1848. t.start()
  1849. def on_generate_paintarea(self, widget):
  1850. """
  1851. Callback for button on geometry form.
  1852. Subscribes to the "Click on plot" event and continues
  1853. after the click. Finds the polygon containing
  1854. the clicked point and runs clear_poly() on it, resulting
  1855. in a new FlatCAMGeometry object.
  1856. :param widget: The widget from which this was called.
  1857. :return: None
  1858. """
  1859. self.info("Click inside the desired polygon.")
  1860. geo = self.get_current()
  1861. geo.read_form()
  1862. assert isinstance(geo, FlatCAMGeometry)
  1863. tooldia = geo.options["painttooldia"]
  1864. overlap = geo.options["paintoverlap"]
  1865. # To be called after clicking on the plot.
  1866. def doit(event):
  1867. self.plot_click_subscribers.pop("generate_paintarea")
  1868. self.info("")
  1869. point = [event.xdata, event.ydata]
  1870. poly = find_polygon(geo.solid_geometry, point)
  1871. # Initializes the new geometry object
  1872. def gen_paintarea(geo_obj, app_obj):
  1873. assert isinstance(geo_obj, FlatCAMGeometry)
  1874. assert isinstance(app_obj, App)
  1875. cp = clear_poly(poly.buffer(-geo.options["paintmargin"]), tooldia, overlap)
  1876. geo_obj.solid_geometry = cp
  1877. geo_obj.options["cnctooldia"] = tooldia
  1878. name = self.selected_item_name + "_paint"
  1879. self.new_object("geometry", name, gen_paintarea)
  1880. self.plot_click_subscribers["generate_paintarea"] = doit
  1881. def on_cncjob_exportgcode(self, widget):
  1882. """
  1883. Called from button on CNCjob form to save the G-Code from the object.
  1884. :param widget: The widget from which this was called.
  1885. :return: None
  1886. """
  1887. def on_success(app_obj, filename):
  1888. cncjob = app_obj.get_current()
  1889. f = open(filename, 'w')
  1890. f.write(cncjob.gcode)
  1891. f.close()
  1892. app_obj.info("Saved to: " + filename)
  1893. self.file_chooser_save_action(on_success)
  1894. def on_delete(self, widget):
  1895. """
  1896. Delete the currently selected FlatCAMObj.
  1897. :param widget: The widget from which this was called.
  1898. :return: None
  1899. """
  1900. # Keep this for later
  1901. name = copy.copy(self.selected_item_name)
  1902. # Remove plot
  1903. self.plotcanvas.figure.delaxes(self.get_current().axes)
  1904. self.plotcanvas.auto_adjust_axes()
  1905. # Remove from dictionary
  1906. self.stuff.pop(self.selected_item_name)
  1907. # Update UI
  1908. self.build_list() # Update the items list
  1909. self.info("Object deleted: %s" % name)
  1910. def on_toolbar_replot(self, widget):
  1911. """
  1912. Callback for toolbar button. Re-plots all objects.
  1913. :param widget: The widget from which this was called.
  1914. :return: None
  1915. """
  1916. self.get_current().read_form()
  1917. self.plot_all()
  1918. def on_clear_plots(self, widget):
  1919. """
  1920. Callback for toolbar button. Clears all plots.
  1921. :param widget: The widget from which this was called.
  1922. :return: None
  1923. """
  1924. self.plotcanvas.clear()
  1925. def on_activate_name(self, entry):
  1926. """
  1927. Hitting 'Enter' after changing the name of an item
  1928. updates the item dictionary and re-builds the item list.
  1929. :param entry: The widget from which this was called.
  1930. :return: None
  1931. """
  1932. # Disconnect event listener
  1933. self.tree.get_selection().disconnect(self.signal_id)
  1934. new_name = entry.get_text() # Get from form
  1935. self.stuff[new_name] = self.stuff.pop(self.selected_item_name) # Update dictionary
  1936. self.stuff[new_name].options["name"] = new_name # update object
  1937. self.info('Name change: ' + self.selected_item_name + " to " + new_name)
  1938. self.selected_item_name = new_name # Update selection name
  1939. self.build_list() # Update the items list
  1940. # Reconnect event listener
  1941. self.signal_id = self.tree.get_selection().connect(
  1942. "changed", self.on_tree_selection_changed)
  1943. def on_tree_selection_changed(self, selection):
  1944. """
  1945. Callback for selection change in the project list. This changes
  1946. the currently selected FlatCAMObj.
  1947. :param selection: Selection associated to the project tree or list
  1948. :type selection: Gtk.TreeSelection
  1949. :return: None
  1950. """
  1951. print "DEBUG: on_tree_selection_change(): ",
  1952. model, treeiter = selection.get_selected()
  1953. if treeiter is not None:
  1954. # Save data for previous selection
  1955. obj = self.get_current()
  1956. if obj is not None:
  1957. obj.read_form()
  1958. print "DEBUG: You selected", model[treeiter][0]
  1959. self.selected_item_name = model[treeiter][0]
  1960. obj_new = self.get_current()
  1961. if obj_new is not None:
  1962. GLib.idle_add(lambda: obj_new.build_ui())
  1963. else:
  1964. print "DEBUG: Nothing selected"
  1965. self.selected_item_name = None
  1966. self.setup_component_editor()
  1967. def on_file_new(self, param):
  1968. """
  1969. Callback for menu item File->New. Returns the application to its
  1970. startup state.
  1971. :param param: Whatever is passed by the event. Ignore.
  1972. :return: None
  1973. """
  1974. # Remove everythong from memory
  1975. # Clear plot
  1976. self.plotcanvas.clear()
  1977. # Clear object editor
  1978. #self.setup_component_editor()
  1979. # Clear data
  1980. self.stuff = {}
  1981. # Clear list
  1982. #self.tree_select.unselect_all()
  1983. self.build_list()
  1984. # Clear project filename
  1985. self.project_filename = None
  1986. # Re-fresh project options
  1987. self.on_options_app2project(None)
  1988. def on_filequit(self, param):
  1989. """
  1990. Callback for menu item File->Quit. Closes the application.
  1991. :param param: Whatever is passed by the event. Ignore.
  1992. :return: None
  1993. """
  1994. self.window.destroy()
  1995. Gtk.main_quit()
  1996. def on_closewindow(self, param):
  1997. """
  1998. Callback for closing the main window.
  1999. :param param: Whatever is passed by the event. Ignore.
  2000. :return: None
  2001. """
  2002. self.window.destroy()
  2003. Gtk.main_quit()
  2004. def file_chooser_action(self, on_success):
  2005. """
  2006. Opens the file chooser and runs on_success on a separate thread
  2007. upon completion of valid file choice.
  2008. :param on_success: A function to run upon completion of a valid file
  2009. selection. Takes 2 parameters: The app instance and the filename.
  2010. Note that it is run on a separate thread, therefore it must take the
  2011. appropriate precautions when accessing shared resources.
  2012. :type on_success: func
  2013. :return: None
  2014. """
  2015. dialog = Gtk.FileChooserDialog("Please choose a file", self.window,
  2016. Gtk.FileChooserAction.OPEN,
  2017. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2018. Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
  2019. response = dialog.run()
  2020. if response == Gtk.ResponseType.OK:
  2021. filename = dialog.get_filename()
  2022. dialog.destroy()
  2023. t = threading.Thread(target=on_success, args=(self, filename))
  2024. t.daemon = True
  2025. t.start()
  2026. #on_success(self, filename)
  2027. elif response == Gtk.ResponseType.CANCEL:
  2028. self.info("Open cancelled.") # print("Cancel clicked")
  2029. dialog.destroy()
  2030. def file_chooser_save_action(self, on_success):
  2031. """
  2032. Opens the file chooser and runs on_success upon completion of valid file choice.
  2033. :param on_success: A function to run upon selection of a filename. Takes 2
  2034. parameters: The instance of the application (App) and the chosen filename. This
  2035. gets run immediately in the same thread.
  2036. :return: None
  2037. """
  2038. dialog = Gtk.FileChooserDialog("Save file", self.window,
  2039. Gtk.FileChooserAction.SAVE,
  2040. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2041. Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
  2042. dialog.set_current_name("Untitled")
  2043. response = dialog.run()
  2044. if response == Gtk.ResponseType.OK:
  2045. filename = dialog.get_filename()
  2046. dialog.destroy()
  2047. on_success(self, filename)
  2048. elif response == Gtk.ResponseType.CANCEL:
  2049. self.info("Save cancelled.") # print("Cancel clicked")
  2050. dialog.destroy()
  2051. def on_fileopengerber(self, param):
  2052. """
  2053. Callback for menu item File->Open Gerber. Defines a function that is then passed
  2054. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMGerber object
  2055. and updates the progress bar throughout the process.
  2056. :param param: Ignore
  2057. :return: None
  2058. """
  2059. # IMPORTANT: on_success will run on a separate thread. Use
  2060. # GLib.idle_add(function, **kwargs) to launch actions that will
  2061. # updata the GUI.
  2062. def on_success(app_obj, filename):
  2063. assert isinstance(app_obj, App)
  2064. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Gerber ..."))
  2065. def obj_init(gerber_obj, app_obj):
  2066. assert isinstance(gerber_obj, FlatCAMGerber)
  2067. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2068. gerber_obj.parse_file(filename)
  2069. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Creating Geometry ..."))
  2070. gerber_obj.create_geometry()
  2071. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2072. name = filename.split('/')[-1].split('\\')[-1]
  2073. app_obj.new_object("gerber", name, obj_init)
  2074. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2075. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2076. # on_success gets run on a separate thread
  2077. self.file_chooser_action(on_success)
  2078. def on_fileopenexcellon(self, param):
  2079. """
  2080. Callback for menu item File->Open Excellon. Defines a function that is then passed
  2081. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMExcellon object
  2082. and updates the progress bar throughout the process.
  2083. :param param: Ignore
  2084. :return: None
  2085. """
  2086. # IMPORTANT: on_success will run on a separate thread. Use
  2087. # GLib.idle_add(function, **kwargs) to launch actions that will
  2088. # updata the GUI.
  2089. def on_success(app_obj, filename):
  2090. assert isinstance(app_obj, App)
  2091. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Excellon ..."))
  2092. def obj_init(excellon_obj, app_obj):
  2093. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2094. excellon_obj.parse_file(filename)
  2095. excellon_obj.create_geometry()
  2096. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2097. name = filename.split('/')[-1].split('\\')[-1]
  2098. app_obj.new_object("excellon", name, obj_init)
  2099. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2100. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2101. # on_success gets run on a separate thread
  2102. self.file_chooser_action(on_success)
  2103. def on_fileopengcode(self, param):
  2104. """
  2105. Callback for menu item File->Open G-Code. Defines a function that is then passed
  2106. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMCNCjob object
  2107. and updates the progress bar throughout the process.
  2108. :param param: Ignore
  2109. :return: None
  2110. """
  2111. # IMPORTANT: on_success will run on a separate thread. Use
  2112. # GLib.idle_add(function, **kwargs) to launch actions that will
  2113. # updata the GUI.
  2114. def on_success(app_obj, filename):
  2115. assert isinstance(app_obj, App)
  2116. def obj_init(job_obj, app_obj_):
  2117. """
  2118. :type app_obj_: App
  2119. """
  2120. assert isinstance(app_obj_, App)
  2121. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.1, "Opening G-Code ..."))
  2122. f = open(filename)
  2123. gcode = f.read()
  2124. f.close()
  2125. job_obj.gcode = gcode
  2126. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.2, "Parsing ..."))
  2127. job_obj.gcode_parse()
  2128. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Creating geometry ..."))
  2129. job_obj.create_geometry()
  2130. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Plotting ..."))
  2131. name = filename.split('/')[-1].split('\\')[-1]
  2132. app_obj.new_object("cncjob", name, obj_init)
  2133. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2134. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2135. # on_success gets run on a separate thread
  2136. self.file_chooser_action(on_success)
  2137. def on_mouse_move_over_plot(self, event):
  2138. """
  2139. Callback for the mouse motion event over the plot. This event is generated
  2140. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2141. For details, see: http://matplotlib.org/users/event_handling.html
  2142. :param event: Contains information about the event.
  2143. :return: None
  2144. """
  2145. try: # May fail in case mouse not within axes
  2146. self.position_label.set_label("X: %.4f Y: %.4f" % (
  2147. event.xdata, event.ydata))
  2148. self.mouse = [event.xdata, event.ydata]
  2149. for subscriber in self.plot_mousemove_subscribers:
  2150. self.plot_mousemove_subscribers[subscriber](event)
  2151. except:
  2152. self.position_label.set_label("")
  2153. self.mouse = None
  2154. def on_click_over_plot(self, event):
  2155. """
  2156. Callback for the mouse click event over the plot. This event is generated
  2157. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2158. For details, see: http://matplotlib.org/users/event_handling.html
  2159. Default actions are:
  2160. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  2161. :param event: Contains information about the event, like which button
  2162. was clicked, the pixel coordinates and the axes coordinates.
  2163. :return: None
  2164. """
  2165. # For key presses
  2166. self.plotcanvas.canvas.grab_focus()
  2167. try:
  2168. print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  2169. event.button, event.x, event.y, event.xdata, event.ydata)
  2170. # TODO: This custom subscription mechanism is probably not necessary.
  2171. for subscriber in self.plot_click_subscribers:
  2172. self.plot_click_subscribers[subscriber](event)
  2173. self.clipboard.set_text("(%.4f, %.4f)" % (event.xdata, event.ydata), -1)
  2174. except Exception, e:
  2175. print "Outside plot!"
  2176. def on_zoom_in(self, event):
  2177. """
  2178. Callback for zoom-in request. This can be either from the corresponding
  2179. toolbar button or the '3' key when the canvas is focused. Calls ``self.zoom()``.
  2180. :param event: Ignored.
  2181. :return: None
  2182. """
  2183. self.plotcanvas.zoom(1.5)
  2184. return
  2185. def on_zoom_out(self, event):
  2186. """
  2187. Callback for zoom-out request. This can be either from the corresponding
  2188. toolbar button or the '2' key when the canvas is focused. Calls ``self.zoom()``.
  2189. :param event: Ignored.
  2190. :return: None
  2191. """
  2192. self.plotcanvas.zoom(1 / 1.5)
  2193. def on_zoom_fit(self, event):
  2194. """
  2195. Callback for zoom-out request. This can be either from the corresponding
  2196. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2197. with axes limits from the geometry bounds of all objects.
  2198. :param event: Ignored.
  2199. :return: None
  2200. """
  2201. xmin, ymin, xmax, ymax = get_bounds(self.stuff)
  2202. width = xmax - xmin
  2203. height = ymax - ymin
  2204. xmin -= 0.05 * width
  2205. xmax += 0.05 * width
  2206. ymin -= 0.05 * height
  2207. ymax += 0.05 * height
  2208. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  2209. def on_key_over_plot(self, event):
  2210. """
  2211. Callback for the key pressed event when the canvas is focused. Keyboard
  2212. shortcuts are handled here. So far, these are the shortcuts:
  2213. ========== ============================================
  2214. Key Action
  2215. ========== ============================================
  2216. '1' Zoom-fit. Fits the axes limits to the data.
  2217. '2' Zoom-out.
  2218. '3' Zoom-in.
  2219. ========== ============================================
  2220. :param event: Ignored.
  2221. :return: None
  2222. """
  2223. #print 'you pressed', event.key, event.xdata, event.ydata
  2224. if event.key == '1': # 1
  2225. self.on_zoom_fit(None)
  2226. return
  2227. if event.key == '2': # 2
  2228. self.plotcanvas.zoom(1 / 1.5, self.mouse)
  2229. return
  2230. if event.key == '3': # 3
  2231. self.plotcanvas.zoom(1.5, self.mouse)
  2232. return
  2233. if event.key == 'm':
  2234. if self.measure.toggle_active():
  2235. self.info("Measuring tool ON")
  2236. else:
  2237. self.info("Measuring tool OFF")
  2238. return
  2239. class BaseDraw:
  2240. def __init__(self, plotcanvas, name=None):
  2241. """
  2242. :param plotcanvas: The PlotCanvas where the drawing tool will operate.
  2243. :type plotcanvas: PlotCanvas
  2244. """
  2245. self.plotcanvas = plotcanvas
  2246. # Must have unique axes
  2247. charset = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
  2248. self.name = name or [random.choice(charset) for i in range(20)]
  2249. self.axes = self.plotcanvas.new_axes(self.name)
  2250. class DrawingObject(BaseDraw):
  2251. def __init__(self, plotcanvas, name=None):
  2252. """
  2253. Possible objects are:
  2254. * Point
  2255. * Line
  2256. * Rectangle
  2257. * Circle
  2258. * Polygon
  2259. """
  2260. BaseDraw.__init__(self, plotcanvas)
  2261. self.properties = {}
  2262. def plot(self):
  2263. return
  2264. def update_plot(self):
  2265. self.axes.cla()
  2266. self.plot()
  2267. self.plotcanvas.auto_adjust_axes()
  2268. class DrawingPoint(DrawingObject):
  2269. def __init__(self, plotcanvas, name=None, coord=None):
  2270. DrawingObject.__init__(self, plotcanvas)
  2271. self.properties.update({
  2272. "coordinate": coord
  2273. })
  2274. def plot(self):
  2275. x, y = self.properties["coordinate"]
  2276. self.axes.plot(x, y, 'o')
  2277. class Measurement:
  2278. def __init__(self, container, axes, click_subscibers, move_subscribers, update=None):
  2279. self.update = update
  2280. self.container = container
  2281. self.frame = None
  2282. self.label = None
  2283. self.click_subscribers = click_subscibers
  2284. self.move_subscribers = move_subscribers
  2285. self.point1 = None
  2286. self.point2 = None
  2287. self.active = False
  2288. def toggle_active(self, *args):
  2289. if self.active: # Deactivate
  2290. self.active = False
  2291. self.move_subscribers.pop("meas")
  2292. self.click_subscribers.pop("meas")
  2293. self.container.remove(self.frame)
  2294. if self.update is not None:
  2295. self.update()
  2296. return False
  2297. else: # Activate
  2298. print "DEBUG: Activating Measurement Tool..."
  2299. self.active = True
  2300. self.click_subscribers["meas"] = self.on_click
  2301. self.move_subscribers["meas"] = self.on_move
  2302. self.frame = Gtk.Frame()
  2303. self.frame.set_margin_right(5)
  2304. self.frame.set_margin_top(3)
  2305. align = Gtk.Alignment()
  2306. align.set(0, 0.5, 0, 0)
  2307. align.set_padding(4, 4, 4, 4)
  2308. self.label = Gtk.Label()
  2309. self.label.set_label("Click on a reference point...")
  2310. abox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
  2311. abox.pack_start(Gtk.Image.new_from_file('share/measure16.png'), False, False, 0)
  2312. abox.pack_start(self.label, False, False, 0)
  2313. align.add(abox)
  2314. self.frame.add(align)
  2315. self.container.pack_end(self.frame, False, True, 1)
  2316. self.frame.show_all()
  2317. return True
  2318. def on_move(self, event):
  2319. if self.point1 is None:
  2320. self.label.set_label("Click on a reference point...")
  2321. else:
  2322. dx = event.xdata - self.point1[0]
  2323. dy = event.ydata - self.point1[1]
  2324. d = sqrt(dx**2 + dy**2)
  2325. self.label.set_label("D = %.4f D(x) = %.4f D(y) = %.4f" % (d, dx, dy))
  2326. if self.update is not None:
  2327. self.update()
  2328. def on_click(self, event):
  2329. if self.point1 is None:
  2330. self.point1 = (event.xdata, event.ydata)
  2331. return
  2332. else:
  2333. self.point2 = copy.copy(self.point1)
  2334. self.point1 = (event.xdata, event.ydata)
  2335. self.on_move(event)
  2336. class PlotCanvas:
  2337. """
  2338. Class handling the plotting area in the application.
  2339. """
  2340. def __init__(self, container):
  2341. """
  2342. The constructor configures the Matplotlib figure that
  2343. will contain all plots, creates the base axes and connects
  2344. events to the plotting area.
  2345. :param container: The parent container in which to draw plots.
  2346. :rtype: PlotCanvas
  2347. """
  2348. # Options
  2349. self.x_margin = 15 # pixels
  2350. self.y_margin = 25 # Pixels
  2351. # Parent container
  2352. self.container = container
  2353. # Plots go onto a single matplotlib.figure
  2354. self.figure = Figure(dpi=50) # TODO: dpi needed?
  2355. self.figure.patch.set_visible(False)
  2356. # These axes show the ticks and grid. No plotting done here.
  2357. # New axes must have a label, otherwise mpl returns an existing one.
  2358. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  2359. self.axes.set_aspect(1)
  2360. self.axes.grid(True)
  2361. # The canvas is the top level container (Gtk.DrawingArea)
  2362. self.canvas = FigureCanvas(self.figure)
  2363. self.canvas.set_hexpand(1)
  2364. self.canvas.set_vexpand(1)
  2365. self.canvas.set_can_focus(True) # For key press
  2366. # Attach to parent
  2367. self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  2368. # Events
  2369. self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
  2370. self.canvas.connect('configure-event', self.auto_adjust_axes)
  2371. self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  2372. self.canvas.connect("scroll-event", self.on_scroll)
  2373. self.mouse = [0,0]
  2374. def mpl_connect(self, event_name, callback):
  2375. """
  2376. Attach an event handler to the canvas through the Matplotlib interface.
  2377. :param event_name: Name of the event
  2378. :type event_name: str
  2379. :param callback: Function to call
  2380. :type callback: func
  2381. :return: Nothing
  2382. """
  2383. self.canvas.mpl_connect(event_name, callback)
  2384. def connect(self, event_name, callback):
  2385. """
  2386. Attach an event handler to the canvas through the native GTK interface.
  2387. :param event_name: Name of the event
  2388. :type event_name: str
  2389. :param callback: Function to call
  2390. :type callback: function
  2391. :return: Nothing
  2392. """
  2393. self.canvas.connect(event_name, callback)
  2394. def clear(self):
  2395. """
  2396. Clears axes and figure.
  2397. :return: None
  2398. """
  2399. # Clear
  2400. self.axes.cla()
  2401. self.figure.clf()
  2402. # Re-build
  2403. self.figure.add_axes(self.axes)
  2404. self.axes.set_aspect(1)
  2405. self.axes.grid(True)
  2406. # Re-draw
  2407. self.canvas.queue_draw()
  2408. def adjust_axes(self, xmin, ymin, xmax, ymax):
  2409. """
  2410. Adjusts all axes while maintaining the use of the whole canvas
  2411. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  2412. request that will be modified to fit these restrictions.
  2413. :param xmin: Requested minimum value for the X axis.
  2414. :type xmin: float
  2415. :param ymin: Requested minimum value for the Y axis.
  2416. :type ymin: float
  2417. :param xmax: Requested maximum value for the X axis.
  2418. :type xmax: float
  2419. :param ymax: Requested maximum value for the Y axis.
  2420. :type ymax: float
  2421. :return: None
  2422. """
  2423. width = xmax - xmin
  2424. height = ymax - ymin
  2425. try:
  2426. r = width / height
  2427. except:
  2428. print "ERROR: Height is", height
  2429. return
  2430. canvas_w, canvas_h = self.canvas.get_width_height()
  2431. canvas_r = float(canvas_w) / canvas_h
  2432. x_ratio = float(self.x_margin) / canvas_w
  2433. y_ratio = float(self.y_margin) / canvas_h
  2434. if r > canvas_r:
  2435. ycenter = (ymin + ymax) / 2.0
  2436. newheight = height * r / canvas_r
  2437. ymin = ycenter - newheight / 2.0
  2438. ymax = ycenter + newheight / 2.0
  2439. else:
  2440. xcenter = (xmax + ymin) / 2.0
  2441. newwidth = width * canvas_r / r
  2442. xmin = xcenter - newwidth / 2.0
  2443. xmax = xcenter + newwidth / 2.0
  2444. # Adjust axes
  2445. for ax in self.figure.get_axes():
  2446. if ax._label != 'base':
  2447. ax.set_frame_on(False) # No frame
  2448. ax.set_xticks([]) # No tick
  2449. ax.set_yticks([]) # No ticks
  2450. ax.patch.set_visible(False) # No background
  2451. ax.set_aspect(1)
  2452. ax.set_xlim((xmin, xmax))
  2453. ax.set_ylim((ymin, ymax))
  2454. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  2455. # Re-draw
  2456. self.canvas.queue_draw()
  2457. def auto_adjust_axes(self, *args):
  2458. """
  2459. Calls ``adjust_axes()`` using the extents of the base axes.
  2460. :rtype : None
  2461. :return: None
  2462. """
  2463. xmin, xmax = self.axes.get_xlim()
  2464. ymin, ymax = self.axes.get_ylim()
  2465. self.adjust_axes(xmin, ymin, xmax, ymax)
  2466. def zoom(self, factor, center=None):
  2467. """
  2468. Zooms the plot by factor around a given
  2469. center point. Takes care of re-drawing.
  2470. :param factor: Number by which to scale the plot.
  2471. :type factor: float
  2472. :param center: Coordinates [x, y] of the point around which to scale the plot.
  2473. :type center: list
  2474. :return: None
  2475. """
  2476. xmin, xmax = self.axes.get_xlim()
  2477. ymin, ymax = self.axes.get_ylim()
  2478. width = xmax - xmin
  2479. height = ymax - ymin
  2480. if center is None or center == [None, None]:
  2481. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  2482. # For keeping the point at the pointer location
  2483. relx = (xmax - center[0]) / width
  2484. rely = (ymax - center[1]) / height
  2485. new_width = width / factor
  2486. new_height = height / factor
  2487. xmin = center[0] - new_width * (1 - relx)
  2488. xmax = center[0] + new_width * relx
  2489. ymin = center[1] - new_height * (1 - rely)
  2490. ymax = center[1] + new_height * rely
  2491. # Adjust axes
  2492. for ax in self.figure.get_axes():
  2493. ax.set_xlim((xmin, xmax))
  2494. ax.set_ylim((ymin, ymax))
  2495. # Re-draw
  2496. self.canvas.queue_draw()
  2497. def new_axes(self, name):
  2498. """
  2499. Creates and returns an Axes object attached to this object's Figure.
  2500. :param name: Unique label for the axes.
  2501. :return: Axes attached to the figure.
  2502. :rtype: Axes
  2503. """
  2504. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  2505. # def plot_axes(self, axes):
  2506. #
  2507. # if axes not in self.figure.axes:
  2508. # self.figure.add_axes(axes)
  2509. #
  2510. # # Basic configuration
  2511. # axes.set_frame_on(False) # No frame
  2512. # axes.set_xticks([]) # No tick
  2513. # axes.set_yticks([]) # No ticks
  2514. # axes.patch.set_visible(False) # No background
  2515. # axes.set_aspect(1)
  2516. #
  2517. # # Adjust limits
  2518. # self.auto_adjust_axes()
  2519. def on_scroll(self, canvas, event):
  2520. """
  2521. Scroll event handler.
  2522. :param canvas: The widget generating the event. Ignored.
  2523. :param event: Event object containing the event information.
  2524. :return: None
  2525. """
  2526. z, direction = event.get_scroll_direction()
  2527. if direction is Gdk.ScrollDirection.UP:
  2528. self.zoom(1.5, self.mouse)
  2529. else:
  2530. self.zoom(1/1.5, self.mouse)
  2531. def on_mouse_move(self, event):
  2532. """
  2533. Mouse movement event hadler.
  2534. :param event: Contains information about the event.
  2535. :return: None
  2536. """
  2537. self.mouse = [event.xdata, event.ydata]
  2538. app = App()
  2539. Gtk.main()