FlatCAM.py 99 KB

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