FlatCAM.py 101 KB

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