FlatCAMApp.py 107 KB

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