FlatCAMApp.py 98 KB

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