FlatCAMApp.py 98 KB

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