FlatCAMApp.py 109 KB

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