FlatCAMApp.py 100 KB

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