FlatCAMApp.py 98 KB

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