FlatCAMApp.py 133 KB

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