FlatCAM.py 102 KB

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