FlatCAMApp.py 98 KB

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