FlatCAMApp.py 98 KB

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