FlatCAMApp.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  1. import traceback
  2. import sys
  3. import urllib
  4. from copy import copy
  5. import random
  6. import logging
  7. import simplejson as json
  8. import re
  9. import webbrowser
  10. import os
  11. import Tkinter
  12. import re
  13. from PyQt4 import QtCore
  14. ########################################
  15. ## Imports part of FlatCAM ##
  16. ########################################
  17. from FlatCAMWorker import Worker
  18. from ObjectCollection import *
  19. from FlatCAMObj import *
  20. from PlotCanvas import *
  21. from FlatCAMGUI import *
  22. from FlatCAMCommon import LoudDict
  23. from FlatCAMTool import *
  24. from FlatCAMShell import FCShell
  25. from FlatCAMDraw import FlatCAMDraw
  26. ########################################
  27. ## App ##
  28. ########################################
  29. class App(QtCore.QObject):
  30. """
  31. The main application class. The constructor starts the GUI.
  32. """
  33. ## Logging ##
  34. log = logging.getLogger('base')
  35. log.setLevel(logging.DEBUG)
  36. #log.setLevel(logging.WARNING)
  37. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  38. handler = logging.StreamHandler()
  39. handler.setFormatter(formatter)
  40. log.addHandler(handler)
  41. ## Version
  42. version = 8
  43. version_date = "2014/10"
  44. ## URL for update checks and statistics
  45. version_url = "http://flatcam.org/version"
  46. ## App URL
  47. app_url = "http://flatcam.org"
  48. ## Manual URL
  49. manual_url = "http://flatcam.org/manual/index.html"
  50. ## Signals
  51. inform = QtCore.pyqtSignal(str) # Message
  52. worker_task = QtCore.pyqtSignal(dict) # Worker task
  53. file_opened = QtCore.pyqtSignal(str, str) # File type and filename
  54. progress = QtCore.pyqtSignal(int) # Percentage of progress
  55. plots_updated = QtCore.pyqtSignal()
  56. object_created = QtCore.pyqtSignal(object)
  57. message = QtCore.pyqtSignal(str, str, str)
  58. def __init__(self):
  59. """
  60. Starts the application. Takes no parameters.
  61. :return: app
  62. :rtype: App
  63. """
  64. App.log.info("FlatCAM Starting...")
  65. self.path = os.path.dirname(sys.argv[0])
  66. #App.log.debug("Running in " + os.path.realpath(__file__))
  67. App.log.debug("Running in " + self.path)
  68. QtCore.QObject.__init__(self)
  69. self.ui = FlatCAMGUI(self.version)
  70. #### Plot Area ####
  71. # self.plotcanvas = PlotCanvas(self.ui.splitter)
  72. self.plotcanvas = PlotCanvas(self.ui.right_layout)
  73. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  74. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  75. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  76. self.ui.splitter.setStretchFactor(1, 2)
  77. ##############
  78. #### Data ####
  79. ##############
  80. self.recent = []
  81. self.clipboard = QtGui.QApplication.clipboard()
  82. self.project_filename = None
  83. self.last_folder = None
  84. self.toggle_units_ignore = False
  85. self.defaults_form = GlobalOptionsUI()
  86. self.defaults_form_fields = {
  87. "units": self.defaults_form.units_radio,
  88. "gerber_plot": self.defaults_form.gerber_group.plot_cb,
  89. "gerber_solid": self.defaults_form.gerber_group.solid_cb,
  90. "gerber_multicolored": self.defaults_form.gerber_group.multicolored_cb,
  91. "gerber_isotooldia": self.defaults_form.gerber_group.iso_tool_dia_entry,
  92. "gerber_isopasses": self.defaults_form.gerber_group.iso_width_entry,
  93. "gerber_isooverlap": self.defaults_form.gerber_group.iso_overlap_entry,
  94. "gerber_cutouttooldia": self.defaults_form.gerber_group.cutout_tooldia_entry,
  95. "gerber_cutoutmargin": self.defaults_form.gerber_group.cutout_margin_entry,
  96. "gerber_cutoutgapsize": self.defaults_form.gerber_group.cutout_gap_entry,
  97. "gerber_gaps": self.defaults_form.gerber_group.gaps_radio,
  98. "gerber_noncoppermargin": self.defaults_form.gerber_group.noncopper_margin_entry,
  99. "gerber_noncopperrounded": self.defaults_form.gerber_group.noncopper_rounded_cb,
  100. "gerber_bboxmargin": self.defaults_form.gerber_group.bbmargin_entry,
  101. "gerber_bboxrounded": self.defaults_form.gerber_group.bbrounded_cb,
  102. "excellon_plot": self.defaults_form.excellon_group.plot_cb,
  103. "excellon_solid": self.defaults_form.excellon_group.solid_cb,
  104. "excellon_drillz": self.defaults_form.excellon_group.cutz_entry,
  105. "excellon_travelz": self.defaults_form.excellon_group.travelz_entry,
  106. "excellon_feedrate": self.defaults_form.excellon_group.feedrate_entry,
  107. "geometry_plot": self.defaults_form.geometry_group.plot_cb,
  108. "geometry_cutz": self.defaults_form.geometry_group.cutz_entry,
  109. "geometry_travelz": self.defaults_form.geometry_group.travelz_entry,
  110. "geometry_feedrate": self.defaults_form.geometry_group.cncfeedrate_entry,
  111. "geometry_cnctooldia": self.defaults_form.geometry_group.cnctooldia_entry,
  112. "geometry_painttooldia": self.defaults_form.geometry_group.painttooldia_entry,
  113. "geometry_paintoverlap": self.defaults_form.geometry_group.paintoverlap_entry,
  114. "geometry_paintmargin": self.defaults_form.geometry_group.paintmargin_entry,
  115. "cncjob_plot": self.defaults_form.cncjob_group.plot_cb,
  116. "cncjob_tooldia": self.defaults_form.cncjob_group.tooldia_entry,
  117. "cncjob_append": self.defaults_form.cncjob_group.append_text
  118. }
  119. self.defaults = LoudDict()
  120. self.defaults.set_change_callback(lambda field: self.defaults_write_form_field(field)) # When the dictionary changes.
  121. self.defaults.update({
  122. "serial": 0,
  123. "stats": {},
  124. "units": "IN",
  125. "gerber_plot": True,
  126. "gerber_solid": True,
  127. "gerber_multicolored": False,
  128. "gerber_isotooldia": 0.016,
  129. "gerber_isopasses": 1,
  130. "gerber_isooverlap": 0.15,
  131. "gerber_cutouttooldia": 0.07,
  132. "gerber_cutoutmargin": 0.1,
  133. "gerber_cutoutgapsize": 0.15,
  134. "gerber_gaps": "4",
  135. "gerber_noncoppermargin": 0.0,
  136. "gerber_noncopperrounded": False,
  137. "gerber_bboxmargin": 0.0,
  138. "gerber_bboxrounded": False,
  139. "excellon_plot": True,
  140. "excellon_solid": False,
  141. "excellon_drillz": -0.1,
  142. "excellon_travelz": 0.1,
  143. "excellon_feedrate": 3.0,
  144. "geometry_plot": True,
  145. "geometry_cutz": -0.002,
  146. "geometry_travelz": 0.1,
  147. "geometry_feedrate": 3.0,
  148. "geometry_cnctooldia": 0.016,
  149. "geometry_painttooldia": 0.07,
  150. "geometry_paintoverlap": 0.15,
  151. "geometry_paintmargin": 0.0,
  152. "cncjob_plot": True,
  153. "cncjob_tooldia": 0.016,
  154. "cncjob_append": "",
  155. # Constants...
  156. "defaults_save_period_ms": 20000, # Time between default saves.
  157. "shell_shape": [500, 300], # Shape of the shell in pixels.
  158. "shell_at_startup": False, # Show the shell at startup.
  159. "recent_limit": 10, # Max. items in recent list.
  160. "fit_key": '1',
  161. "zoom_out_key": '2',
  162. "zoom_in_key": '3',
  163. "zoom_ratio": 1.5,
  164. "point_clipboard_format": "(%.4f, %.4f)",
  165. "zdownrate": None #
  166. })
  167. ###############################
  168. ### Load defaults from file ###
  169. self.load_defaults()
  170. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  171. if self.defaults['serial'] == 0 or len(str(self.defaults['serial'])) < 10:
  172. self.defaults['serial'] = ''.join([random.choice(chars) for i in range(20)])
  173. self.save_defaults()
  174. self.propagate_defaults()
  175. def auto_save_defaults():
  176. try:
  177. self.save_defaults()
  178. finally:
  179. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  180. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  181. self.options_form = GlobalOptionsUI()
  182. self.options_form_fields = {
  183. "units": self.options_form.units_radio,
  184. "gerber_plot": self.options_form.gerber_group.plot_cb,
  185. "gerber_solid": self.options_form.gerber_group.solid_cb,
  186. "gerber_multicolored": self.options_form.gerber_group.multicolored_cb,
  187. "gerber_isotooldia": self.options_form.gerber_group.iso_tool_dia_entry,
  188. "gerber_isopasses": self.options_form.gerber_group.iso_width_entry,
  189. "gerber_isooverlap": self.options_form.gerber_group.iso_overlap_entry,
  190. "gerber_cutouttooldia": self.options_form.gerber_group.cutout_tooldia_entry,
  191. "gerber_cutoutmargin": self.options_form.gerber_group.cutout_margin_entry,
  192. "gerber_cutoutgapsize": self.options_form.gerber_group.cutout_gap_entry,
  193. "gerber_gaps": self.options_form.gerber_group.gaps_radio,
  194. "gerber_noncoppermargin": self.options_form.gerber_group.noncopper_margin_entry,
  195. "gerber_noncopperrounded": self.options_form.gerber_group.noncopper_rounded_cb,
  196. "gerber_bboxmargin": self.options_form.gerber_group.bbmargin_entry,
  197. "gerber_bboxrounded": self.options_form.gerber_group.bbrounded_cb,
  198. "excellon_plot": self.options_form.excellon_group.plot_cb,
  199. "excellon_solid": self.options_form.excellon_group.solid_cb,
  200. "excellon_drillz": self.options_form.excellon_group.cutz_entry,
  201. "excellon_travelz": self.options_form.excellon_group.travelz_entry,
  202. "excellon_feedrate": self.options_form.excellon_group.feedrate_entry,
  203. "geometry_plot": self.options_form.geometry_group.plot_cb,
  204. "geometry_cutz": self.options_form.geometry_group.cutz_entry,
  205. "geometry_travelz": self.options_form.geometry_group.travelz_entry,
  206. "geometry_feedrate": self.options_form.geometry_group.cncfeedrate_entry,
  207. "geometry_cnctooldia": self.options_form.geometry_group.cnctooldia_entry,
  208. "geometry_painttooldia": self.options_form.geometry_group.painttooldia_entry,
  209. "geometry_paintoverlap": self.options_form.geometry_group.paintoverlap_entry,
  210. "geometry_paintmargin": self.options_form.geometry_group.paintmargin_entry,
  211. "cncjob_plot": self.options_form.cncjob_group.plot_cb,
  212. "cncjob_tooldia": self.options_form.cncjob_group.tooldia_entry,
  213. "cncjob_append": self.options_form.cncjob_group.append_text
  214. }
  215. self.options = LoudDict()
  216. self.options.set_change_callback(lambda field: self.options_write_form_field(field))
  217. self.options.update({
  218. "units": "IN",
  219. "gerber_plot": True,
  220. "gerber_solid": True,
  221. "gerber_multicolored": False,
  222. "gerber_isotooldia": 0.016,
  223. "gerber_isopasses": 1,
  224. "gerber_isooverlap": 0.15,
  225. "gerber_cutouttooldia": 0.07,
  226. "gerber_cutoutmargin": 0.1,
  227. "gerber_cutoutgapsize": 0.15,
  228. "gerber_gaps": "4",
  229. "gerber_noncoppermargin": 0.0,
  230. "gerber_noncopperrounded": False,
  231. "gerber_bboxmargin": 0.0,
  232. "gerber_bboxrounded": False,
  233. "excellon_plot": True,
  234. "excellon_solid": False,
  235. "excellon_drillz": -0.1,
  236. "excellon_travelz": 0.1,
  237. "excellon_feedrate": 3.0,
  238. "geometry_plot": True,
  239. "geometry_cutz": -0.002,
  240. "geometry_travelz": 0.1,
  241. "geometry_feedrate": 3.0,
  242. "geometry_cnctooldia": 0.016,
  243. "geometry_painttooldia": 0.07,
  244. "geometry_paintoverlap": 0.15,
  245. "geometry_paintmargin": 0.0,
  246. "cncjob_plot": True,
  247. "cncjob_tooldia": 0.016,
  248. "cncjob_append": ""
  249. })
  250. self.options.update(self.defaults) # Copy app defaults to project options
  251. #self.options_write_form()
  252. self.on_options_combo_change(0) # Will show the initial form
  253. self.collection = ObjectCollection()
  254. self.ui.project_tab_layout.addWidget(self.collection.view)
  255. #### End of Data ####
  256. #### Worker ####
  257. App.log.info("Starting Worker...")
  258. self.worker = Worker(self)
  259. self.thr1 = QtCore.QThread()
  260. self.worker.moveToThread(self.thr1)
  261. self.connect(self.thr1, QtCore.SIGNAL("started()"), self.worker.run)
  262. self.thr1.start()
  263. #### Check for updates ####
  264. # Separate thread (Not worker)
  265. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  266. self.worker2 = Worker(self, name="worker2")
  267. self.thr2 = QtCore.QThread()
  268. self.worker2.moveToThread(self.thr2)
  269. self.connect(self.thr2, QtCore.SIGNAL("started()"), self.worker2.run)
  270. self.connect(self.thr2, QtCore.SIGNAL("started()"),
  271. lambda: self.worker_task.emit({'fcn': self.version_check,
  272. 'params': [],
  273. 'worker_name': "worker2"}))
  274. self.thr2.start()
  275. ### Signal handling ###
  276. ## Custom signals
  277. self.inform.connect(self.info)
  278. self.message.connect(self.message_dialog)
  279. self.progress.connect(self.set_progress_bar)
  280. self.object_created.connect(self.on_object_created)
  281. self.plots_updated.connect(self.on_plots_updated)
  282. self.file_opened.connect(self.register_recent)
  283. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  284. ## Standard signals
  285. # Menu
  286. self.ui.menufilenew.triggered.connect(self.on_file_new)
  287. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  288. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  289. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  290. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  291. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  292. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  293. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  294. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  295. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  296. self.ui.menueditedit.triggered.connect(self.edit_geometry)
  297. self.ui.menueditok.triggered.connect(self.editor2geometry)
  298. self.ui.menueditjoin.triggered.connect(self.on_edit_join)
  299. self.ui.menueditdelete.triggered.connect(self.on_delete)
  300. self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  301. self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  302. self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  303. self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  304. self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  305. self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  306. self.ui.menuviewdisableall.triggered.connect(self.disable_plots)
  307. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(except_current=True))
  308. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  309. self.ui.menutoolshell.triggered.connect(lambda: self.shell.show())
  310. self.ui.menuhelp_about.triggered.connect(self.on_about)
  311. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  312. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  313. # Toolbar
  314. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  315. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  316. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1/1.5))
  317. self.ui.clear_plot_btn.triggered.connect(self.plotcanvas.clear)
  318. self.ui.replot_btn.triggered.connect(self.on_toolbar_replot)
  319. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  320. self.ui.editgeo_btn.triggered.connect(self.edit_geometry)
  321. self.ui.updategeo_btn.triggered.connect(self.editor2geometry)
  322. self.ui.delete_btn.triggered.connect(self.on_delete)
  323. self.ui.shell_btn.triggered.connect(lambda: self.shell.show())
  324. # Object list
  325. self.collection.view.activated.connect(self.on_row_activated)
  326. # Options
  327. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  328. self.options_form.units_radio.group_toggle_fn = self.on_toggle_units
  329. ####################
  330. ### Other setups ###
  331. ####################
  332. self.setup_obj_classes()
  333. self.setup_recent_items()
  334. self.setup_component_editor()
  335. #########################
  336. ### Tools and Plugins ###
  337. #########################
  338. self.dblsidedtool = DblSidedTool(self)
  339. self.dblsidedtool.install()
  340. self.measeurement_tool = Measurement(self)
  341. self.measeurement_tool.install()
  342. self.draw = FlatCAMDraw(self, disabled=True)
  343. #############
  344. ### Shell ###
  345. #############
  346. # TODO: Move this to its own class
  347. self.shell = FCShell(self)
  348. self.shell.setWindowIcon(self.ui.app_icon)
  349. self.shell.setWindowTitle("FlatCAM Shell")
  350. if self.defaults["shell_at_startup"]:
  351. self.shell.show()
  352. self.shell.resize(*self.defaults["shell_shape"])
  353. self.shell.append_output("FlatCAM %s\n(c) 2014 Juan Pablo Caram\n\n" % self.version)
  354. self.shell.append_output("Type help to get started.\n\n")
  355. self.tcl = Tkinter.Tcl()
  356. self.setup_shell()
  357. App.log.debug("END of constructor. Releasing control.")
  358. def defaults_read_form(self):
  359. for option in self.defaults_form_fields:
  360. self.defaults[option] = self.defaults_form_fields[option].get_value()
  361. def defaults_write_form(self):
  362. for option in self.defaults:
  363. self.defaults_write_form_field(option)
  364. # try:
  365. # self.defaults_form_fields[option].set_value(self.defaults[option])
  366. # except KeyError:
  367. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  368. # # TODO: Rethink this?
  369. # pass
  370. def defaults_write_form_field(self, field):
  371. try:
  372. self.defaults_form_fields[field].set_value(self.defaults[field])
  373. except KeyError:
  374. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  375. # TODO: Rethink this?
  376. pass
  377. def disable_plots(self, except_current=False):
  378. """
  379. Disables all plots with exception of the current object if specified.
  380. :param except_current: Wether to skip the current object.
  381. :rtype except_current: boolean
  382. :return: None
  383. """
  384. # TODO: This method is very similar to replot_all. Try to merge.
  385. self.progress.emit(10)
  386. def worker_task(app_obj):
  387. percentage = 0.1
  388. try:
  389. delta = 0.9 / len(self.collection.get_list())
  390. except ZeroDivisionError:
  391. self.progress.emit(0)
  392. return
  393. for obj in self.collection.get_list():
  394. if obj != self.collection.get_active() or not except_current:
  395. obj.options['plot'] = False
  396. obj.plot()
  397. percentage += delta
  398. self.progress.emit(int(percentage*100))
  399. self.progress.emit(0)
  400. self.plots_updated.emit()
  401. # Send to worker
  402. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  403. def edit_geometry(self):
  404. """
  405. Send the current geometry object (if any) into the editor.
  406. :return: None
  407. """
  408. if not isinstance(self.collection.get_active(), FlatCAMGeometry):
  409. self.info("Select a Geometry Object to edit.")
  410. return
  411. self.draw.edit_fcgeometry(self.collection.get_active())
  412. def editor2geometry(self):
  413. """
  414. Transfers the geometry in the editor to the current geometry object.
  415. :return: None
  416. """
  417. geo = self.collection.get_active()
  418. if not isinstance(geo, FlatCAMGeometry):
  419. self.info("Select a Geometry Object to update.")
  420. return
  421. self.draw.update_fcgeometry(geo)
  422. self.draw.clear()
  423. self.draw.drawing_toolbar.setDisabled(True)
  424. geo.plot()
  425. def report_usage(self, resource):
  426. """
  427. Increments usage counter for the given resource
  428. in self.defaults['stats'].
  429. :param resource: Name of the resource.
  430. :return: None
  431. """
  432. if resource in self.defaults['stats']:
  433. self.defaults['stats'][resource] += 1
  434. else:
  435. self.defaults['stats'][resource] = 1
  436. def exec_command(self, text):
  437. """
  438. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  439. :param text: Input command
  440. :return: None
  441. """
  442. self.report_usage('exec_command')
  443. text = str(text)
  444. try:
  445. result = self.tcl.eval(str(text))
  446. self.shell.append_output(result + '\n')
  447. except Tkinter.TclError, e:
  448. self.shell.append_error('ERROR: ' + str(e) + '\n')
  449. raise
  450. return
  451. """
  452. Code below is unsused. Saved for later.
  453. """
  454. parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  455. parts = [p.replace('\n', '').replace('"', '') for p in parts]
  456. self.log.debug(parts)
  457. try:
  458. if parts[0] not in commands:
  459. self.shell.append_error("Unknown command\n")
  460. return
  461. #import inspect
  462. #inspect.getargspec(someMethod)
  463. if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  464. (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  465. self.shell.append_error(
  466. "Command %s takes %d arguments. %d given.\n" %
  467. (parts[0], commands[parts[0]]["params"], len(parts)-1)
  468. )
  469. return
  470. cmdfcn = commands[parts[0]]["fcn"]
  471. cmdconv = commands[parts[0]]["converters"]
  472. if len(parts)-1 > 0:
  473. retval = cmdfcn(*[cmdconv[i](parts[i+1]) for i in range(len(parts)-1)])
  474. else:
  475. retval = cmdfcn()
  476. retfcn = commands[parts[0]]["retfcn"]
  477. if retval and retfcn(retval):
  478. self.shell.append_output(retfcn(retval) + "\n")
  479. except:
  480. self.shell.append_error(''.join(traceback.format_exc()))
  481. #self.shell.append_error("?\n")
  482. def info(self, msg):
  483. """
  484. Writes on the status bar.
  485. :param msg: Text to write.
  486. :return: None
  487. """
  488. match = re.search("\[([^\]]+)\](.*)", msg)
  489. if match:
  490. self.ui.fcinfo.set_status(QtCore.QString(match.group(2)), level=match.group(1))
  491. else:
  492. self.ui.fcinfo.set_status(QtCore.QString(msg), level="info")
  493. def load_defaults(self):
  494. """
  495. Loads the aplication's default settings from defaults.json into
  496. ``self.defaults``.
  497. :return: None
  498. """
  499. try:
  500. f = open(self.path + "/defaults.json")
  501. options = f.read()
  502. f.close()
  503. except IOError:
  504. self.log.error("Could not load defaults file.")
  505. self.inform.emit("ERROR: Could not load defaults file.")
  506. return
  507. try:
  508. defaults = json.loads(options)
  509. except:
  510. e = sys.exc_info()[0]
  511. App.log.error(str(e))
  512. self.inform.emit("ERROR: Failed to parse defaults file.")
  513. return
  514. self.defaults.update(defaults)
  515. def message_dialog(self, title, message, kind="info"):
  516. icon = {"info": QtGui.QMessageBox.Information,
  517. "warning": QtGui.QMessageBox.Warning,
  518. "error": QtGui.QMessageBox.Critical}[str(kind)]
  519. dlg = QtGui.QMessageBox(icon, title, message, parent=self.ui)
  520. dlg.setText(message)
  521. dlg.exec_()
  522. def register_recent(self, kind, filename):
  523. self.log.debug("register_recent()")
  524. self.log.debug(" %s" % kind)
  525. self.log.debug(" %s" % filename)
  526. record = {'kind': str(kind), 'filename': str(filename)}
  527. if record in self.recent:
  528. return
  529. self.recent.insert(0, record)
  530. if len(self.recent) > self.defaults['recent_limit']: # Limit reached
  531. self.recent.pop()
  532. try:
  533. f = open('recent.json', 'w')
  534. except IOError:
  535. App.log.error("Failed to open recent items file for writing.")
  536. self.inform.emit('Failed to open recent files file for writing.')
  537. return
  538. #try:
  539. json.dump(self.recent, f)
  540. # except:
  541. # App.log.error("Failed to write to recent items file.")
  542. # self.inform.emit('ERROR: Failed to write to recent items file.')
  543. # f.close()
  544. f.close()
  545. # Re-buid the recent items menu
  546. self.setup_recent_items()
  547. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True):
  548. """
  549. Creates a new specalized FlatCAMObj and attaches it to the application,
  550. this is, updates the GUI accordingly, any other records and plots it.
  551. This method is thread-safe.
  552. :param kind: The kind of object to create. One of 'gerber',
  553. 'excellon', 'cncjob' and 'geometry'.
  554. :type kind: str
  555. :param name: Name for the object.
  556. :type name: str
  557. :param initialize: Function to run after creation of the object
  558. but before it is attached to the application. The function is
  559. called with 2 parameters: the new object and the App instance.
  560. :type initialize: function
  561. :return: None
  562. :rtype: None
  563. """
  564. App.log.debug("new_object()")
  565. ### Check for existing name
  566. while name in self.collection.get_names():
  567. ## Create a new name
  568. # Ends with number?
  569. App.log.debug("new_object(): Object name (%s) exists, changing." % name)
  570. match = re.search(r'(.*[^\d])?(\d+)$', name)
  571. if match: # Yes: Increment the number!
  572. base = match.group(1) or ''
  573. num = int(match.group(2))
  574. name = base + str(num + 1)
  575. else: # No: add a number!
  576. name += "_1"
  577. # Create object
  578. classdict = {
  579. "gerber": FlatCAMGerber,
  580. "excellon": FlatCAMExcellon,
  581. "cncjob": FlatCAMCNCjob,
  582. "geometry": FlatCAMGeometry
  583. }
  584. App.log.debug("Calling object constructor...")
  585. obj = classdict[kind](name)
  586. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  587. # Set default options from self.options
  588. for option in self.options:
  589. if option.find(kind + "_") == 0:
  590. oname = option[len(kind)+1:]
  591. obj.options[oname] = self.options[option]
  592. # Initialize as per user request
  593. # User must take care to implement initialize
  594. # in a thread-safe way as is is likely that we
  595. # have been invoked in a separate thread.
  596. initialize(obj, self)
  597. # Check units and convert if necessary
  598. if self.options["units"].upper() != obj.units.upper():
  599. self.inform.emit("Converting units to " + self.options["units"] + ".")
  600. obj.convert_units(self.options["units"])
  601. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  602. # Move the object to the main thread and let the app know that it is available.
  603. obj.moveToThread(QtGui.QApplication.instance().thread())
  604. self.object_created.emit(obj)
  605. return obj
  606. def options_read_form(self):
  607. for option in self.options_form_fields:
  608. self.options[option] = self.options_form_fields[option].get_value()
  609. def options_write_form(self):
  610. for option in self.options:
  611. self.options_write_form_field(option)
  612. def options_write_form_field(self, field):
  613. try:
  614. self.options_form_fields[field].set_value(self.options[field])
  615. except KeyError:
  616. # Changed from error to debug. This allows to have data stored
  617. # which is not user-editable.
  618. self.log.debug("options_write_form_field(): No field for: %s" % field)
  619. def on_about(self):
  620. """
  621. Displays the "about" dialog.
  622. :return: None
  623. """
  624. self.report_usage("on_about")
  625. version = self.version
  626. version_date = self.version_date
  627. class AboutDialog(QtGui.QDialog):
  628. def __init__(self, parent=None):
  629. QtGui.QDialog.__init__(self, parent)
  630. self.setWindowIcon(parent.app_icon)
  631. layout1 = QtGui.QVBoxLayout()
  632. self.setLayout(layout1)
  633. layout2 = QtGui.QHBoxLayout()
  634. layout1.addLayout(layout2)
  635. logo = QtGui.QLabel()
  636. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  637. layout2.addWidget(logo, stretch=0)
  638. title = QtGui.QLabel(
  639. "<font size=8><B>FlatCAM</B></font><BR>"
  640. "Version %s (%s)<BR>"
  641. "<BR>"
  642. "2D Post-processing for Manufacturing specialized in<BR>"
  643. "Printed Circuit Boards<BR>"
  644. "<BR>"
  645. "(c) 2014 Juan Pablo Caram" % (version, version_date)
  646. )
  647. layout2.addWidget(title, stretch=1)
  648. layout3 = QtGui.QHBoxLayout()
  649. layout1.addLayout(layout3)
  650. layout3.addStretch()
  651. okbtn = QtGui.QPushButton("Close")
  652. layout3.addWidget(okbtn)
  653. okbtn.clicked.connect(self.accept)
  654. AboutDialog(self.ui).exec_()
  655. def on_file_savedefaults(self):
  656. """
  657. Callback for menu item File->Save Defaults. Saves application default options
  658. ``self.defaults`` to defaults.json.
  659. :return: None
  660. """
  661. self.save_defaults()
  662. def save_defaults(self):
  663. """
  664. Saves application default options
  665. ``self.defaults`` to defaults.json.
  666. :return: None
  667. """
  668. self.report_usage("save_defaults")
  669. ## Read options from file ##
  670. try:
  671. f = open(self.path + "/defaults.json")
  672. options = f.read()
  673. f.close()
  674. except:
  675. e = sys.exc_info()[0]
  676. App.log.error("Could not load defaults file.")
  677. App.log.error(str(e))
  678. self.inform.emit("[error] Could not load defaults file.")
  679. return
  680. try:
  681. defaults = json.loads(options)
  682. except:
  683. e = sys.exc_info()[0]
  684. App.log.error("Failed to parse defaults file.")
  685. App.log.error(str(e))
  686. self.inform.emit("[error] Failed to parse defaults file.")
  687. return
  688. # Update options
  689. self.defaults_read_form()
  690. defaults.update(self.defaults)
  691. # Save update options
  692. try:
  693. f = open("defaults.json", "w")
  694. json.dump(defaults, f)
  695. f.close()
  696. except:
  697. self.inform.emit("[error] Failed to write defaults to file.")
  698. return
  699. self.inform.emit("Defaults saved.")
  700. def on_edit_join(self):
  701. """
  702. Callback for Edit->Join. Joins the selected geometry objects into
  703. a new one.
  704. :return: None
  705. """
  706. objs = self.collection.get_selected()
  707. def initialize(obj, app):
  708. FlatCAMGeometry.merge(objs, obj)
  709. self.new_object("geometry", "Combo", initialize)
  710. def on_options_app2project(self):
  711. """
  712. Callback for Options->Transfer Options->App=>Project. Copies options
  713. from application defaults to project defaults.
  714. :return: None
  715. """
  716. self.report_usage("on_options_app2project")
  717. self.defaults_read_form()
  718. self.options.update(self.defaults)
  719. self.options_write_form()
  720. def on_options_project2app(self):
  721. """
  722. Callback for Options->Transfer Options->Project=>App. Copies options
  723. from project defaults to application defaults.
  724. :return: None
  725. """
  726. self.report_usage("on_options_project2app")
  727. self.options_read_form()
  728. self.defaults.update(self.options)
  729. self.defaults_write_form()
  730. def on_options_project2object(self):
  731. """
  732. Callback for Options->Transfer Options->Project=>Object. Copies options
  733. from project defaults to the currently selected object.
  734. :return: None
  735. """
  736. self.report_usage("on_options_project2object")
  737. self.options_read_form()
  738. obj = self.collection.get_active()
  739. if obj is None:
  740. self.inform.emit("WARNING: No object selected.")
  741. return
  742. for option in self.options:
  743. if option.find(obj.kind + "_") == 0:
  744. oname = option[len(obj.kind)+1:]
  745. obj.options[oname] = self.options[option]
  746. obj.to_form() # Update UI
  747. def on_options_object2project(self):
  748. """
  749. Callback for Options->Transfer Options->Object=>Project. Copies options
  750. from the currently selected object to project defaults.
  751. :return: None
  752. """
  753. self.report_usage("on_options_object2project")
  754. obj = self.collection.get_active()
  755. if obj is None:
  756. self.inform.emit("WARNING: No object selected.")
  757. return
  758. obj.read_form()
  759. for option in obj.options:
  760. if option in ['name']: # TODO: Handle this better...
  761. continue
  762. self.options[obj.kind + "_" + option] = obj.options[option]
  763. self.options_write_form()
  764. def on_options_object2app(self):
  765. """
  766. Callback for Options->Transfer Options->Object=>App. Copies options
  767. from the currently selected object to application defaults.
  768. :return: None
  769. """
  770. self.report_usage("on_options_object2app")
  771. obj = self.collection.get_active()
  772. if obj is None:
  773. self.inform.emit("WARNING: No object selected.")
  774. return
  775. obj.read_form()
  776. for option in obj.options:
  777. if option in ['name']: # TODO: Handle this better...
  778. continue
  779. self.defaults[obj.kind + "_" + option] = obj.options[option]
  780. self.defaults_write_form()
  781. def on_options_app2object(self):
  782. """
  783. Callback for Options->Transfer Options->App=>Object. Copies options
  784. from application defaults to the currently selected object.
  785. :return: None
  786. """
  787. self.report_usage("on_options_app2object")
  788. self.defaults_read_form()
  789. obj = self.collection.get_active()
  790. if obj is None:
  791. self.inform.emit("WARNING: No object selected.")
  792. return
  793. for option in self.defaults:
  794. if option.find(obj.kind + "_") == 0:
  795. oname = option[len(obj.kind)+1:]
  796. obj.options[oname] = self.defaults[option]
  797. obj.to_form() # Update UI
  798. def on_toggle_units(self):
  799. """
  800. Callback for the Units radio-button change in the Options tab.
  801. Changes the application's default units or the current project's units.
  802. If changing the project's units, the change propagates to all of
  803. the objects in the project.
  804. :return: None
  805. """
  806. self.report_usage("on_toggle_units")
  807. if self.toggle_units_ignore:
  808. return
  809. # If option is the same, then ignore
  810. if self.options_form.units_radio.get_value().upper() == self.options['units'].upper():
  811. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  812. return
  813. # Options to scale
  814. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  815. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  816. 'excellon_travelz', 'excellon_feedrate', 'cncjob_tooldia',
  817. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  818. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  819. 'geometry_paintmargin']
  820. def scale_options(sfactor):
  821. for dim in dimensions:
  822. self.options[dim] *= sfactor
  823. # The scaling factor depending on choice of units.
  824. factor = 1/25.4
  825. if self.options_form.units_radio.get_value().upper() == 'MM':
  826. factor = 25.4
  827. # Changing project units. Warn user.
  828. msgbox = QtGui.QMessageBox()
  829. msgbox.setText("<B>Change project units ...</B>")
  830. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  831. "properties of all objects to be scaled accordingly. Continue?")
  832. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  833. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  834. response = msgbox.exec_()
  835. if response == QtGui.QMessageBox.Ok:
  836. self.options_read_form()
  837. scale_options(factor)
  838. self.options_write_form()
  839. for obj in self.collection.get_list():
  840. units = self.options_form.units_radio.get_value().upper()
  841. obj.convert_units(units)
  842. current = self.collection.get_active()
  843. if current is not None:
  844. current.to_form()
  845. self.plot_all()
  846. else:
  847. # Undo toggling
  848. self.toggle_units_ignore = True
  849. if self.options_form.units_radio.get_value().upper() == 'MM':
  850. self.options_form.units_radio.set_value('IN')
  851. else:
  852. self.options_form.units_radio.set_value('MM')
  853. self.toggle_units_ignore = False
  854. self.options_read_form()
  855. self.inform.emit("Converted units to %s" % self.options["units"])
  856. self.ui.units_label.setText("[" + self.options["units"] + "]")
  857. def on_options_combo_change(self, sel):
  858. """
  859. Called when the combo box to choose between application defaults and
  860. project option changes value. The corresponding variables are
  861. copied to the UI.
  862. :param sel: The option index that was chosen.
  863. :return: None
  864. """
  865. # combo_sel = self.ui.notebook.combo_options.get_active()
  866. App.log.debug("Options --> %s" % sel)
  867. # Remove anything else in the box
  868. # box_children = self.options_box.get_children()
  869. # box_children = self.ui.notebook.options_contents.get_children()
  870. # for child in box_children:
  871. # self.ui.notebook.options_contents.remove(child)
  872. # try:
  873. # self.ui.options_area.removeWidget(self.defaults_form)
  874. # except:
  875. # pass
  876. #
  877. # try:
  878. # self.ui.options_area.removeWidget(self.options_form)
  879. # except:
  880. # pass
  881. form = [self.defaults_form, self.options_form][sel]
  882. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  883. try:
  884. self.ui.options_scroll_area.takeWidget()
  885. except:
  886. self.log.debug("Nothing to remove")
  887. self.ui.options_scroll_area.setWidget(form)
  888. form.show()
  889. # self.options2form()
  890. def on_delete(self):
  891. """
  892. Delete the currently selected FlatCAMObj.
  893. :return: None
  894. """
  895. self.report_usage("on_delete")
  896. # Keep this for later
  897. try:
  898. name = copy(self.collection.get_active().options["name"])
  899. except AttributeError:
  900. self.log.debug("Nothing selected for deletion")
  901. return
  902. # Remove plot
  903. self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  904. self.plotcanvas.auto_adjust_axes()
  905. # Clear form
  906. self.setup_component_editor()
  907. # Remove from dictionary
  908. self.collection.delete_active()
  909. self.inform.emit("Object deleted: %s" % name)
  910. def on_plots_updated(self):
  911. """
  912. Callback used to report when the plots have changed.
  913. Adjust axes and zooms to fit.
  914. :return: None
  915. """
  916. self.plotcanvas.auto_adjust_axes()
  917. self.on_zoom_fit(None)
  918. def on_toolbar_replot(self):
  919. """
  920. Callback for toolbar button. Re-plots all objects.
  921. :return: None
  922. """
  923. self.report_usage("on_toolbar_replot")
  924. self.log.debug("on_toolbar_replot()")
  925. try:
  926. self.collection.get_active().read_form()
  927. except AttributeError:
  928. self.log.debug("on_toolbar_replot(): AttributeError")
  929. pass
  930. self.plot_all()
  931. def on_row_activated(self, index):
  932. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  933. def on_object_created(self, obj):
  934. """
  935. Event callback for object creation.
  936. :param obj: The newly created FlatCAM object.
  937. :return: None
  938. """
  939. self.log.debug("on_object_created()")
  940. self.inform.emit("Object (%s) created: %s" % (obj.kind, obj.options['name']))
  941. self.collection.append(obj)
  942. obj.plot()
  943. self.on_zoom_fit(None)
  944. def on_zoom_fit(self, event):
  945. """
  946. Callback for zoom-out request. This can be either from the corresponding
  947. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  948. with axes limits from the geometry bounds of all objects.
  949. :param event: Ignored.
  950. :return: None
  951. """
  952. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  953. width = xmax - xmin
  954. height = ymax - ymin
  955. xmin -= 0.05 * width
  956. xmax += 0.05 * width
  957. ymin -= 0.05 * height
  958. ymax += 0.05 * height
  959. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  960. def on_key_over_plot(self, event):
  961. """
  962. Callback for the key pressed event when the canvas is focused. Keyboard
  963. shortcuts are handled here. So far, these are the shortcuts:
  964. ========== ============================================
  965. Key Action
  966. ========== ============================================
  967. '1' Zoom-fit. Fits the axes limits to the data.
  968. '2' Zoom-out.
  969. '3' Zoom-in.
  970. 'm' Toggle on-off the measuring tool.
  971. ========== ============================================
  972. :param event: Ignored.
  973. :return: None
  974. """
  975. if event.key == self.defaults['fit_key']: # 1
  976. self.on_zoom_fit(None)
  977. return
  978. if event.key == self.defaults['zoom_out_key']: # 2
  979. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  980. return
  981. if event.key == self.defaults['zoom_in_key']: # 3
  982. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  983. return
  984. # if event.key == 'm':
  985. # if self.measure.toggle_active():
  986. # self.inform.emit("Measuring tool ON")
  987. # else:
  988. # self.inform.emit("Measuring tool OFF")
  989. # return
  990. def on_click_over_plot(self, event):
  991. """
  992. Callback for the mouse click event over the plot. This event is generated
  993. by the Matplotlib backend and has been registered in ``self.__init__()``.
  994. For details, see: http://matplotlib.org/users/event_handling.html
  995. Default actions are:
  996. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  997. :param event: Contains information about the event, like which button
  998. was clicked, the pixel coordinates and the axes coordinates.
  999. :return: None
  1000. """
  1001. # So it can receive key presses
  1002. self.plotcanvas.canvas.setFocus()
  1003. try:
  1004. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  1005. event.button, event.x, event.y, event.xdata, event.ydata))
  1006. self.clipboard.setText(self.defaults["point_clipboard_format"] % (event.xdata, event.ydata))
  1007. except Exception, e:
  1008. App.log.debug("Outside plot?")
  1009. App.log.debug(str(e))
  1010. def on_mouse_move_over_plot(self, event):
  1011. """
  1012. Callback for the mouse motion event over the plot. This event is generated
  1013. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1014. For details, see: http://matplotlib.org/users/event_handling.html
  1015. :param event: Contains information about the event.
  1016. :return: None
  1017. """
  1018. try: # May fail in case mouse not within axes
  1019. self.ui.position_label.setText("X: %.4f Y: %.4f" % (
  1020. event.xdata, event.ydata))
  1021. self.mouse = [event.xdata, event.ydata]
  1022. except:
  1023. self.ui.position_label.setText("")
  1024. self.mouse = None
  1025. def on_file_new(self):
  1026. """
  1027. Callback for menu item File->New. Returns the application to its
  1028. startup state. This method is thread-safe.
  1029. :return: None
  1030. """
  1031. self.report_usage("on_file_new")
  1032. # Remove everything from memory
  1033. App.log.debug("on_file_new()")
  1034. self.plotcanvas.clear()
  1035. self.collection.delete_all()
  1036. self.setup_component_editor()
  1037. # Clear project filename
  1038. self.project_filename = None
  1039. # Re-fresh project options
  1040. self.on_options_app2project()
  1041. def on_fileopengerber(self):
  1042. """
  1043. File menu callback for opening a Gerber.
  1044. :return: None
  1045. """
  1046. self.report_usage("on_fileopengerber")
  1047. App.log.debug("on_fileopengerber()")
  1048. try:
  1049. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber",
  1050. directory=self.last_folder)
  1051. except TypeError:
  1052. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber")
  1053. # The Qt methods above will return a QString which can cause problems later.
  1054. # So far json.dump() will fail to serialize it.
  1055. # TODO: Improve the serialization methods and remove this fix.
  1056. filename = str(filename)
  1057. if str(filename) == "":
  1058. self.inform.emit("Open cancelled.")
  1059. else:
  1060. self.worker_task.emit({'fcn': self.open_gerber,
  1061. 'params': [filename]})
  1062. def on_fileopenexcellon(self):
  1063. """
  1064. File menu callback for opening an Excellon file.
  1065. :return: None
  1066. """
  1067. self.report_usage("on_fileopenexcellon")
  1068. App.log.debug("on_fileopenexcellon()")
  1069. try:
  1070. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon",
  1071. directory=self.last_folder)
  1072. except TypeError:
  1073. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon")
  1074. # The Qt methods above will return a QString which can cause problems later.
  1075. # So far json.dump() will fail to serialize it.
  1076. # TODO: Improve the serialization methods and remove this fix.
  1077. filename = str(filename)
  1078. if str(filename) == "":
  1079. self.inform.emit("Open cancelled.")
  1080. else:
  1081. self.worker_task.emit({'fcn': self.open_excellon,
  1082. 'params': [filename]})
  1083. def on_fileopengcode(self):
  1084. """
  1085. File menu call back for opening gcode.
  1086. :return: None
  1087. """
  1088. self.report_usage("on_fileopengcode")
  1089. App.log.debug("on_fileopengcode()")
  1090. try:
  1091. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code",
  1092. directory=self.last_folder)
  1093. except TypeError:
  1094. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code")
  1095. # The Qt methods above will return a QString which can cause problems later.
  1096. # So far json.dump() will fail to serialize it.
  1097. # TODO: Improve the serialization methods and remove this fix.
  1098. filename = str(filename)
  1099. if str(filename) == "":
  1100. self.inform.emit("Open cancelled.")
  1101. else:
  1102. self.worker_task.emit({'fcn': self.open_gcode,
  1103. 'params': [filename]})
  1104. def on_file_openproject(self):
  1105. """
  1106. File menu callback for opening a project.
  1107. :return: None
  1108. """
  1109. self.report_usage("on_file_openproject")
  1110. App.log.debug("on_file_openproject()")
  1111. try:
  1112. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project",
  1113. directory=self.last_folder)
  1114. except TypeError:
  1115. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project")
  1116. # The Qt methods above will return a QString which can cause problems later.
  1117. # So far json.dump() will fail to serialize it.
  1118. # TODO: Improve the serialization methods and remove this fix.
  1119. filename = str(filename)
  1120. if str(filename) == "":
  1121. self.inform.emit("Open cancelled.")
  1122. else:
  1123. # self.worker_task.emit({'fcn': self.open_project,
  1124. # 'params': [filename]})
  1125. # The above was failing because open_project() is not
  1126. # thread safe. The new_project()
  1127. self.open_project(filename)
  1128. def on_file_saveproject(self):
  1129. """
  1130. Callback for menu item File->Save Project. Saves the project to
  1131. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1132. if set to None. The project is saved by calling ``self.save_project()``.
  1133. :return: None
  1134. """
  1135. self.report_usage("on_file_saveproject")
  1136. if self.project_filename is None:
  1137. self.on_file_saveprojectas()
  1138. else:
  1139. self.save_project(self.project_filename)
  1140. self.file_opened.emit("project", self.project_filename)
  1141. self.inform.emit("Project saved to: " + self.project_filename)
  1142. def on_file_saveprojectas(self, make_copy=False):
  1143. """
  1144. Callback for menu item File->Save Project As... Opens a file
  1145. chooser and saves the project to the given file via
  1146. ``self.save_project()``.
  1147. :return: None
  1148. """
  1149. self.report_usage("on_file_saveprojectas")
  1150. try:
  1151. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...",
  1152. directory=self.last_folder)
  1153. except TypeError:
  1154. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...")
  1155. try:
  1156. f = open(filename, 'r')
  1157. f.close()
  1158. exists = True
  1159. except IOError:
  1160. exists = False
  1161. msg = "File exists. Overwrite?"
  1162. if exists:
  1163. msgbox = QtGui.QMessageBox()
  1164. msgbox.setInformativeText(msg)
  1165. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1166. msgbox.setDefaultButton(QtGui.QMessageBox.Cancel)
  1167. result = msgbox.exec_()
  1168. if result == QtGui.QMessageBox.Cancel:
  1169. return
  1170. self.save_project(filename)
  1171. self.file_opened.emit("project", filename)
  1172. if not make_copy:
  1173. self.project_filename = filename
  1174. self.inform.emit("Project saved to: " + self.project_filename)
  1175. else:
  1176. self.inform.emit("Project copy saved to: " + self.project_filename)
  1177. def open_gerber(self, filename, follow=False, outname=None):
  1178. """
  1179. Opens a Gerber file, parses it and creates a new object for
  1180. it in the program. Thread-safe.
  1181. :param filename: Gerber file filename
  1182. :type filename: str
  1183. :param follow: If true, the parser will not create polygons, just lines
  1184. following the gerber path.
  1185. :type follow: bool
  1186. :return: None
  1187. """
  1188. App.log.debug("open_gerber()")
  1189. self.progress.emit(10)
  1190. # How the object should be initialized
  1191. def obj_init(gerber_obj, app_obj):
  1192. assert isinstance(gerber_obj, FlatCAMGerber)
  1193. # Opening the file happens here
  1194. self.progress.emit(30)
  1195. try:
  1196. gerber_obj.parse_file(filename, follow=follow)
  1197. except IOError:
  1198. app_obj.inform.emit("[error] Failed to open file: " + filename)
  1199. app_obj.progress.emit(0)
  1200. # Further parsing
  1201. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  1202. # Object name
  1203. name = outname or filename.split('/')[-1].split('\\')[-1]
  1204. self.new_object("gerber", name, obj_init)
  1205. # New object creation and file processing
  1206. # try:
  1207. # self.new_object("gerber", name, obj_init)
  1208. # except:
  1209. # e = sys.exc_info()
  1210. # print "ERROR:", e[0]
  1211. # traceback.print_exc()
  1212. # self.message_dialog("Failed to create Gerber Object",
  1213. # "Attempting to create a FlatCAM Gerber Object from " +
  1214. # "Gerber file failed during processing:\n" +
  1215. # str(e[0]) + " " + str(e[1]), kind="error")
  1216. # GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "Idle"))
  1217. # self.collection.delete_active()
  1218. # return
  1219. # Register recent file
  1220. self.file_opened.emit("gerber", filename)
  1221. self.progress.emit(100)
  1222. # GUI feedback
  1223. self.inform.emit("Opened: " + filename)
  1224. def open_excellon(self, filename, outname=None):
  1225. """
  1226. Opens an Excellon file, parses it and creates a new object for
  1227. it in the program. Thread-safe.
  1228. :param filename: Excellon file filename
  1229. :type filename: str
  1230. :return: None
  1231. """
  1232. App.log.debug("open_excellon()")
  1233. self.progress.emit(10)
  1234. # How the object should be initialized
  1235. def obj_init(excellon_obj, app_obj):
  1236. self.progress.emit(20)
  1237. try:
  1238. excellon_obj.parse_file(filename)
  1239. except IOError:
  1240. app_obj.inform.emit("[error] Cannot open file: " + filename)
  1241. self.progress.emit(0) # TODO: self and app_bjj mixed
  1242. raise IOError
  1243. excellon_obj.create_geometry()
  1244. self.progress.emit(70)
  1245. # Object name
  1246. name = outname or filename.split('/')[-1].split('\\')[-1]
  1247. self.new_object("excellon", name, obj_init)
  1248. # New object creation and file processing
  1249. # try:
  1250. # self.new_object("excellon", name, obj_init)
  1251. # except:
  1252. # e = sys.exc_info()
  1253. # App.log.error(str(e))
  1254. # self.message_dialog("Failed to create Excellon Object",
  1255. # "Attempting to create a FlatCAM Excellon Object from " +
  1256. # "Excellon file failed during processing:\n" +
  1257. # str(e[0]) + " " + str(e[1]), kind="error")
  1258. # self.progress.emit(0)
  1259. # self.collection.delete_active()
  1260. # return
  1261. # Register recent file
  1262. self.file_opened.emit("excellon", filename)
  1263. # GUI feedback
  1264. self.inform.emit("Opened: " + filename)
  1265. self.progress.emit(100)
  1266. def open_gcode(self, filename, outname=None):
  1267. """
  1268. Opens a G-gcode file, parses it and creates a new object for
  1269. it in the program. Thread-safe.
  1270. :param filename: G-code file filename
  1271. :type filename: str
  1272. :return: None
  1273. """
  1274. App.log.debug("open_gcode()")
  1275. # How the object should be initialized
  1276. def obj_init(job_obj, app_obj_):
  1277. """
  1278. :type app_obj_: App
  1279. """
  1280. assert isinstance(app_obj_, App)
  1281. self.progress.emit(10)
  1282. f = open(filename)
  1283. gcode = f.read()
  1284. f.close()
  1285. job_obj.gcode = gcode
  1286. self.progress.emit(20)
  1287. job_obj.gcode_parse()
  1288. self.progress.emit(60)
  1289. job_obj.create_geometry()
  1290. # Object name
  1291. name = outname or filename.split('/')[-1].split('\\')[-1]
  1292. # New object creation and file processing
  1293. try:
  1294. self.new_object("cncjob", name, obj_init)
  1295. except:
  1296. e = sys.exc_info()
  1297. App.log.error(str(e))
  1298. self.message_dialog("Failed to create CNCJob Object",
  1299. "Attempting to create a FlatCAM CNCJob Object from " +
  1300. "G-Code file failed during processing:\n" +
  1301. str(e[0]) + " " + str(e[1]), kind="error")
  1302. self.progress.emit(0)
  1303. self.collection.delete_active()
  1304. return
  1305. # Register recent file
  1306. self.file_opened.emit("cncjob", filename)
  1307. # GUI feedback
  1308. self.inform.emit("Opened: " + filename)
  1309. self.progress.emit(100)
  1310. def open_project(self, filename):
  1311. """
  1312. Loads a project from the specified file.
  1313. 1) Loads and parses file
  1314. 2) Registers the file as recently opened.
  1315. 3) Calls on_file_new()
  1316. 4) Updates options
  1317. 5) Calls new_object() with the object's from_dict() as init method.
  1318. 6) Calls plot_all()
  1319. :param filename: Name of the file from which to load.
  1320. :type filename: str
  1321. :return: None
  1322. """
  1323. App.log.debug("Opening project: " + filename)
  1324. ## Open and parse
  1325. try:
  1326. f = open(filename, 'r')
  1327. except IOError:
  1328. App.log.error("Failed to open project file: %s" % filename)
  1329. self.inform.emit("[error] Failed to open project file: %s" % filename)
  1330. return
  1331. try:
  1332. d = json.load(f, object_hook=dict2obj)
  1333. except:
  1334. App.log.error("Failed to parse project file: %s" % filename)
  1335. self.inform.emit("[error] Failed to parse project file: %s" % filename)
  1336. f.close()
  1337. return
  1338. self.file_opened.emit("project", filename)
  1339. ## Clear the current project
  1340. ## NOT THREAD SAFE ##
  1341. self.on_file_new()
  1342. ##Project options
  1343. self.options.update(d['options'])
  1344. self.project_filename = filename
  1345. self.ui.units_label.setText("[" + self.options["units"] + "]")
  1346. ## Re create objects
  1347. App.log.debug("Re-creating objects...")
  1348. for obj in d['objs']:
  1349. def obj_init(obj_inst, app_inst):
  1350. obj_inst.from_dict(obj)
  1351. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  1352. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=False)
  1353. self.plot_all()
  1354. self.inform.emit("Project loaded from: " + filename)
  1355. App.log.debug("Project loaded")
  1356. def propagate_defaults(self):
  1357. routes = {
  1358. "zdownrate": CNCjob
  1359. }
  1360. for param in routes:
  1361. routes[param].defaults[param] = self.defaults[param]
  1362. def plot_all(self):
  1363. """
  1364. Re-generates all plots from all objects.
  1365. :return: None
  1366. """
  1367. self.log.debug("plot_all()")
  1368. self.plotcanvas.clear()
  1369. self.progress.emit(10)
  1370. def worker_task(app_obj):
  1371. percentage = 0.1
  1372. try:
  1373. delta = 0.9 / len(self.collection.get_list())
  1374. except ZeroDivisionError:
  1375. self.progress.emit(0)
  1376. return
  1377. for obj in self.collection.get_list():
  1378. obj.plot()
  1379. percentage += delta
  1380. self.progress.emit(int(percentage*100))
  1381. self.progress.emit(0)
  1382. self.plots_updated.emit()
  1383. # Send to worker
  1384. #self.worker.add_task(worker_task, [self])
  1385. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  1386. def register_folder(self, filename):
  1387. self.last_folder = os.path.split(str(filename))[0]
  1388. def set_progress_bar(self, percentage, text=""):
  1389. self.ui.progress_bar.setValue(int(percentage))
  1390. def setup_shell(self):
  1391. """
  1392. Creates shell functions. Runs once at startup.
  1393. :return: None
  1394. """
  1395. self.log.debug("setup_shell()")
  1396. def shelp(p=None):
  1397. if not p:
  1398. return "Available commands:\n" + '\n'.join([' ' + cmd for cmd in commands]) + \
  1399. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  1400. if p not in commands:
  1401. return "Unknown command: %s" % p
  1402. return commands[p]["help"]
  1403. def options(name):
  1404. ops = self.collection.get_by_name(str(name)).options
  1405. return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  1406. def h(*args):
  1407. """
  1408. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  1409. and standalone parameters into list.
  1410. """
  1411. kwa = {}
  1412. a = []
  1413. n = len(args)
  1414. name = None
  1415. for i in range(n):
  1416. match = re.search(r'^-([a-zA-Z].*)', args[i])
  1417. if match:
  1418. assert name is None
  1419. name = match.group(1)
  1420. continue
  1421. if name is None:
  1422. a.append(args[i])
  1423. else:
  1424. kwa[name] = args[i]
  1425. name = None
  1426. return a, kwa
  1427. def open_gerber(filename, *args):
  1428. a, kwa = h(*args)
  1429. types = {'follow': bool,
  1430. 'outname': str}
  1431. for key in kwa:
  1432. if key not in types:
  1433. return 'Unknown parameter: %s' % key
  1434. kwa[key] = types[key](kwa[key])
  1435. self.open_gerber(str(filename), **kwa)
  1436. def open_excellon(filename, *args):
  1437. a, kwa = h(*args)
  1438. types = {'outname': str}
  1439. for key in kwa:
  1440. if key not in types:
  1441. return 'Unknown parameter: %s' % key
  1442. kwa[key] = types[key](kwa[key])
  1443. self.open_excellon(str(filename), **kwa)
  1444. def open_gcode(filename, *args):
  1445. a, kwa = h(*args)
  1446. types = {'outname': str}
  1447. for key in kwa:
  1448. if key not in types:
  1449. return 'Unknown parameter: %s' % key
  1450. kwa[key] = types[key](kwa[key])
  1451. self.open_gcode(str(filename), **kwa)
  1452. def isolate(name, *args):
  1453. a, kwa = h(*args)
  1454. types = {'dia': float,
  1455. 'passes': int,
  1456. 'overlap': float,
  1457. 'outname': str}
  1458. for key in kwa:
  1459. if key not in types:
  1460. return 'Unknown parameter: %s' % key
  1461. kwa[key] = types[key](kwa[key])
  1462. try:
  1463. obj = self.collection.get_by_name(str(name))
  1464. except:
  1465. return "Could not retrieve object: %s" % name
  1466. if obj is None:
  1467. return "Object not found: %s" % name
  1468. try:
  1469. obj.isolate(**kwa)
  1470. except Exception, e:
  1471. return "Operation failed: %s" % str(e)
  1472. return 'Ok'
  1473. def cncjob(obj_name, *args):
  1474. a, kwa = h(*args)
  1475. types = {'z_cut': float,
  1476. 'z_move': float,
  1477. 'feedrate': float,
  1478. 'tooldia': float,
  1479. 'outname': str}
  1480. for key in kwa:
  1481. if key not in types:
  1482. return 'Unknown parameter: %s' % key
  1483. kwa[key] = types[key](kwa[key])
  1484. try:
  1485. obj = self.collection.get_by_name(str(obj_name))
  1486. except:
  1487. return "Could not retrieve object: %s" % obj_name
  1488. if obj is None:
  1489. return "Object not found: %s" % obj_name
  1490. try:
  1491. obj.generatecncjob(**kwa)
  1492. except Exception, e:
  1493. return "Operation failed: %s" % str(e)
  1494. return 'Ok'
  1495. def write_gcode(obj_name, filename, preamble='', postamble=''):
  1496. try:
  1497. obj = self.collection.get_by_name(str(obj_name))
  1498. except:
  1499. return "Could not retrieve object: %s" % obj_name
  1500. if obj is None:
  1501. return "Object not found: %s" % obj_name
  1502. obj.export_gcode(str(filename), str(preamble), str(postamble))
  1503. def paint_poly(obj_name, inside_pt_x, inside_pt_y, tooldia, overlap):
  1504. try:
  1505. obj = self.collection.get_by_name(str(obj_name))
  1506. except:
  1507. return "Could not retrieve object: %s" % obj_name
  1508. if obj is None:
  1509. return "Object not found: %s" % obj_name
  1510. obj.paint_poly([float(inside_pt_x), float(inside_pt_y)], float(tooldia), float(overlap))
  1511. def add_poly(obj_name, *args):
  1512. if len(args) % 2 != 0:
  1513. return "Incomplete coordinate."
  1514. points = [[float(args[2*i]), float(args[2*i+1])] for i in range(len(args)/2)]
  1515. try:
  1516. obj = self.collection.get_by_name(str(obj_name))
  1517. except:
  1518. return "Could not retrieve object: %s" % obj_name
  1519. if obj is None:
  1520. return "Object not found: %s" % obj_name
  1521. obj.add_polygon(points)
  1522. def add_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  1523. return add_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  1524. topright_x, topright_y, topright_x, botleft_y)
  1525. def add_circle(obj_name, center_x, center_y, radius):
  1526. try:
  1527. obj = self.collection.get_by_name(str(obj_name))
  1528. except:
  1529. return "Could not retrieve object: %s" % obj_name
  1530. if obj is None:
  1531. return "Object not found: %s" % obj_name
  1532. obj.add_circle([float(center_x), float(center_y)], float(radius))
  1533. def set_active(obj_name):
  1534. try:
  1535. self.collection.set_active(str(obj_name))
  1536. except Exception, e:
  1537. return "Command failed: %s" % str(e)
  1538. def delete(obj_name):
  1539. try:
  1540. self.collection.set_active(str(obj_name))
  1541. self.on_delete()
  1542. except Exception, e:
  1543. return "Command failed: %s" % str(e)
  1544. def geo_union(obj_name):
  1545. try:
  1546. obj = self.collection.get_by_name(str(obj_name))
  1547. except:
  1548. return "Could not retrieve object: %s" % obj_name
  1549. if obj is None:
  1550. return "Object not found: %s" % obj_name
  1551. obj.union()
  1552. def make_docs():
  1553. output = ''
  1554. import collections
  1555. od = collections.OrderedDict(sorted(commands.items()))
  1556. for cmd, val in od.iteritems():
  1557. #print cmd, '\n', ''.join(['~']*len(cmd))
  1558. output += cmd + ' \n' + ''.join(['~']*len(cmd)) + '\n'
  1559. t = val['help']
  1560. usage_i = t.find('>')
  1561. if usage_i < 0:
  1562. expl = t
  1563. #print expl + '\n'
  1564. output += expl + '\n\n'
  1565. continue
  1566. expl = t[:usage_i-1]
  1567. #print expl + '\n'
  1568. output += expl + '\n\n'
  1569. end_usage_i = t[usage_i:].find('\n')
  1570. if end_usage_i < 0:
  1571. end_usage_i = len(t[usage_i:])
  1572. #print ' ' + t[usage_i:]
  1573. #print ' No parameters.\n'
  1574. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  1575. else:
  1576. extras = t[usage_i+end_usage_i+1:]
  1577. parts = [s.strip() for s in extras.split('\n')]
  1578. #print ' ' + t[usage_i:usage_i+end_usage_i]
  1579. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  1580. for p in parts:
  1581. #print ' ' + p + '\n'
  1582. output += ' ' + p + '\n\n'
  1583. return output
  1584. def follow(obj_name, *args):
  1585. a, kwa = h(*args)
  1586. types = {'outname': str}
  1587. for key in kwa:
  1588. if key not in types:
  1589. return 'Unknown parameter: %s' % key
  1590. kwa[key] = types[key](kwa[key])
  1591. try:
  1592. obj = self.collection.get_by_name(str(obj_name))
  1593. except:
  1594. return "Could not retrieve object: %s" % obj_name
  1595. if obj is None:
  1596. return "Object not found: %s" % obj_name
  1597. try:
  1598. obj.follow(**kwa)
  1599. except Exception, e:
  1600. return "ERROR: %s" % str(e)
  1601. def get_sys(param):
  1602. if param in self.defaults:
  1603. return self.defaults[param]
  1604. return "ERROR: No such system parameter."
  1605. def set_sys(param, value):
  1606. if param in self.defaults:
  1607. self.defaults[param] = value
  1608. self.propagate_defaults()
  1609. return
  1610. return "ERROR: No such system parameter."
  1611. commands = {
  1612. 'help': {
  1613. 'fcn': shelp,
  1614. 'help': "Shows list of commands."
  1615. },
  1616. 'open_gerber': {
  1617. 'fcn': open_gerber,
  1618. 'help': "Opens a Gerber file.\n' +"
  1619. "> open_gerber <filename> [-follow <0|1>] [-outname <o>]\n' +"
  1620. " filename: Path to file to open.\n" +
  1621. " follow: If 1, does not create polygons, just follows the gerber path.\n" +
  1622. " outname: Name of the created gerber object."
  1623. },
  1624. 'open_excellon': {
  1625. 'fcn': open_excellon,
  1626. 'help': "Opens an Excellon file.\n" +
  1627. "> open_excellon <filename> [-outname <o>]\n" +
  1628. " filename: Path to file to open.\n" +
  1629. " outname: Name of the created excellon object."
  1630. },
  1631. 'open_gcode': {
  1632. 'fcn': open_gcode,
  1633. 'help': "Opens an G-Code file.\n" +
  1634. "> open_gcode <filename> [-outname <o>]\n" +
  1635. " filename: Path to file to open.\n" +
  1636. " outname: Name of the created CNC Job object."
  1637. },
  1638. 'open_project': {
  1639. 'fcn': self.open_project,
  1640. "help": "Opens a FlatCAM project.\n> open_project <filename>\n filename: Path to file to open."
  1641. },
  1642. 'save_project': {
  1643. 'fcn': self.save_project,
  1644. 'help': "Saves the FlatCAM project to file.\n> save_project <filename>\n filename: Path to file to save."
  1645. },
  1646. 'set_active': {
  1647. 'fcn': set_active,
  1648. 'help': "Sets a FlatCAM object as active.\n > set_active <name>\n name: Name of the object."
  1649. },
  1650. 'get_names': {
  1651. 'fcn': lambda: '\n'.join(self.collection.get_names()),
  1652. 'help': "Lists the names of objects in the project.\n > get_names"
  1653. },
  1654. 'new': {
  1655. 'fcn': self.on_file_new,
  1656. 'help': "Starts a new project. Clears objects from memory.\n > new"
  1657. },
  1658. 'options': {
  1659. 'fcn': options,
  1660. 'help': "Shows the settings for an object.\n > options <name>\n name: Object name."
  1661. },
  1662. 'isolate': {
  1663. 'fcn': isolate,
  1664. 'help': "Creates isolation routing geometry for the given Gerber.\n" +
  1665. "> isolate <name> [-dia <d>] [-passes <p>] [-overlap <o>]\n" +
  1666. " name: Name of the object\n"
  1667. " dia: Tool diameter\n passes: # of tool width\n" +
  1668. " overlap: Fraction of tool diameter to overlap passes"
  1669. },
  1670. 'scale': {
  1671. 'fcn': lambda name, factor: self.collection.get_by_name(str(name)).scale(float(factor)),
  1672. 'help': "Resizes the object by a factor.\n" +
  1673. "> scale <name> <factor>\n" +
  1674. " name: Name of the object\n factor: Fraction by which to scale"
  1675. },
  1676. 'offset': {
  1677. 'fcn': lambda name, x, y: self.collection.get_by_name(str(name)).offset([float(x), float(y)]),
  1678. 'help': "Changes the position of the object.\n" +
  1679. "> offset <name> <x> <y>\n" +
  1680. " name: Name of the object\n" +
  1681. " x: X-axis distance\n" +
  1682. " y: Y-axis distance"
  1683. },
  1684. 'plot': {
  1685. 'fcn': self.plot_all,
  1686. 'help': 'Updates the plot on the user interface'
  1687. },
  1688. 'cncjob': {
  1689. 'fcn': cncjob,
  1690. 'help': 'Generates a CNC Job from a Geometry Object.\n' +
  1691. '> cncjob <name> [-z_cut <c>] [-z_move <m>] [-feedrate <f>] [-tooldia <t>] [-outname <n>]\n' +
  1692. ' name: Name of the source object\n' +
  1693. ' z_cut: Z-axis cutting position\n' +
  1694. ' z_move: Z-axis moving position\n' +
  1695. ' feedrate: Moving speed when cutting\n' +
  1696. ' tooldia: Tool diameter to show on screen\n' +
  1697. ' outname: Name of the output object'
  1698. },
  1699. 'write_gcode': {
  1700. 'fcn': write_gcode,
  1701. 'help': 'Saves G-code of a CNC Job object to file.\n' +
  1702. '> write_gcode <name> <filename>\n' +
  1703. ' name: Source CNC Job object\n' +
  1704. ' filename: Output filename'
  1705. },
  1706. 'paint_poly': {
  1707. 'fcn': paint_poly,
  1708. 'help': 'Creates a geometry object with toolpath to cover the inside of a polygon.\n' +
  1709. '> paint_poly <name> <inside_pt_x> <inside_pt_y> <tooldia> <overlap>\n' +
  1710. ' name: Name of the sourge geometry object.\n' +
  1711. ' inside_pt_x, inside_pt_y: Coordinates of a point inside the polygon.\n' +
  1712. ' tooldia: Diameter of the tool to be used.\n' +
  1713. ' overlap: Fraction of the tool diameter to overlap cuts.'
  1714. },
  1715. 'new_geometry': {
  1716. 'fcn': lambda name: self.new_object('geometry', str(name), lambda x, y: None),
  1717. 'help': 'Creates a new empty geometry object.\n' +
  1718. '> new_geometry <name>\n' +
  1719. ' name: New object name'
  1720. },
  1721. 'add_poly': {
  1722. 'fcn': add_poly,
  1723. 'help': 'Creates a polygon in the given Geometry object.\n' +
  1724. '> create_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  1725. ' name: Name of the geometry object to which to append the polygon.\n' +
  1726. ' xi, yi: Coordinates of points in the polygon.'
  1727. },
  1728. 'delete': {
  1729. 'fcn': delete,
  1730. 'help': 'Deletes the give object.\n' +
  1731. '> delete <name>\n' +
  1732. ' name: Name of the object to delete.'
  1733. },
  1734. 'geo_union': {
  1735. 'fcn': geo_union,
  1736. 'help': 'Runs a union operation (addition) on the components ' +
  1737. 'of the geometry object. For example, if it contains ' +
  1738. '2 intersecting polygons, this opperation adds them into' +
  1739. 'a single larger polygon.\n' +
  1740. '> geo_union <name>\n' +
  1741. ' name: Name of the geometry object.'
  1742. },
  1743. 'add_rect': {
  1744. 'fcn': add_rectangle,
  1745. 'help': 'Creates a rectange in the given Geometry object.\n' +
  1746. '> add_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  1747. ' name: Name of the geometry object to which to append the rectangle.\n' +
  1748. ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  1749. ' topright_x, topright_y Coordinates of the top right corner.'
  1750. },
  1751. 'add_circle': {
  1752. 'fcn': add_circle,
  1753. 'help': 'Creates a circle in the given Geometry object.\n' +
  1754. '> add_circle <name> <center_x> <center_y> <radius>\n' +
  1755. ' name: Name of the geometry object to which to append the circle.\n' +
  1756. ' center_x, center_y: Coordinates of the center of the circle.\n' +
  1757. ' radius: Radius of the circle.'
  1758. },
  1759. 'make_docs': {
  1760. 'fcn': make_docs,
  1761. 'help': 'Prints command rererence in reStructuredText format.'
  1762. },
  1763. 'follow': {
  1764. 'fcn': follow,
  1765. 'help': 'Creates a geometry object following gerber paths.\n' +
  1766. '> follow <name> [-outname <oname>]\n' +
  1767. ' name: Name of the gerber object.\n' +
  1768. ' outname: Name of the output geometry object.'
  1769. },
  1770. 'get_sys': {
  1771. 'fcn': get_sys,
  1772. 'help': 'Get the value of a system parameter (FlatCAM constant)\n' +
  1773. '> get_sys <sysparam>\n' +
  1774. ' sysparam: Name of the parameter.'
  1775. },
  1776. 'set_sys': {
  1777. 'fcn': set_sys,
  1778. 'help': 'Set the value of a system parameter (FlatCAM constant)\n' +
  1779. '> set_sys <sysparam> <paramvalue>\n' +
  1780. ' sysparam: Name of the parameter.\n' +
  1781. ' paramvalue: Value to set.'
  1782. }
  1783. }
  1784. # Add commands to the tcl interpreter
  1785. for cmd in commands:
  1786. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  1787. # Make the tcl puts function return instead of print to stdout
  1788. self.tcl.eval('''
  1789. rename puts original_puts
  1790. proc puts {args} {
  1791. if {[llength $args] == 1} {
  1792. return "[lindex $args 0]"
  1793. } else {
  1794. eval original_puts $args
  1795. }
  1796. }
  1797. ''')
  1798. def setup_recent_items(self):
  1799. self.log.debug("setup_recent_items()")
  1800. # TODO: Move this to constructor
  1801. icons = {
  1802. "gerber": "share/flatcam_icon16.png",
  1803. "excellon": "share/drill16.png",
  1804. "cncjob": "share/cnc16.png",
  1805. "project": "share/project16.png"
  1806. }
  1807. openers = {
  1808. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  1809. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  1810. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  1811. 'project': self.open_project
  1812. }
  1813. # Open file
  1814. try:
  1815. f = open('recent.json')
  1816. except IOError:
  1817. App.log.error("Failed to load recent item list.")
  1818. self.inform.emit("[error] Failed to load recent item list.")
  1819. return
  1820. try:
  1821. self.recent = json.load(f)
  1822. except json.scanner.JSONDecodeError:
  1823. App.log.error("Failed to parse recent item list.")
  1824. self.inform.emit("[error] Failed to parse recent item list.")
  1825. f.close()
  1826. return
  1827. f.close()
  1828. # Closure needed to create callbacks in a loop.
  1829. # Otherwise late binding occurs.
  1830. def make_callback(func, fname):
  1831. def opener():
  1832. func(fname)
  1833. return opener
  1834. # Reset menu
  1835. self.ui.recent.clear()
  1836. # Create menu items
  1837. for recent in self.recent:
  1838. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  1839. action = QtGui.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  1840. # Attach callback
  1841. o = make_callback(openers[recent["kind"]], recent['filename'])
  1842. action.triggered.connect(o)
  1843. self.ui.recent.addAction(action)
  1844. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  1845. # self.ui.menufilerecent.set_submenu(recent_menu)
  1846. # recent_menu.show_all()
  1847. # self.ui.recent.show()
  1848. def setup_component_editor(self):
  1849. label = QtGui.QLabel("Choose an item from Project")
  1850. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  1851. self.ui.selected_scroll_area.setWidget(label)
  1852. def setup_obj_classes(self):
  1853. """
  1854. Sets up application specifics on the FlatCAMObj class.
  1855. :return: None
  1856. """
  1857. FlatCAMObj.app = self
  1858. def version_check(self):
  1859. """
  1860. Checks for the latest version of the program. Alerts the
  1861. user if theirs is outdated. This method is meant to be run
  1862. in a separate thread.
  1863. :return: None
  1864. """
  1865. self.log.debug("version_check()")
  1866. full_url = App.version_url + \
  1867. "?s=" + str(self.defaults['serial']) + \
  1868. "&v=" + str(self.version) + \
  1869. "&" + urllib.urlencode(self.defaults["stats"])
  1870. App.log.debug("Checking for updates @ %s" % full_url)
  1871. try:
  1872. f = urllib.urlopen(full_url)
  1873. except:
  1874. App.log.warning("Failed checking for latest version. Could not connect.")
  1875. self.inform.emit("[warning] Failed checking for latest version. Could not connect.")
  1876. return
  1877. try:
  1878. data = json.load(f)
  1879. except Exception, e:
  1880. App.log.error("Could not parse information about latest version.")
  1881. self.inform.emit("[error] Could not parse information about latest version.")
  1882. App.log.debug("json.load(): %s" % str(e))
  1883. f.close()
  1884. return
  1885. f.close()
  1886. if self.version >= data["version"]:
  1887. App.log.debug("FlatCAM is up to date!")
  1888. self.inform.emit("[success] FlatCAM is up to date!")
  1889. return
  1890. App.log.debug("Newer version available.")
  1891. self.message.emit(
  1892. "Newer Version Available",
  1893. "There is a newer version of FlatCAM\n" +
  1894. "available for download:\n\n" +
  1895. data["name"] + "\n\n" + data["message"],
  1896. "info"
  1897. )
  1898. def enable_all_plots(self, *args):
  1899. self.plotcanvas.clear()
  1900. def worker_task(app_obj):
  1901. percentage = 0.1
  1902. try:
  1903. delta = 0.9 / len(self.collection.get_list())
  1904. except ZeroDivisionError:
  1905. self.progress.emit(0)
  1906. return
  1907. for obj in self.collection.get_list():
  1908. obj.options['plot'] = True
  1909. obj.plot()
  1910. percentage += delta
  1911. self.progress.emit(int(percentage*100))
  1912. self.progress.emit(0)
  1913. self.plots_updated.emit()
  1914. # Send to worker
  1915. # self.worker.add_task(worker_task, [self])
  1916. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  1917. def save_project(self, filename):
  1918. """
  1919. Saves the current project to the specified file.
  1920. :param filename: Name of the file in which to save.
  1921. :type filename: str
  1922. :return: None
  1923. """
  1924. self.log.debug("save_project()")
  1925. ## Capture the latest changes
  1926. # Current object
  1927. try:
  1928. self.collection.get_active().read_form()
  1929. except:
  1930. self.log.debug("[warning] There was no active object")
  1931. pass
  1932. # Project options
  1933. self.options_read_form()
  1934. # Serialize the whole project
  1935. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  1936. "options": self.options,
  1937. "version": self.version}
  1938. # Open file
  1939. try:
  1940. f = open(filename, 'w')
  1941. except IOError:
  1942. App.log.error("[error] Failed to open file for saving:", filename)
  1943. return
  1944. # Write
  1945. try:
  1946. json.dump(d, f, default=to_dict)
  1947. except:
  1948. App.log.error("[error] File open but failed to write:", filename)
  1949. f.close()
  1950. return
  1951. f.close()
  1952. self.inform.emit("Project saved to: %s" % filename)
  1953. # def main():
  1954. #
  1955. # app = QtGui.QApplication(sys.argv)
  1956. # fc = App()
  1957. # sys.exit(app.exec_())
  1958. #
  1959. #
  1960. # if __name__ == '__main__':
  1961. # main()