FlatCAMApp.py 101 KB

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