FlatCAMApp.py 88 KB

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