FlatCAMApp.py 98 KB

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