FlatCAM.py 96 KB

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