FlatCAMApp.py 87 KB

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