FlatCAM.py 96 KB

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