FlatCAMApp.py 99 KB

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