FlatCAM.py 91 KB

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