FlatCAMApp.py 112 KB

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