FlatCAMApp.py 98 KB

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