FlatCAMApp.py 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import random
  13. import logging
  14. import simplejson as json
  15. import re
  16. import webbrowser
  17. import os
  18. import tkinter
  19. from PyQt4 import Qt, QtCore, QtGui
  20. import time # Just used for debugging. Double check before removing.
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. from contextlib import contextmanager
  23. ########################################
  24. ## Imports part of FlatCAM ##
  25. ########################################
  26. import FlatCAMVersion
  27. from FlatCAMWorker import Worker
  28. import ObjectCollection
  29. from FlatCAMObj import FlatCAMCNCjob, FlatCAMExcellon, FlatCAMGerber, FlatCAMGeometry, FlatCAMObj
  30. from PlotCanvas import PlotCanvas
  31. from FlatCAMGUI import FlatCAMGUI, GlobalOptionsUI, FlatCAMActivityView, FlatCAMInfoBar
  32. from FlatCAMCommon import LoudDict
  33. from FlatCAMShell import FCShell
  34. from FlatCAMDraw import FlatCAMDraw
  35. from FlatCAMProcess import *
  36. from MeasurementTool import Measurement
  37. from DblSidedTool import DblSidedTool
  38. import tclCommands
  39. from camlib import *
  40. ########################################
  41. ## App ##
  42. ########################################
  43. class App(QtCore.QObject):
  44. """
  45. The main application class. The constructor starts the GUI.
  46. """
  47. ## Get Cmd Line Options
  48. cmd_line_shellfile = ''
  49. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  50. try:
  51. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", "shellfile=")
  52. except getopt.GetoptError:
  53. print(cmd_line_help)
  54. sys.exit(2)
  55. for opt, arg in cmd_line_options:
  56. if opt == '-h':
  57. print(cmd_line_help)
  58. sys.exit()
  59. elif opt == '--shellfile':
  60. cmd_line_shellfile = arg
  61. ## Logging ##
  62. log = logging.getLogger('base')
  63. log.setLevel(logging.DEBUG)
  64. # log.setLevel(logging.WARNING)
  65. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  66. handler = logging.StreamHandler()
  67. handler.setFormatter(formatter)
  68. log.addHandler(handler)
  69. ## Version
  70. version = 8.5
  71. #version_date_str = "2016/7"
  72. version_date = (0, 0, 0)
  73. version_name = None
  74. ## URL for update checks and statistics
  75. version_url = "http://flatcam.org/version"
  76. ## App URL
  77. app_url = "http://flatcam.org"
  78. ## Manual URL
  79. manual_url = "http://flatcam.org/manual/index.html"
  80. ##################
  81. ## Signals ##
  82. ##################
  83. # Inform the user
  84. # Handled by:
  85. # * App.info() --> Print on the status bar
  86. inform = QtCore.pyqtSignal(str)
  87. # General purpose background task
  88. worker_task = QtCore.pyqtSignal(dict)
  89. # File opened
  90. # Handled by:
  91. # * register_folder()
  92. # * register_recent()
  93. # Note: Setting the parameters to unicode does not seem
  94. # to have an effect. Then are received as Qstring
  95. # anyway.
  96. file_opened = QtCore.pyqtSignal(str, str) # File type and filename
  97. progress = QtCore.pyqtSignal(int) # Percentage of progress
  98. plots_updated = QtCore.pyqtSignal()
  99. # Emitted by new_object() and passes the new object as argument.
  100. # on_object_created() adds the object to the collection,
  101. # and emits new_object_available.
  102. object_created = QtCore.pyqtSignal(object)
  103. # Emitted when a new object has been added to the collection
  104. # and is ready to be used.
  105. new_object_available = QtCore.pyqtSignal(object)
  106. message = QtCore.pyqtSignal(str, str, str)
  107. # Emmited when shell command is finished(one command only)
  108. shell_command_finished = QtCore.pyqtSignal(object)
  109. # Emitted when an unhandled exception happens
  110. # in the worker task.
  111. thread_exception = QtCore.pyqtSignal(object)
  112. @property
  113. def version_date_str(self):
  114. return "{:4d}/{:02d}".format(
  115. self.version_date[0],
  116. self.version_date[1]
  117. )
  118. def __init__(self, user_defaults=True, post_gui=None):
  119. """
  120. Starts the application.
  121. :return: app
  122. :rtype: App
  123. """
  124. FlatCAMVersion.setup(self)
  125. App.log.info("FlatCAM Starting...")
  126. ###################
  127. ### OS-specific ###
  128. ###################
  129. # Folder for user settings.
  130. if sys.platform == 'win32':
  131. from win32com.shell import shell, shellcon
  132. App.log.debug("Win32!")
  133. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  134. '/FlatCAM'
  135. self.os = 'windows'
  136. else: # Linux/Unix/MacOS
  137. self.data_path = os.path.expanduser('~') + \
  138. '/.FlatCAM'
  139. self.os = 'unix'
  140. ###############################
  141. ### Setup folders and files ###
  142. ###############################
  143. if not os.path.exists(self.data_path):
  144. os.makedirs(self.data_path)
  145. App.log.debug('Created data folder: ' + self.data_path)
  146. try:
  147. f = open(self.data_path + '/defaults.json')
  148. f.close()
  149. except IOError:
  150. App.log.debug('Creating empty defaults.json')
  151. f = open(self.data_path + '/defaults.json', 'w')
  152. json.dump({}, f)
  153. f.close()
  154. try:
  155. f = open(self.data_path + '/recent.json')
  156. f.close()
  157. except IOError:
  158. App.log.debug('Creating empty recent.json')
  159. f = open(self.data_path + '/recent.json', 'w')
  160. json.dump([], f)
  161. f.close()
  162. # Application directory. Chdir to it. Otherwise, trying to load
  163. # GUI icons will fail as thir path is relative.
  164. if hasattr(sys, "frozen"):
  165. # For cx_freeze and sililar.
  166. self.app_home = os.path.dirname(sys.executable)
  167. else:
  168. self.app_home = os.path.dirname(os.path.realpath(__file__))
  169. App.log.debug("Application path is " + self.app_home)
  170. App.log.debug("Started in " + os.getcwd())
  171. os.chdir(self.app_home)
  172. ####################
  173. ## Initialize GUI ##
  174. ####################
  175. QtCore.QObject.__init__(self)
  176. self.ui = FlatCAMGUI(self.version, name=self.version_name)
  177. self.connect(self.ui,
  178. QtCore.SIGNAL("geomUpdate(int, int, int, int)"),
  179. self.save_geometry)
  180. #### Plot Area ####
  181. # self.plotcanvas = PlotCanvas(self.ui.splitter)
  182. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  183. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  184. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  185. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  186. self.ui.splitter.setStretchFactor(1, 2)
  187. ##############
  188. #### Data ####
  189. ##############
  190. self.recent = []
  191. self.clipboard = QtGui.QApplication.clipboard()
  192. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  193. self.project_filename = None
  194. self.toggle_units_ignore = False
  195. self.defaults_form = GlobalOptionsUI()
  196. self.defaults_form_fields = {
  197. "units": self.defaults_form.units_radio,
  198. "gerber_plot": self.defaults_form.gerber_group.plot_cb,
  199. "gerber_solid": self.defaults_form.gerber_group.solid_cb,
  200. "gerber_multicolored": self.defaults_form.gerber_group.multicolored_cb,
  201. "gerber_isotooldia": self.defaults_form.gerber_group.iso_tool_dia_entry,
  202. "gerber_isopasses": self.defaults_form.gerber_group.iso_width_entry,
  203. "gerber_isooverlap": self.defaults_form.gerber_group.iso_overlap_entry,
  204. "gerber_combine_passes": self.defaults_form.gerber_group.combine_passes_cb,
  205. "gerber_cutouttooldia": self.defaults_form.gerber_group.cutout_tooldia_entry,
  206. "gerber_cutoutmargin": self.defaults_form.gerber_group.cutout_margin_entry,
  207. "gerber_cutoutgapsize": self.defaults_form.gerber_group.cutout_gap_entry,
  208. "gerber_gaps": self.defaults_form.gerber_group.gaps_radio,
  209. "gerber_noncoppermargin": self.defaults_form.gerber_group.noncopper_margin_entry,
  210. "gerber_noncopperrounded": self.defaults_form.gerber_group.noncopper_rounded_cb,
  211. "gerber_bboxmargin": self.defaults_form.gerber_group.bbmargin_entry,
  212. "gerber_bboxrounded": self.defaults_form.gerber_group.bbrounded_cb,
  213. "excellon_plot": self.defaults_form.excellon_group.plot_cb,
  214. "excellon_solid": self.defaults_form.excellon_group.solid_cb,
  215. "excellon_drillz": self.defaults_form.excellon_group.cutz_entry,
  216. "excellon_travelz": self.defaults_form.excellon_group.travelz_entry,
  217. "excellon_feedrate": self.defaults_form.excellon_group.feedrate_entry,
  218. "excellon_spindlespeed": self.defaults_form.excellon_group.spindlespeed_entry,
  219. "excellon_toolchangez": self.defaults_form.excellon_group.toolchangez_entry,
  220. "excellon_tooldia": self.defaults_form.excellon_group.tooldia_entry,
  221. "geometry_plot": self.defaults_form.geometry_group.plot_cb,
  222. "geometry_cutz": self.defaults_form.geometry_group.cutz_entry,
  223. "geometry_travelz": self.defaults_form.geometry_group.travelz_entry,
  224. "geometry_feedrate": self.defaults_form.geometry_group.cncfeedrate_entry,
  225. "geometry_cnctooldia": self.defaults_form.geometry_group.cnctooldia_entry,
  226. "geometry_painttooldia": self.defaults_form.geometry_group.painttooldia_entry,
  227. "geometry_spindlespeed": self.defaults_form.geometry_group.cncspindlespeed_entry,
  228. "geometry_paintoverlap": self.defaults_form.geometry_group.paintoverlap_entry,
  229. "geometry_paintmargin": self.defaults_form.geometry_group.paintmargin_entry,
  230. "geometry_selectmethod": self.defaults_form.geometry_group.selectmethod_combo,
  231. "geometry_pathconnect": self.defaults_form.geometry_group.pathconnect_cb,
  232. "geometry_paintcontour": self.defaults_form.geometry_group.contour_cb,
  233. "cncjob_plot": self.defaults_form.cncjob_group.plot_cb,
  234. "cncjob_tooldia": self.defaults_form.cncjob_group.tooldia_entry,
  235. "cncjob_prepend": self.defaults_form.cncjob_group.prepend_text,
  236. "cncjob_append": self.defaults_form.cncjob_group.append_text,
  237. "cncjob_dwell": self.defaults_form.cncjob_group.dwell_cb,
  238. "cncjob_dwelltime": self.defaults_form.cncjob_group.dwelltime_cb
  239. }
  240. self.defaults = LoudDict()
  241. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  242. self.defaults.update({
  243. "serial": 0,
  244. "stats": {},
  245. "units": "IN",
  246. "gerber_plot": True,
  247. "gerber_solid": True,
  248. "gerber_multicolored": False,
  249. "gerber_isotooldia": 0.016,
  250. "gerber_isopasses": 1,
  251. "gerber_isooverlap": 0.15,
  252. "gerber_cutouttooldia": 0.07,
  253. "gerber_cutoutmargin": 0.1,
  254. "gerber_cutoutgapsize": 0.15,
  255. "gerber_gaps": "4",
  256. "gerber_noncoppermargin": 0.0,
  257. "gerber_noncopperrounded": False,
  258. "gerber_bboxmargin": 0.0,
  259. "gerber_bboxrounded": False,
  260. "excellon_plot": True,
  261. "excellon_solid": False,
  262. "excellon_drillz": -0.1,
  263. "excellon_travelz": 0.1,
  264. "excellon_feedrate": 3.0,
  265. "excellon_spindlespeed": None,
  266. "excellon_toolchangez": 1.0,
  267. "excellon_tooldia": 0.016,
  268. "geometry_plot": True,
  269. "geometry_cutz": -0.002,
  270. "geometry_travelz": 0.1,
  271. "geometry_feedrate": 3.0,
  272. "geometry_cnctooldia": 0.016,
  273. "geometry_spindlespeed": None,
  274. "geometry_painttooldia": 0.07,
  275. "geometry_paintoverlap": 0.15,
  276. "geometry_paintmargin": 0.0,
  277. "geometry_selectmethod": "single",
  278. "geometry_pathconnect": True,
  279. "geometry_paintcontour": True,
  280. "cncjob_plot": True,
  281. "cncjob_tooldia": 0.016,
  282. "cncjob_prepend": "",
  283. "cncjob_append": "",
  284. "cncjob_dwell": True,
  285. "cncjob_dwelltime": 1,
  286. "background_timeout": 300000, # Default value is 5 minutes
  287. "verbose_error_level": 0, # Shell verbosity 0 = default
  288. # (python trace only for unknown errors),
  289. # 1 = show trace(show trace allways),
  290. # 2 = (For the future).
  291. # Persistence
  292. "last_folder": None,
  293. # Default window geometry
  294. "def_win_x": 100,
  295. "def_win_y": 100,
  296. "def_win_w": 1024,
  297. "def_win_h": 650,
  298. # Constants...
  299. "defaults_save_period_ms": 20000, # Time between default saves.
  300. "shell_shape": [500, 300], # Shape of the shell in pixels.
  301. "shell_at_startup": False, # Show the shell at startup.
  302. "recent_limit": 10, # Max. items in recent list.
  303. "fit_key": '1',
  304. "zoom_out_key": '2',
  305. "zoom_in_key": '3',
  306. "zoom_ratio": 1.5,
  307. "point_clipboard_format": "(%.4f, %.4f)",
  308. "zdownrate": None,
  309. "excellon_zeros": "L",
  310. "gerber_use_buffer_for_union": True,
  311. "cncjob_coordinate_format": "X%.4fY%.4f"
  312. })
  313. ###############################
  314. ### Load defaults from file ###
  315. if user_defaults:
  316. self.load_defaults()
  317. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  318. if self.defaults['serial'] == 0 or len(str(self.defaults['serial'])) < 10:
  319. self.defaults['serial'] = ''.join([random.choice(chars) for i in range(20)])
  320. self.save_defaults(silent=True)
  321. self.propagate_defaults()
  322. self.restore_main_win_geom()
  323. def auto_save_defaults():
  324. try:
  325. self.save_defaults(silent=True)
  326. finally:
  327. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  328. if user_defaults:
  329. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  330. self.options_form = GlobalOptionsUI()
  331. self.options_form_fields = {
  332. "units": self.options_form.units_radio,
  333. "gerber_plot": self.options_form.gerber_group.plot_cb,
  334. "gerber_solid": self.options_form.gerber_group.solid_cb,
  335. "gerber_multicolored": self.options_form.gerber_group.multicolored_cb,
  336. "gerber_isotooldia": self.options_form.gerber_group.iso_tool_dia_entry,
  337. "gerber_isopasses": self.options_form.gerber_group.iso_width_entry,
  338. "gerber_isooverlap": self.options_form.gerber_group.iso_overlap_entry,
  339. "gerber_combine_passes": self.options_form.gerber_group.combine_passes_cb,
  340. "gerber_cutouttooldia": self.options_form.gerber_group.cutout_tooldia_entry,
  341. "gerber_cutoutmargin": self.options_form.gerber_group.cutout_margin_entry,
  342. "gerber_cutoutgapsize": self.options_form.gerber_group.cutout_gap_entry,
  343. "gerber_gaps": self.options_form.gerber_group.gaps_radio,
  344. "gerber_noncoppermargin": self.options_form.gerber_group.noncopper_margin_entry,
  345. "gerber_noncopperrounded": self.options_form.gerber_group.noncopper_rounded_cb,
  346. "gerber_bboxmargin": self.options_form.gerber_group.bbmargin_entry,
  347. "gerber_bboxrounded": self.options_form.gerber_group.bbrounded_cb,
  348. "excellon_plot": self.options_form.excellon_group.plot_cb,
  349. "excellon_solid": self.options_form.excellon_group.solid_cb,
  350. "excellon_drillz": self.options_form.excellon_group.cutz_entry,
  351. "excellon_travelz": self.options_form.excellon_group.travelz_entry,
  352. "excellon_feedrate": self.options_form.excellon_group.feedrate_entry,
  353. "excellon_spindlespeed": self.options_form.excellon_group.spindlespeed_entry,
  354. "excellon_toolchangez": self.options_form.excellon_group.toolchangez_entry,
  355. "excellon_tooldia": self.options_form.excellon_group.tooldia_entry,
  356. "geometry_plot": self.options_form.geometry_group.plot_cb,
  357. "geometry_cutz": self.options_form.geometry_group.cutz_entry,
  358. "geometry_travelz": self.options_form.geometry_group.travelz_entry,
  359. "geometry_feedrate": self.options_form.geometry_group.cncfeedrate_entry,
  360. "geometry_spindlespeed": self.options_form.geometry_group.cncspindlespeed_entry,
  361. "geometry_cnctooldia": self.options_form.geometry_group.cnctooldia_entry,
  362. "geometry_painttooldia": self.options_form.geometry_group.painttooldia_entry,
  363. "geometry_paintoverlap": self.options_form.geometry_group.paintoverlap_entry,
  364. "geometry_paintmargin": self.options_form.geometry_group.paintmargin_entry,
  365. "geometry_selectmethod": self.options_form.geometry_group.selectmethod_combo,
  366. "cncjob_plot": self.options_form.cncjob_group.plot_cb,
  367. "cncjob_tooldia": self.options_form.cncjob_group.tooldia_entry,
  368. "cncjob_prepend": self.options_form.cncjob_group.prepend_text,
  369. "cncjob_append": self.options_form.cncjob_group.append_text
  370. }
  371. self.options = LoudDict()
  372. self.options.set_change_callback(self.on_options_dict_change)
  373. self.options.update({
  374. "units": "IN",
  375. "gerber_plot": True,
  376. "gerber_solid": True,
  377. "gerber_multicolored": False,
  378. "gerber_isotooldia": 0.016,
  379. "gerber_isopasses": 1,
  380. "gerber_isooverlap": 0.15,
  381. "gerber_combine_passes": True,
  382. "gerber_cutouttooldia": 0.07,
  383. "gerber_cutoutmargin": 0.1,
  384. "gerber_cutoutgapsize": 0.15,
  385. "gerber_gaps": "4",
  386. "gerber_noncoppermargin": 0.0,
  387. "gerber_noncopperrounded": False,
  388. "gerber_bboxmargin": 0.0,
  389. "gerber_bboxrounded": False,
  390. "excellon_plot": True,
  391. "excellon_solid": False,
  392. "excellon_drillz": -0.1,
  393. "excellon_travelz": 0.1,
  394. "excellon_feedrate": 3.0,
  395. "excellon_spindlespeed": None,
  396. "excellon_toolchangez": 1.0,
  397. "excellon_tooldia": 0.016,
  398. "geometry_plot": True,
  399. "geometry_cutz": -0.002,
  400. "geometry_travelz": 0.1,
  401. "geometry_feedrate": 3.0,
  402. "geometry_spindlespeed": None,
  403. "geometry_cnctooldia": 0.016,
  404. "geometry_painttooldia": 0.07,
  405. "geometry_paintoverlap": 0.15,
  406. "geometry_paintmargin": 0.0,
  407. "geometry_selectmethod": "single",
  408. "cncjob_plot": True,
  409. "cncjob_tooldia": 0.016,
  410. "cncjob_prepend": "",
  411. "cncjob_append": "",
  412. "background_timeout": 300000, # Default value is 5 minutes
  413. "verbose_error_level": 0, # Shell verbosity:
  414. # 0 = default(python trace only for unknown errors),
  415. # 1 = show trace(show trace allways), 2 = (For the future).
  416. })
  417. self.options.update(self.defaults) # Copy app defaults to project options
  418. #self.options_write_form()
  419. self.on_options_combo_change(0) # Will show the initial form
  420. self.collection = ObjectCollection.ObjectCollection()
  421. self.ui.project_tab_layout.addWidget(self.collection.view)
  422. #### End of Data ####
  423. #### Worker ####
  424. App.log.info("Starting Worker...")
  425. self.worker = Worker(self)
  426. self.thr1 = QtCore.QThread()
  427. self.worker.moveToThread(self.thr1)
  428. self.connect(self.thr1, QtCore.SIGNAL("started()"), self.worker.run)
  429. self.thr1.start()
  430. #### Check for updates ####
  431. # Separate thread (Not worker)
  432. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  433. self.worker2 = Worker(self, name="worker2")
  434. self.thr2 = QtCore.QThread()
  435. self.worker2.moveToThread(self.thr2)
  436. self.connect(self.thr2, QtCore.SIGNAL("started()"), self.worker2.run)
  437. self.connect(self.thr2, QtCore.SIGNAL("started()"),
  438. lambda: self.worker_task.emit({'fcn': self.version_check,
  439. 'params': [],
  440. 'worker_name': "worker2"}))
  441. self.thr2.start()
  442. ### Signal handling ###
  443. ## Custom signals
  444. self.inform.connect(self.info)
  445. self.message.connect(self.message_dialog)
  446. self.progress.connect(self.set_progress_bar)
  447. self.object_created.connect(self.on_object_created)
  448. self.plots_updated.connect(self.on_plots_updated)
  449. self.file_opened.connect(self.register_recent)
  450. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  451. ## Standard signals
  452. # Menu
  453. self.ui.menufilenew.triggered.connect(self.on_file_new)
  454. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  455. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  456. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  457. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  458. self.ui.menufileimportsvg.triggered.connect(self.on_file_importsvg)
  459. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  460. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  461. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  462. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  463. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  464. self.ui.exit_action.triggered.connect(self.on_file_exit)
  465. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  466. self.ui.menueditedit.triggered.connect(self.edit_geometry)
  467. self.ui.menueditok.triggered.connect(self.editor2geometry)
  468. self.ui.menueditjoin.triggered.connect(self.on_edit_join)
  469. self.ui.menueditdelete.triggered.connect(self.on_delete)
  470. self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  471. self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  472. self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  473. self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  474. self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  475. self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  476. self.ui.menuviewdisableall.triggered.connect(self.disable_plots)
  477. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(except_current=True))
  478. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  479. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  480. self.ui.menuhelp_about.triggered.connect(self.on_about)
  481. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  482. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  483. # Toolbar
  484. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  485. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  486. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  487. self.ui.clear_plot_btn.triggered.connect(self.plotcanvas.clear)
  488. self.ui.replot_btn.triggered.connect(self.on_toolbar_replot)
  489. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  490. self.ui.editgeo_btn.triggered.connect(self.edit_geometry)
  491. self.ui.updategeo_btn.triggered.connect(self.editor2geometry)
  492. self.ui.delete_btn.triggered.connect(self.on_delete)
  493. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  494. # Object list
  495. self.collection.view.activated.connect(self.on_row_activated)
  496. # Options
  497. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  498. self.options_form.units_radio.group_toggle_fn = self.on_toggle_units
  499. #Notebook tabs
  500. ####################
  501. ### Other setups ###
  502. ####################
  503. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  504. self.setup_obj_classes()
  505. self.setup_recent_items()
  506. self.setup_component_editor()
  507. #########################
  508. ### Tools and Plugins ###
  509. #########################
  510. self.dblsidedtool = DblSidedTool(self)
  511. self.dblsidedtool.install()
  512. self.measeurement_tool = Measurement(self)
  513. self.measeurement_tool.install()
  514. self.draw = FlatCAMDraw(self, disabled=True)
  515. #############
  516. ### Shell ###
  517. #############
  518. # TODO: Move this to its own class
  519. self.shell = FCShell(self)
  520. self.shell.setWindowIcon(self.ui.app_icon)
  521. self.shell.setWindowTitle("FlatCAM Shell")
  522. self.shell.resize(*self.defaults["shell_shape"])
  523. self.shell.append_output("FlatCAM {}".format(self.version))
  524. if self.version_name:
  525. self.shell.append_output(" - {}".format(self.version_name))
  526. self.shell.append_output("\n(c) 2014-{} Juan Pablo Caram\n\n".format(
  527. self.version_date[0]))
  528. self.shell.append_output("Type help to get started.\n\n")
  529. self.init_tcl()
  530. self.ui.shell_dock = QtGui.QDockWidget("FlatCAM TCL Shell")
  531. self.ui.shell_dock.setWidget(self.shell)
  532. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  533. self.ui.shell_dock.setFeatures(QtGui.QDockWidget.DockWidgetMovable |
  534. QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetClosable)
  535. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  536. if self.defaults["shell_at_startup"]:
  537. self.ui.shell_dock.show()
  538. else:
  539. self.ui.shell_dock.hide()
  540. if self.cmd_line_shellfile:
  541. try:
  542. with open(self.cmd_line_shellfile, "r") as myfile:
  543. cmd_line_shellfile_text = myfile.read()
  544. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  545. except Exception as ext:
  546. print(("ERROR: ", ext))
  547. sys.exit(2)
  548. # Post-GUI initialization: Experimental attempt
  549. # to perform unit tests on the GUI.
  550. if post_gui is not None:
  551. post_gui(self)
  552. App.log.debug("END of constructor. Releasing control.")
  553. def init_tcl(self):
  554. if hasattr(self, 'tcl'):
  555. # self.tcl = None
  556. # TODO we need to clean non default variables and procedures here
  557. # new object cannot be used here as it will not remember values created for next passes,
  558. # because tcl was execudted in old instance of TCL
  559. pass
  560. else:
  561. self.tcl = tkinter.Tcl()
  562. self.setup_shell()
  563. def defaults_read_form(self):
  564. for option in self.defaults_form_fields:
  565. self.defaults[option] = self.defaults_form_fields[option].get_value()
  566. def defaults_write_form(self):
  567. for option in self.defaults:
  568. self.defaults_write_form_field(option)
  569. # try:
  570. # self.defaults_form_fields[option].set_value(self.defaults[option])
  571. # except KeyError:
  572. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  573. # # TODO: Rethink this?
  574. # pass
  575. def defaults_write_form_field(self, field):
  576. try:
  577. self.defaults_form_fields[field].set_value(self.defaults[field])
  578. except KeyError:
  579. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  580. # TODO: Rethink this?
  581. pass
  582. def disable_plots(self, except_current=False):
  583. """
  584. Disables all plots with exception of the current object if specified.
  585. :param except_current: Wether to skip the current object.
  586. :rtype except_current: boolean
  587. :return: None
  588. """
  589. # TODO: This method is very similar to replot_all. Try to merge.
  590. self.progress.emit(10)
  591. def worker_task(app_obj):
  592. percentage = 0.1
  593. try:
  594. delta = 0.9 / len(self.collection.get_list())
  595. except ZeroDivisionError:
  596. self.progress.emit(0)
  597. return
  598. for obj in self.collection.get_list():
  599. if obj != self.collection.get_active() or not except_current:
  600. obj.options['plot'] = False
  601. obj.plot()
  602. percentage += delta
  603. self.progress.emit(int(percentage*100))
  604. self.progress.emit(0)
  605. self.plots_updated.emit()
  606. # Send to worker
  607. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  608. def edit_geometry(self):
  609. """
  610. Send the current geometry object (if any) into the editor.
  611. :return: None
  612. """
  613. if not isinstance(self.collection.get_active(), FlatCAMGeometry):
  614. self.info("Select a Geometry Object to edit.")
  615. return
  616. self.ui.updategeo_btn.setEnabled(True)
  617. self.draw.edit_fcgeometry(self.collection.get_active())
  618. def editor2geometry(self):
  619. """
  620. Transfers the geometry in the editor to the current geometry object.
  621. :return: None
  622. """
  623. geo = self.collection.get_active()
  624. if not isinstance(geo, FlatCAMGeometry):
  625. self.info("Select a Geometry Object to update.")
  626. return
  627. self.draw.update_fcgeometry(geo)
  628. self.draw.deactivate()
  629. self.ui.updategeo_btn.setEnabled(False)
  630. geo.plot()
  631. def get_last_folder(self):
  632. return self.defaults["last_folder"]
  633. def report_usage(self, resource):
  634. """
  635. Increments usage counter for the given resource
  636. in self.defaults['stats'].
  637. :param resource: Name of the resource.
  638. :return: None
  639. """
  640. if resource in self.defaults['stats']:
  641. self.defaults['stats'][resource] += 1
  642. else:
  643. self.defaults['stats'][resource] = 1
  644. # TODO: This shouldn't be here.
  645. class TclErrorException(Exception):
  646. """
  647. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  648. """
  649. pass
  650. def shell_message(self, msg, show=False, error=False):
  651. """
  652. Shows a message on the FlatCAM Shell
  653. :param msg: Message to display.
  654. :param show: Opens the shell.
  655. :param error: Shows the message as an error.
  656. :return: None
  657. """
  658. if show:
  659. self.ui.shell_dock.show()
  660. if error:
  661. self.shell.append_error(msg + "\n")
  662. else:
  663. self.shell.append_output(msg + "\n")
  664. def raise_tcl_unknown_error(self, unknownException):
  665. """
  666. Raise exception if is different type than TclErrorException
  667. this is here mainly to show unknown errors inside TCL shell console.
  668. :param unknownException:
  669. :return:
  670. """
  671. if not isinstance(unknownException, self.TclErrorException):
  672. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  673. else:
  674. raise unknownException
  675. def display_tcl_error(self, error, error_info=None):
  676. """
  677. escape bracket [ with \ otherwise there is error
  678. "ERROR: missing close-bracket" instead of real error
  679. :param error: it may be text or exception
  680. :return: None
  681. """
  682. if isinstance(error, Exception):
  683. exc_type, exc_value, exc_traceback = error_info
  684. if not isinstance(error, self.TclErrorException):
  685. show_trace = 1
  686. else:
  687. show_trace = int(self.defaults['verbose_error_level'])
  688. if show_trace > 0:
  689. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  690. trc_formated = []
  691. for a in reversed(trc):
  692. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  693. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  694. exc_type,
  695. "\n".join(trc_formated))
  696. else:
  697. text = "%s" % error
  698. else:
  699. text = error
  700. text = text.replace('[', '\\[').replace('"', '\\"')
  701. self.tcl.eval('return -code error "%s"' % text)
  702. def raise_tcl_error(self, text):
  703. """
  704. this method pass exception from python into TCL as error, so we get stacktrace and reason
  705. :param text: text of error
  706. :return: raise exception
  707. """
  708. self.display_tcl_error(text)
  709. raise self.TclErrorException(text)
  710. def exec_command(self, text):
  711. """
  712. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  713. Also handles execution in separated threads
  714. :param text:
  715. :return: output if there was any
  716. """
  717. self.report_usage('exec_command')
  718. result = self.exec_command_test(text, False)
  719. return result
  720. def exec_command_test(self, text, reraise=True):
  721. """
  722. Same as exec_command(...) with additional control over exceptions.
  723. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  724. :param text: Input command
  725. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  726. :return: Output from the command
  727. """
  728. text = str(text)
  729. try:
  730. self.shell.open_proccessing() # Disables input box.
  731. result = self.tcl.eval(str(text))
  732. if result != 'None':
  733. self.shell.append_output(result + '\n')
  734. except tkinter.TclError as e:
  735. # This will display more precise answer if something in TCL shell fails
  736. result = self.tcl.eval("set errorInfo")
  737. self.log.error("Exec command Exception: %s" % (result + '\n'))
  738. self.shell.append_error('ERROR: ' + result + '\n')
  739. # Show error in console and just return or in test raise exception
  740. if reraise:
  741. raise e
  742. finally:
  743. self.shell.close_proccessing()
  744. pass
  745. return result
  746. """
  747. Code below is unsused. Saved for later.
  748. """
  749. parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  750. parts = [p.replace('\n', '').replace('"', '') for p in parts]
  751. self.log.debug(parts)
  752. try:
  753. if parts[0] not in commands:
  754. self.shell.append_error("Unknown command\n")
  755. return
  756. #import inspect
  757. #inspect.getargspec(someMethod)
  758. if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  759. (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  760. self.shell.append_error(
  761. "Command %s takes %d arguments. %d given.\n" %
  762. (parts[0], commands[parts[0]]["params"], len(parts)-1)
  763. )
  764. return
  765. cmdfcn = commands[parts[0]]["fcn"]
  766. cmdconv = commands[parts[0]]["converters"]
  767. if len(parts) - 1 > 0:
  768. retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  769. else:
  770. retval = cmdfcn()
  771. retfcn = commands[parts[0]]["retfcn"]
  772. if retval and retfcn(retval):
  773. self.shell.append_output(retfcn(retval) + "\n")
  774. except Exception as e:
  775. #self.shell.append_error(''.join(traceback.format_exc()))
  776. #self.shell.append_error("?\n")
  777. self.shell.append_error(str(e) + "\n")
  778. def info(self, msg, toshell=True):
  779. """
  780. Informs the user. Normally on the status bar, optionally
  781. also on the shell.
  782. :param msg: Text to write.
  783. :param toshell: Forward the meesage to the shell.
  784. :return: None
  785. """
  786. # Type of message in brackets at the begining of the message.
  787. match = re.search("\[([^\]]+)\](.*)", msg)
  788. if match:
  789. level = match.group(1)
  790. msg_ = match.group(2)
  791. self.ui.fcinfo.set_status(str(msg_), level=level)
  792. if toshell:
  793. error = level == "error" or level == "warning"
  794. self.shell_message(msg, error=error, show=True)
  795. else:
  796. self.ui.fcinfo.set_status(str(msg), level="info")
  797. if toshell:
  798. self.shell_message(msg)
  799. def load_defaults(self):
  800. """
  801. Loads the aplication's default settings from defaults.json into
  802. ``self.defaults``.
  803. :return: None
  804. """
  805. try:
  806. f = open(self.data_path + "/defaults.json")
  807. options = f.read()
  808. f.close()
  809. except IOError:
  810. self.log.error("Could not load defaults file.")
  811. self.inform.emit("ERROR: Could not load defaults file.")
  812. return
  813. try:
  814. defaults = json.loads(options)
  815. except:
  816. e = sys.exc_info()[0]
  817. App.log.error(str(e))
  818. self.inform.emit("ERROR: Failed to parse defaults file.")
  819. return
  820. self.defaults.update(defaults)
  821. def save_geometry(self, x, y, width, height):
  822. self.defaults["def_win_x"] = x
  823. self.defaults["def_win_y"] = y
  824. self.defaults["def_win_w"] = width
  825. self.defaults["def_win_h"] = height
  826. self.save_defaults()
  827. def message_dialog(self, title, message, kind="info"):
  828. icon = {"info": QtGui.QMessageBox.Information,
  829. "warning": QtGui.QMessageBox.Warning,
  830. "error": QtGui.QMessageBox.Critical}[str(kind)]
  831. dlg = QtGui.QMessageBox(icon, title, message, parent=self.ui)
  832. dlg.setText(message)
  833. dlg.exec_()
  834. def register_recent(self, kind, filename):
  835. self.log.debug("register_recent()")
  836. self.log.debug(" %s" % kind)
  837. self.log.debug(" %s" % filename)
  838. record = {'kind': str(kind), 'filename': str(filename)}
  839. if record in self.recent:
  840. return
  841. self.recent.insert(0, record)
  842. if len(self.recent) > self.defaults['recent_limit']: # Limit reached
  843. self.recent.pop()
  844. try:
  845. f = open(self.data_path + '/recent.json', 'w')
  846. except IOError:
  847. App.log.error("Failed to open recent items file for writing.")
  848. self.inform.emit('Failed to open recent files file for writing.')
  849. return
  850. #try:
  851. json.dump(self.recent, f)
  852. # except:
  853. # App.log.error("Failed to write to recent items file.")
  854. # self.inform.emit('ERROR: Failed to write to recent items file.')
  855. # f.close()
  856. f.close()
  857. # Re-buid the recent items menu
  858. self.setup_recent_items()
  859. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True):
  860. """
  861. Creates a new specalized FlatCAMObj and attaches it to the application,
  862. this is, updates the GUI accordingly, any other records and plots it.
  863. This method is thread-safe.
  864. Notes:
  865. * If the name is in use, the self.collection will modify it
  866. when appending it to the collection. There is no need to handle
  867. name conflicts here.
  868. :param kind: The kind of object to create. One of 'gerber',
  869. 'excellon', 'cncjob' and 'geometry'.
  870. :type kind: str
  871. :param name: Name for the object.
  872. :type name: str
  873. :param initialize: Function to run after creation of the object
  874. but before it is attached to the application. The function is
  875. called with 2 parameters: the new object and the App instance.
  876. :type initialize: function
  877. :return: None
  878. :rtype: None
  879. """
  880. App.log.debug("new_object()")
  881. t0 = time.time() # Debug
  882. ## Create object
  883. classdict = {
  884. "gerber": FlatCAMGerber,
  885. "excellon": FlatCAMExcellon,
  886. "cncjob": FlatCAMCNCjob,
  887. "geometry": FlatCAMGeometry
  888. }
  889. App.log.debug("Calling object constructor...")
  890. obj = classdict[kind](name)
  891. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  892. # Set default options from self.options
  893. for option in self.options:
  894. if option.find(kind + "_") == 0:
  895. oname = option[len(kind) + 1:]
  896. obj.options[oname] = self.options[option]
  897. # Initialize as per user request
  898. # User must take care to implement initialize
  899. # in a thread-safe way as is is likely that we
  900. # have been invoked in a separate thread.
  901. t1 = time.time()
  902. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  903. initialize(obj, self)
  904. t2 = time.time()
  905. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  906. # Check units and convert if necessary
  907. # This condition CAN be true because initialize() can change obj.units
  908. if self.options["units"].upper() != obj.units.upper():
  909. self.inform.emit("Converting units to " + self.options["units"] + ".")
  910. obj.convert_units(self.options["units"])
  911. t3 = time.time()
  912. self.log.debug("%f seconds converting units." % (t3 - t2))
  913. self.log.debug("Moving new object back to main thread.")
  914. # Move the object to the main thread and let the app know that it is available.
  915. obj.moveToThread(QtGui.QApplication.instance().thread())
  916. self.object_created.emit(obj)
  917. return obj
  918. def options_read_form(self):
  919. for option in self.options_form_fields:
  920. self.options[option] = self.options_form_fields[option].get_value()
  921. def options_write_form(self):
  922. for option in self.options:
  923. self.options_write_form_field(option)
  924. def options_write_form_field(self, field):
  925. try:
  926. self.options_form_fields[field].set_value(self.options[field])
  927. except KeyError:
  928. # Changed from error to debug. This allows to have data stored
  929. # which is not user-editable.
  930. self.log.debug("options_write_form_field(): No field for: %s" % field)
  931. def on_about(self):
  932. """
  933. Displays the "about" dialog.
  934. :return: None
  935. """
  936. self.report_usage("on_about")
  937. version = self.version
  938. version_date_str = self.version_date_str
  939. version_year = self.version_date[0]
  940. class AboutDialog(QtGui.QDialog):
  941. def __init__(self, parent=None):
  942. QtGui.QDialog.__init__(self, parent)
  943. # Icon and title
  944. self.setWindowIcon(parent.app_icon)
  945. self.setWindowTitle("FlatCAM")
  946. layout1 = QtGui.QVBoxLayout()
  947. self.setLayout(layout1)
  948. layout2 = QtGui.QHBoxLayout()
  949. layout1.addLayout(layout2)
  950. logo = QtGui.QLabel()
  951. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  952. layout2.addWidget(logo, stretch=0)
  953. title = QtGui.QLabel(
  954. "<font size=8><B>FlatCAM</B></font><BR>"
  955. "Version {} ({})<BR>"
  956. "<BR>"
  957. "2D Computer-Aided Printed Circuit Board<BR>"
  958. "Manufacturing.<BR>"
  959. "<BR>"
  960. "(c) 2014-{} Juan Pablo Caram".format(
  961. version,
  962. version_date_str,
  963. version_year
  964. )
  965. )
  966. layout2.addWidget(title, stretch=1)
  967. layout3 = QtGui.QHBoxLayout()
  968. layout1.addLayout(layout3)
  969. layout3.addStretch()
  970. okbtn = QtGui.QPushButton("Close")
  971. layout3.addWidget(okbtn)
  972. okbtn.clicked.connect(self.accept)
  973. AboutDialog(self.ui).exec_()
  974. def on_file_savedefaults(self):
  975. """
  976. Callback for menu item File->Save Defaults. Saves application default options
  977. ``self.defaults`` to defaults.json.
  978. :return: None
  979. """
  980. self.save_defaults()
  981. def on_file_exit(self):
  982. QtGui.qApp.quit()
  983. def save_defaults(self, silent=False):
  984. """
  985. Saves application default options
  986. ``self.defaults`` to defaults.json.
  987. :return: None
  988. """
  989. self.report_usage("save_defaults")
  990. ## Read options from file ##
  991. try:
  992. f = open(self.data_path + "/defaults.json")
  993. options = f.read()
  994. f.close()
  995. except:
  996. e = sys.exc_info()[0]
  997. App.log.error("Could not load defaults file.")
  998. App.log.error(str(e))
  999. self.inform.emit("[error] Could not load defaults file.")
  1000. return
  1001. try:
  1002. defaults = json.loads(options)
  1003. except:
  1004. e = sys.exc_info()[0]
  1005. App.log.error("Failed to parse defaults file.")
  1006. App.log.error(str(e))
  1007. self.inform.emit("[error] Failed to parse defaults file.")
  1008. return
  1009. # Update options
  1010. self.defaults_read_form()
  1011. defaults.update(self.defaults)
  1012. # Save update options
  1013. try:
  1014. f = open(self.data_path + "/defaults.json", "w")
  1015. json.dump(defaults, f)
  1016. f.close()
  1017. except:
  1018. self.inform.emit("[error] Failed to write defaults to file.")
  1019. return
  1020. if not silent:
  1021. self.inform.emit("Defaults saved.")
  1022. def on_toggle_shell(self):
  1023. """
  1024. toggle shell if is visible close it if closed open it
  1025. :return:
  1026. """
  1027. if self.ui.shell_dock.isVisible():
  1028. self.ui.shell_dock.hide()
  1029. else:
  1030. self.ui.shell_dock.show()
  1031. def on_edit_join(self):
  1032. """
  1033. Callback for Edit->Join. Joins the selected geometry objects into
  1034. a new one.
  1035. :return: None
  1036. """
  1037. objs = self.collection.get_selected()
  1038. def initialize(obj, app):
  1039. FlatCAMGeometry.merge(objs, obj)
  1040. self.new_object("geometry", "Combo", initialize)
  1041. def on_options_app2project(self):
  1042. """
  1043. Callback for Options->Transfer Options->App=>Project. Copies options
  1044. from application defaults to project defaults.
  1045. :return: None
  1046. """
  1047. self.report_usage("on_options_app2project")
  1048. self.defaults_read_form()
  1049. self.options.update(self.defaults)
  1050. self.options_write_form()
  1051. def on_options_project2app(self):
  1052. """
  1053. Callback for Options->Transfer Options->Project=>App. Copies options
  1054. from project defaults to application defaults.
  1055. :return: None
  1056. """
  1057. self.report_usage("on_options_project2app")
  1058. self.options_read_form()
  1059. self.defaults.update(self.options)
  1060. self.defaults_write_form()
  1061. def on_options_project2object(self):
  1062. """
  1063. Callback for Options->Transfer Options->Project=>Object. Copies options
  1064. from project defaults to the currently selected object.
  1065. :return: None
  1066. """
  1067. self.report_usage("on_options_project2object")
  1068. self.options_read_form()
  1069. obj = self.collection.get_active()
  1070. if obj is None:
  1071. self.inform.emit("WARNING: No object selected.")
  1072. return
  1073. for option in self.options:
  1074. if option.find(obj.kind + "_") == 0:
  1075. oname = option[len(obj.kind)+1:]
  1076. obj.options[oname] = self.options[option]
  1077. obj.to_form() # Update UI
  1078. def on_options_object2project(self):
  1079. """
  1080. Callback for Options->Transfer Options->Object=>Project. Copies options
  1081. from the currently selected object to project defaults.
  1082. :return: None
  1083. """
  1084. self.report_usage("on_options_object2project")
  1085. obj = self.collection.get_active()
  1086. if obj is None:
  1087. self.inform.emit("WARNING: No object selected.")
  1088. return
  1089. obj.read_form()
  1090. for option in obj.options:
  1091. if option in ['name']: # TODO: Handle this better...
  1092. continue
  1093. self.options[obj.kind + "_" + option] = obj.options[option]
  1094. self.options_write_form()
  1095. def on_options_object2app(self):
  1096. """
  1097. Callback for Options->Transfer Options->Object=>App. Copies options
  1098. from the currently selected object to application defaults.
  1099. :return: None
  1100. """
  1101. self.report_usage("on_options_object2app")
  1102. obj = self.collection.get_active()
  1103. if obj is None:
  1104. self.inform.emit("WARNING: No object selected.")
  1105. return
  1106. obj.read_form()
  1107. for option in obj.options:
  1108. if option in ['name']: # TODO: Handle this better...
  1109. continue
  1110. self.defaults[obj.kind + "_" + option] = obj.options[option]
  1111. self.defaults_write_form()
  1112. def on_options_app2object(self):
  1113. """
  1114. Callback for Options->Transfer Options->App=>Object. Copies options
  1115. from application defaults to the currently selected object.
  1116. :return: None
  1117. """
  1118. self.report_usage("on_options_app2object")
  1119. self.defaults_read_form()
  1120. obj = self.collection.get_active()
  1121. if obj is None:
  1122. self.inform.emit("WARNING: No object selected.")
  1123. return
  1124. for option in self.defaults:
  1125. if option.find(obj.kind + "_") == 0:
  1126. oname = option[len(obj.kind)+1:]
  1127. obj.options[oname] = self.defaults[option]
  1128. obj.to_form() # Update UI
  1129. def on_options_dict_change(self, field):
  1130. self.options_write_form_field(field)
  1131. if field == "units":
  1132. self.set_screen_units(self.options['units'])
  1133. def on_defaults_dict_change(self, field):
  1134. self.defaults_write_form_field(field)
  1135. def set_screen_units(self, units):
  1136. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  1137. def on_toggle_units(self):
  1138. """
  1139. Callback for the Units radio-button change in the Options tab.
  1140. Changes the application's default units or the current project's units.
  1141. If changing the project's units, the change propagates to all of
  1142. the objects in the project.
  1143. :return: None
  1144. """
  1145. self.report_usage("on_toggle_units")
  1146. if self.toggle_units_ignore:
  1147. return
  1148. # If option is the same, then ignore
  1149. if self.options_form.units_radio.get_value().upper() == self.options['units'].upper():
  1150. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  1151. return
  1152. # Options to scale
  1153. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1154. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1155. 'excellon_travelz', 'excellon_feedrate', 'excellon_toolchangez', 'excellon_tooldia', 'cncjob_tooldia',
  1156. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1157. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1158. 'geometry_paintmargin']
  1159. def scale_options(sfactor):
  1160. for dim in dimensions:
  1161. self.options[dim] *= sfactor
  1162. # The scaling factor depending on choice of units.
  1163. factor = 1/25.4
  1164. if self.options_form.units_radio.get_value().upper() == 'MM':
  1165. factor = 25.4
  1166. # Changing project units. Warn user.
  1167. msgbox = QtGui.QMessageBox()
  1168. msgbox.setText("<B>Change project units ...</B>")
  1169. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  1170. "properties of all objects to be scaled accordingly. Continue?")
  1171. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1172. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1173. response = msgbox.exec_()
  1174. if response == QtGui.QMessageBox.Ok:
  1175. self.options_read_form()
  1176. scale_options(factor)
  1177. self.options_write_form()
  1178. for obj in self.collection.get_list():
  1179. units = self.options_form.units_radio.get_value().upper()
  1180. obj.convert_units(units)
  1181. current = self.collection.get_active()
  1182. if current is not None:
  1183. current.to_form()
  1184. self.plot_all()
  1185. else:
  1186. # Undo toggling
  1187. self.toggle_units_ignore = True
  1188. if self.options_form.units_radio.get_value().upper() == 'MM':
  1189. self.options_form.units_radio.set_value('IN')
  1190. else:
  1191. self.options_form.units_radio.set_value('MM')
  1192. self.toggle_units_ignore = False
  1193. self.options_read_form()
  1194. self.inform.emit("Converted units to %s" % self.options["units"])
  1195. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1196. self.set_screen_units(self.options["units"])
  1197. def on_options_combo_change(self, sel):
  1198. """
  1199. Called when the combo box to choose between application defaults and
  1200. project option changes value. The corresponding variables are
  1201. copied to the UI.
  1202. :param sel: The option index that was chosen.
  1203. :return: None
  1204. """
  1205. # combo_sel = self.ui.notebook.combo_options.get_active()
  1206. App.log.debug("Options --> %s" % sel)
  1207. # Remove anything else in the box
  1208. # box_children = self.options_box.get_children()
  1209. # box_children = self.ui.notebook.options_contents.get_children()
  1210. # for child in box_children:
  1211. # self.ui.notebook.options_contents.remove(child)
  1212. # try:
  1213. # self.ui.options_area.removeWidget(self.defaults_form)
  1214. # except:
  1215. # pass
  1216. #
  1217. # try:
  1218. # self.ui.options_area.removeWidget(self.options_form)
  1219. # except:
  1220. # pass
  1221. form = [self.defaults_form, self.options_form][sel]
  1222. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  1223. try:
  1224. self.ui.options_scroll_area.takeWidget()
  1225. except:
  1226. self.log.debug("Nothing to remove")
  1227. self.ui.options_scroll_area.setWidget(form)
  1228. form.show()
  1229. # self.options2form()
  1230. def on_delete(self):
  1231. """
  1232. Delete the currently selected FlatCAMObjs.
  1233. :return: None
  1234. """
  1235. self.log.debug("on_delete()")
  1236. self.report_usage("on_delete")
  1237. while (self.collection.get_active()):
  1238. self.delete_first_selected()
  1239. def delete_first_selected(self):
  1240. # Keep this for later
  1241. try:
  1242. name = self.collection.get_active().options["name"]
  1243. except AttributeError:
  1244. self.log.debug("Nothing selected for deletion")
  1245. return
  1246. # Remove plot
  1247. self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  1248. self.plotcanvas.auto_adjust_axes()
  1249. # Clear form
  1250. self.setup_component_editor()
  1251. # Remove from dictionary
  1252. self.collection.delete_active()
  1253. self.inform.emit("Object deleted: %s" % name)
  1254. def on_plots_updated(self):
  1255. """
  1256. Callback used to report when the plots have changed.
  1257. Adjust axes and zooms to fit.
  1258. :return: None
  1259. """
  1260. self.plotcanvas.auto_adjust_axes()
  1261. self.on_zoom_fit(None)
  1262. def on_toolbar_replot(self):
  1263. """
  1264. Callback for toolbar button. Re-plots all objects.
  1265. :return: None
  1266. """
  1267. self.report_usage("on_toolbar_replot")
  1268. self.log.debug("on_toolbar_replot()")
  1269. try:
  1270. self.collection.get_active().read_form()
  1271. except AttributeError:
  1272. self.log.debug("on_toolbar_replot(): AttributeError")
  1273. pass
  1274. self.plot_all()
  1275. def on_row_activated(self, index):
  1276. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1277. def on_object_created(self, obj):
  1278. """
  1279. Event callback for object creation.
  1280. :param obj: The newly created FlatCAM object.
  1281. :return: None
  1282. """
  1283. t0 = time.time() # DEBUG
  1284. self.log.debug("on_object_created()")
  1285. # The Collection might change the name if there is a collision
  1286. self.collection.append(obj)
  1287. self.inform.emit("Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1288. self.new_object_available.emit(obj)
  1289. obj.plot()
  1290. self.on_zoom_fit(None)
  1291. t1 = time.time() # DEBUG
  1292. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1293. def on_zoom_fit(self, event):
  1294. """
  1295. Callback for zoom-out request. This can be either from the corresponding
  1296. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  1297. with axes limits from the geometry bounds of all objects.
  1298. :param event: Ignored.
  1299. :return: None
  1300. """
  1301. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  1302. width = xmax - xmin
  1303. height = ymax - ymin
  1304. xmin -= 0.05 * width
  1305. xmax += 0.05 * width
  1306. ymin -= 0.05 * height
  1307. ymax += 0.05 * height
  1308. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  1309. def on_key_over_plot(self, event):
  1310. """
  1311. Callback for the key pressed event when the canvas is focused. Keyboard
  1312. shortcuts are handled here. So far, these are the shortcuts:
  1313. ========== ============================================
  1314. Key Action
  1315. ========== ============================================
  1316. '1' Zoom-fit. Fits the axes limits to the data.
  1317. '2' Zoom-out.
  1318. '3' Zoom-in.
  1319. 'm' Toggle on-off the measuring tool.
  1320. ========== ============================================
  1321. :param event: Ignored.
  1322. :return: None
  1323. """
  1324. if event.key == self.defaults['fit_key']: # 1
  1325. self.on_zoom_fit(None)
  1326. return
  1327. if event.key == self.defaults['zoom_out_key']: # 2
  1328. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  1329. return
  1330. if event.key == self.defaults['zoom_in_key']: # 3
  1331. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  1332. return
  1333. # if event.key == 'm':
  1334. # if self.measure.toggle_active():
  1335. # self.inform.emit("Measuring tool ON")
  1336. # else:
  1337. # self.inform.emit("Measuring tool OFF")
  1338. # return
  1339. def on_click_over_plot(self, event):
  1340. """
  1341. Callback for the mouse click event over the plot. This event is generated
  1342. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1343. For details, see: http://matplotlib.org/users/event_handling.html
  1344. Default actions are:
  1345. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  1346. :param event: Contains information about the event, like which button
  1347. was clicked, the pixel coordinates and the axes coordinates.
  1348. :return: None
  1349. """
  1350. # So it can receive key presses
  1351. self.plotcanvas.canvas.setFocus()
  1352. try:
  1353. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  1354. event.button, event.x, event.y, event.xdata, event.ydata))
  1355. self.clipboard.setText(self.defaults["point_clipboard_format"] % (event.xdata, event.ydata))
  1356. except Exception as e:
  1357. App.log.debug("Outside plot?")
  1358. App.log.debug(str(e))
  1359. def on_mouse_move_over_plot(self, event):
  1360. """
  1361. Callback for the mouse motion event over the plot. This event is generated
  1362. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1363. For details, see: http://matplotlib.org/users/event_handling.html
  1364. :param event: Contains information about the event.
  1365. :return: None
  1366. """
  1367. try: # May fail in case mouse not within axes
  1368. self.ui.position_label.setText("X: %.4f Y: %.4f" % (
  1369. event.xdata, event.ydata))
  1370. self.mouse = [event.xdata, event.ydata]
  1371. except:
  1372. self.ui.position_label.setText("")
  1373. self.mouse = None
  1374. def on_file_new(self):
  1375. """
  1376. Callback for menu item File->New. Returns the application to its
  1377. startup state. This method is thread-safe.
  1378. :return: None
  1379. """
  1380. self.report_usage("on_file_new")
  1381. # Remove everything from memory
  1382. App.log.debug("on_file_new()")
  1383. self.plotcanvas.clear()
  1384. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  1385. self.init_tcl()
  1386. self.collection.delete_all()
  1387. self.setup_component_editor()
  1388. # Clear project filename
  1389. self.project_filename = None
  1390. # Re-fresh project options
  1391. self.on_options_app2project()
  1392. def on_fileopengerber(self):
  1393. """
  1394. File menu callback for opening a Gerber.
  1395. :return: None
  1396. """
  1397. self.report_usage("on_fileopengerber")
  1398. App.log.debug("on_fileopengerber()")
  1399. try:
  1400. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber",
  1401. directory=self.get_last_folder())
  1402. except TypeError:
  1403. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber")
  1404. # The Qt methods above will return a QString which can cause problems later.
  1405. # So far json.dump() will fail to serialize it.
  1406. # TODO: Improve the serialization methods and remove this fix.
  1407. filename = str(filename)
  1408. if filename == "":
  1409. self.inform.emit("Open cancelled.")
  1410. else:
  1411. self.worker_task.emit({'fcn': self.open_gerber,
  1412. 'params': [filename]})
  1413. def on_fileopenexcellon(self):
  1414. """
  1415. File menu callback for opening an Excellon file.
  1416. :return: None
  1417. """
  1418. self.report_usage("on_fileopenexcellon")
  1419. App.log.debug("on_fileopenexcellon()")
  1420. try:
  1421. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon",
  1422. directory=self.get_last_folder())
  1423. except TypeError:
  1424. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon")
  1425. # The Qt methods above will return a QString which can cause problems later.
  1426. # So far json.dump() will fail to serialize it.
  1427. # TODO: Improve the serialization methods and remove this fix.
  1428. filename = str(filename)
  1429. if filename == "":
  1430. self.inform.emit("Open cancelled.")
  1431. else:
  1432. self.worker_task.emit({'fcn': self.open_excellon,
  1433. 'params': [filename]})
  1434. def on_fileopengcode(self):
  1435. """
  1436. File menu call back for opening gcode.
  1437. :return: None
  1438. """
  1439. self.report_usage("on_fileopengcode")
  1440. App.log.debug("on_fileopengcode()")
  1441. try:
  1442. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code",
  1443. directory=self.get_last_folder())
  1444. except TypeError:
  1445. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code")
  1446. # The Qt methods above will return a QString which can cause problems later.
  1447. # So far json.dump() will fail to serialize it.
  1448. # TODO: Improve the serialization methods and remove this fix.
  1449. filename = str(filename)
  1450. if filename == "":
  1451. self.inform.emit("Open cancelled.")
  1452. else:
  1453. self.worker_task.emit({'fcn': self.open_gcode,
  1454. 'params': [filename]})
  1455. def on_file_openproject(self):
  1456. """
  1457. File menu callback for opening a project.
  1458. :return: None
  1459. """
  1460. self.report_usage("on_file_openproject")
  1461. App.log.debug("on_file_openproject()")
  1462. try:
  1463. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project",
  1464. directory=self.get_last_folder())
  1465. except TypeError:
  1466. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project")
  1467. # The Qt methods above will return a QString which can cause problems later.
  1468. # So far json.dump() will fail to serialize it.
  1469. # TODO: Improve the serialization methods and remove this fix.
  1470. filename = str(filename)
  1471. if filename == "":
  1472. self.inform.emit("Open cancelled.")
  1473. else:
  1474. # self.worker_task.emit({'fcn': self.open_project,
  1475. # 'params': [filename]})
  1476. # The above was failing because open_project() is not
  1477. # thread safe. The new_project()
  1478. self.open_project(filename)
  1479. def on_file_exportsvg(self):
  1480. """
  1481. Callback for menu item File->Export SVG.
  1482. :return: None
  1483. """
  1484. self.report_usage("on_file_exportsvg")
  1485. App.log.debug("on_file_exportsvg()")
  1486. obj = self.collection.get_active()
  1487. if obj is None:
  1488. self.inform.emit("WARNING: No object selected.")
  1489. msg = "Please Select a Geometry object to export"
  1490. msgbox = QtGui.QMessageBox()
  1491. msgbox.setInformativeText(msg)
  1492. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1493. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1494. msgbox.exec_()
  1495. return
  1496. # Check for more compatible types and add as required
  1497. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  1498. and not isinstance(obj, FlatCAMExcellon)):
  1499. msg = "ERROR: Only Geometry, Gerber and CNCJob objects can be used."
  1500. msgbox = QtGui.QMessageBox()
  1501. msgbox.setInformativeText(msg)
  1502. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1503. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1504. msgbox.exec_()
  1505. return
  1506. name = self.collection.get_active().options["name"]
  1507. try:
  1508. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG",
  1509. directory=self.get_last_folder(), filter="*.svg")
  1510. except TypeError:
  1511. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG")
  1512. filename = str(filename)
  1513. if filename == "":
  1514. self.inform.emit("Export SVG cancelled.")
  1515. return
  1516. else:
  1517. self.export_svg(name, filename)
  1518. def on_file_importsvg(self):
  1519. """
  1520. Callback for menu item File->Import SVG.
  1521. :return: None
  1522. """
  1523. self.report_usage("on_file_importsvg")
  1524. App.log.debug("on_file_importsvg()")
  1525. try:
  1526. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG",
  1527. directory=self.get_last_folder())
  1528. except TypeError:
  1529. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG")
  1530. filename = str(filename)
  1531. if filename == "":
  1532. self.inform.emit("Open cancelled.")
  1533. else:
  1534. self.worker_task.emit({'fcn': self.import_svg,
  1535. 'params': [filename]})
  1536. def on_file_saveproject(self):
  1537. """
  1538. Callback for menu item File->Save Project. Saves the project to
  1539. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1540. if set to None. The project is saved by calling ``self.save_project()``.
  1541. :return: None
  1542. """
  1543. self.report_usage("on_file_saveproject")
  1544. if self.project_filename is None:
  1545. self.on_file_saveprojectas()
  1546. else:
  1547. self.save_project(self.project_filename)
  1548. self.file_opened.emit("project", self.project_filename)
  1549. self.inform.emit("Project saved to: " + self.project_filename)
  1550. def on_file_saveprojectas(self, make_copy=False):
  1551. """
  1552. Callback for menu item File->Save Project As... Opens a file
  1553. chooser and saves the project to the given file via
  1554. ``self.save_project()``.
  1555. :return: None
  1556. """
  1557. self.report_usage("on_file_saveprojectas")
  1558. try:
  1559. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...",
  1560. directory=self.get_last_folder())
  1561. except TypeError:
  1562. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...")
  1563. filename = str(filename)
  1564. try:
  1565. f = open(filename, 'r')
  1566. f.close()
  1567. exists = True
  1568. except IOError:
  1569. exists = False
  1570. msg = "File exists. Overwrite?"
  1571. if exists:
  1572. msgbox = QtGui.QMessageBox()
  1573. msgbox.setInformativeText(msg)
  1574. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1575. msgbox.setDefaultButton(QtGui.QMessageBox.Cancel)
  1576. result = msgbox.exec_()
  1577. if result == QtGui.QMessageBox.Cancel:
  1578. return
  1579. self.save_project(filename)
  1580. self.file_opened.emit("project", filename)
  1581. if not make_copy:
  1582. self.project_filename = filename
  1583. self.inform.emit("Project saved to: " + self.project_filename)
  1584. else:
  1585. self.inform.emit("Project copy saved to: " + self.project_filename)
  1586. def export_svg(self, obj_name, filename, scale_factor=0.00):
  1587. """
  1588. Exports a Geometry Object to an SVG file.
  1589. :param filename: Path to the SVG file to save to.
  1590. :return:
  1591. """
  1592. self.log.debug("export_svg()")
  1593. try:
  1594. obj = self.collection.get_by_name(str(obj_name))
  1595. except:
  1596. # TODO: The return behavior has not been established... should raise exception?
  1597. return "Could not retrieve object: %s" % obj_name
  1598. with self.proc_container.new("Exporting SVG") as proc:
  1599. exported_svg = obj.export_svg(scale_factor=scale_factor)
  1600. # Determine bounding area for svg export
  1601. bounds = obj.bounds()
  1602. size = obj.size()
  1603. # Convert everything to strings for use in the xml doc
  1604. svgwidth = str(size[0])
  1605. svgheight = str(size[1])
  1606. minx = str(bounds[0])
  1607. miny = str(bounds[1] - size[1])
  1608. uom = obj.units.lower()
  1609. # Add a SVG Header and footer to the svg output from shapely
  1610. # The transform flips the Y Axis so that everything renders
  1611. # properly within svg apps such as inkscape
  1612. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  1613. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  1614. svg_header += 'width="' + svgwidth + uom + '" '
  1615. svg_header += 'height="' + svgheight + uom + '" '
  1616. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  1617. svg_header += '<g transform="scale(1,-1)">'
  1618. svg_footer = '</g> </svg>'
  1619. svg_elem = svg_header + exported_svg + svg_footer
  1620. # Parse the xml through a xml parser just to add line feeds
  1621. # and to make it look more pretty for the output
  1622. doc = parse_xml_string(svg_elem)
  1623. with open(filename, 'w') as fp:
  1624. fp.write(doc.toprettyxml())
  1625. def import_svg(self, filename, outname=None):
  1626. """
  1627. Adds a new Geometry Object to the projects and populates
  1628. it with shapes extracted from the SVG file.
  1629. :param filename: Path to the SVG file.
  1630. :param outname:
  1631. :return:
  1632. """
  1633. def obj_init(geo_obj, app_obj):
  1634. geo_obj.import_svg(filename)
  1635. with self.proc_container.new("Importing SVG") as proc:
  1636. # Object name
  1637. name = outname or filename.split('/')[-1].split('\\')[-1]
  1638. self.new_object("geometry", name, obj_init)
  1639. # Register recent file
  1640. self.file_opened.emit("svg", filename)
  1641. # GUI feedback
  1642. self.inform.emit("Opened: " + filename)
  1643. def open_gerber(self, filename, follow=False, outname=None):
  1644. """
  1645. Opens a Gerber file, parses it and creates a new object for
  1646. it in the program. Thread-safe.
  1647. :param outname: Name of the resulting object. None causes the
  1648. name to be that of the file.
  1649. :param filename: Gerber file filename
  1650. :type filename: str
  1651. :param follow: If true, the parser will not create polygons, just lines
  1652. following the gerber path.
  1653. :type follow: bool
  1654. :return: None
  1655. """
  1656. # How the object should be initialized
  1657. def obj_init(gerber_obj, app_obj):
  1658. assert isinstance(gerber_obj, FlatCAMGerber), \
  1659. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  1660. # Opening the file happens here
  1661. self.progress.emit(30)
  1662. try:
  1663. gerber_obj.parse_file(filename, follow=follow)
  1664. except IOError:
  1665. app_obj.inform.emit("[error] Failed to open file: " + filename)
  1666. app_obj.progress.emit(0)
  1667. raise IOError('Failed to open file: ' + filename)
  1668. except ParseError as e:
  1669. app_obj.inform.emit("[error] Failed to parse file: " + filename + ". " + e[0])
  1670. app_obj.progress.emit(0)
  1671. self.log.error(str(e))
  1672. raise
  1673. except:
  1674. msg = "[error] An internal error has ocurred. See shell.\n"
  1675. msg += traceback.format_exc()
  1676. app_obj.inform.emit(msg)
  1677. raise
  1678. if gerber_obj.is_empty():
  1679. app_obj.inform.emit("[error] No geometry found in file: " + filename)
  1680. self.collection.set_active(gerber_obj.options["name"])
  1681. self.collection.delete_active()
  1682. # Further parsing
  1683. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  1684. App.log.debug("open_gerber()")
  1685. with self.proc_container.new("Opening Gerber") as proc:
  1686. self.progress.emit(10)
  1687. # Object name
  1688. name = outname or filename.split('/')[-1].split('\\')[-1]
  1689. ### Object creation ###
  1690. self.new_object("gerber", name, obj_init)
  1691. # Register recent file
  1692. self.file_opened.emit("gerber", filename)
  1693. self.progress.emit(100)
  1694. #proc.done()
  1695. # GUI feedback
  1696. self.inform.emit("Opened: " + filename)
  1697. def open_excellon(self, filename, outname=None):
  1698. """
  1699. Opens an Excellon file, parses it and creates a new object for
  1700. it in the program. Thread-safe.
  1701. :param outname: Name of the resulting object. None causes the
  1702. name to be that of the file.
  1703. :param filename: Excellon file filename
  1704. :type filename: str
  1705. :return: None
  1706. """
  1707. App.log.debug("open_excellon()")
  1708. #self.progress.emit(10)
  1709. # How the object should be initialized
  1710. def obj_init(excellon_obj, app_obj):
  1711. #self.progress.emit(20)
  1712. try:
  1713. excellon_obj.parse_file(filename)
  1714. except IOError:
  1715. app_obj.inform.emit("[error] Cannot open file: " + filename)
  1716. self.progress.emit(0) # TODO: self and app_bjj mixed
  1717. raise IOError("Cannot open file: " + filename)
  1718. except:
  1719. msg = "[error] An internal error has ocurred. See shell.\n"
  1720. msg += traceback.format_exc()
  1721. app_obj.inform.emit(msg)
  1722. raise
  1723. try:
  1724. excellon_obj.create_geometry()
  1725. except:
  1726. msg = "[error] An internal error has ocurred. See shell.\n"
  1727. msg += traceback.format_exc()
  1728. app_obj.inform.emit(msg)
  1729. raise
  1730. if excellon_obj.is_empty():
  1731. app_obj.inform.emit("[error] No geometry found in file: " + filename)
  1732. self.collection.set_active(excellon_obj.options["name"])
  1733. self.collection.delete_active()
  1734. #self.progress.emit(70)
  1735. with self.proc_container.new("Opening Excellon."):
  1736. # Object name
  1737. name = outname or filename.split('/')[-1].split('\\')[-1]
  1738. self.new_object("excellon", name, obj_init)
  1739. # Register recent file
  1740. self.file_opened.emit("excellon", filename)
  1741. # GUI feedback
  1742. self.inform.emit("Opened: " + filename)
  1743. #self.progress.emit(100)
  1744. def open_gcode(self, filename, outname=None):
  1745. """
  1746. Opens a G-gcode file, parses it and creates a new object for
  1747. it in the program. Thread-safe.
  1748. :param outname: Name of the resulting object. None causes the
  1749. name to be that of the file.
  1750. :param filename: G-code file filename
  1751. :type filename: str
  1752. :return: None
  1753. """
  1754. App.log.debug("open_gcode()")
  1755. # How the object should be initialized
  1756. def obj_init(job_obj, app_obj_):
  1757. """
  1758. :type app_obj_: App
  1759. """
  1760. assert isinstance(app_obj_, App), \
  1761. "Initializer expected App, got %s" % type(app_obj_)
  1762. self.progress.emit(10)
  1763. try:
  1764. f = open(filename)
  1765. gcode = f.read()
  1766. f.close()
  1767. except IOError:
  1768. app_obj_.inform.emit("[error] Failed to open " + filename)
  1769. self.progress.emit(0)
  1770. raise IOError("Failed to open " + filename)
  1771. job_obj.gcode = gcode
  1772. self.progress.emit(20)
  1773. job_obj.gcode_parse()
  1774. self.progress.emit(60)
  1775. job_obj.create_geometry()
  1776. with self.proc_container.new("Opening G-Code."):
  1777. # Object name
  1778. name = outname or filename.split('/')[-1].split('\\')[-1]
  1779. # New object creation and file processing
  1780. try:
  1781. self.new_object("cncjob", name, obj_init)
  1782. except Exception as e:
  1783. # e = sys.exc_info()
  1784. App.log.error(str(e))
  1785. self.message_dialog("Failed to create CNCJob Object",
  1786. "Attempting to create a FlatCAM CNCJob Object from " +
  1787. "G-Code file failed during processing:\n" +
  1788. str(e[0]) + " " + str(e[1]), kind="error")
  1789. self.progress.emit(0)
  1790. self.collection.delete_active()
  1791. raise e
  1792. # Register recent file
  1793. self.file_opened.emit("cncjob", filename)
  1794. # GUI feedback
  1795. self.inform.emit("Opened: " + filename)
  1796. self.progress.emit(100)
  1797. def open_project(self, filename):
  1798. """
  1799. Loads a project from the specified file.
  1800. 1) Loads and parses file
  1801. 2) Registers the file as recently opened.
  1802. 3) Calls on_file_new()
  1803. 4) Updates options
  1804. 5) Calls new_object() with the object's from_dict() as init method.
  1805. 6) Calls plot_all()
  1806. :param filename: Name of the file from which to load.
  1807. :type filename: str
  1808. :return: None
  1809. """
  1810. App.log.debug("Opening project: " + filename)
  1811. ## Open and parse
  1812. try:
  1813. f = open(filename, 'r')
  1814. except IOError:
  1815. App.log.error("Failed to open project file: %s" % filename)
  1816. self.inform.emit("[error] Failed to open project file: %s" % filename)
  1817. return
  1818. try:
  1819. d = json.load(f, object_hook=dict2obj)
  1820. except:
  1821. App.log.error("Failed to parse project file: %s" % filename)
  1822. self.inform.emit("[error] Failed to parse project file: %s" % filename)
  1823. f.close()
  1824. return
  1825. self.file_opened.emit("project", filename)
  1826. ## Clear the current project
  1827. ## NOT THREAD SAFE ##
  1828. self.on_file_new()
  1829. ##Project options
  1830. self.options.update(d['options'])
  1831. self.project_filename = filename
  1832. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1833. self.set_screen_units(self.options["units"])
  1834. ## Re create objects
  1835. App.log.debug("Re-creating objects...")
  1836. for obj in d['objs']:
  1837. def obj_init(obj_inst, app_inst):
  1838. obj_inst.from_dict(obj)
  1839. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  1840. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=False)
  1841. self.plot_all()
  1842. self.inform.emit("Project loaded from: " + filename)
  1843. App.log.debug("Project loaded")
  1844. def propagate_defaults(self):
  1845. """
  1846. This method is used to set default values in classes. It's
  1847. an alternative to project options but allows the use
  1848. of values invisible to the user.
  1849. :return: None
  1850. """
  1851. self.log.debug("propagate_defaults()")
  1852. # Which objects to update the given parameters.
  1853. routes = {
  1854. "zdownrate": CNCjob,
  1855. "excellon_zeros": Excellon,
  1856. "gerber_use_buffer_for_union": Gerber,
  1857. "cncjob_coordinate_format": CNCjob
  1858. # "spindlespeed": CNCjob
  1859. }
  1860. for param in routes:
  1861. if param in routes[param].defaults:
  1862. try:
  1863. routes[param].defaults[param] = self.defaults[param]
  1864. self.log.debug(" " + param + " OK")
  1865. except KeyError:
  1866. self.log.debug(" ERROR: " + param + " not in defaults.")
  1867. else:
  1868. # Try extracting the name:
  1869. # classname_param here is param in the object
  1870. if param.find(routes[param].__name__.lower() + "_") == 0:
  1871. p = param[len(routes[param].__name__) + 1:]
  1872. if p in routes[param].defaults:
  1873. routes[param].defaults[p] = self.defaults[param]
  1874. self.log.debug(" " + param + " OK!")
  1875. def restore_main_win_geom(self):
  1876. self.ui.setGeometry(self.defaults["def_win_x"],
  1877. self.defaults["def_win_y"],
  1878. self.defaults["def_win_w"],
  1879. self.defaults["def_win_h"])
  1880. def plot_all(self):
  1881. """
  1882. Re-generates all plots from all objects.
  1883. :return: None
  1884. """
  1885. self.log.debug("plot_all()")
  1886. self.plotcanvas.clear()
  1887. self.progress.emit(10)
  1888. def worker_task(app_obj):
  1889. percentage = 0.1
  1890. try:
  1891. delta = 0.9 / len(self.collection.get_list())
  1892. except ZeroDivisionError:
  1893. self.progress.emit(0)
  1894. return
  1895. for obj in self.collection.get_list():
  1896. obj.plot()
  1897. percentage += delta
  1898. self.progress.emit(int(percentage*100))
  1899. self.progress.emit(0)
  1900. self.plots_updated.emit()
  1901. # Send to worker
  1902. #self.worker.add_task(worker_task, [self])
  1903. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  1904. def register_folder(self, filename):
  1905. self.defaults["last_folder"] = os.path.split(str(filename))[0]
  1906. def set_progress_bar(self, percentage, text=""):
  1907. self.ui.progress_bar.setValue(int(percentage))
  1908. def setup_shell(self):
  1909. """
  1910. Creates shell functions. Runs once at startup.
  1911. :return: None
  1912. """
  1913. self.log.debug("setup_shell()")
  1914. def shelp(p=None):
  1915. if not p:
  1916. return "Available commands:\n" + \
  1917. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  1918. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  1919. if p not in commands:
  1920. return "Unknown command: %s" % p
  1921. return commands[p]["help"]
  1922. # --- Migrated to new architecture ---
  1923. # def options(name):
  1924. # ops = self.collection.get_by_name(str(name)).options
  1925. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  1926. def h(*args):
  1927. """
  1928. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  1929. and standalone parameters into list.
  1930. """
  1931. kwa = {}
  1932. a = []
  1933. n = len(args)
  1934. name = None
  1935. for i in range(n):
  1936. match = re.search(r'^-([a-zA-Z].*)', args[i])
  1937. if match:
  1938. assert name is None
  1939. name = match.group(1)
  1940. continue
  1941. if name is None:
  1942. a.append(args[i])
  1943. else:
  1944. kwa[name] = args[i]
  1945. name = None
  1946. return a, kwa
  1947. @contextmanager
  1948. def wait_signal(signal, timeout=10000):
  1949. """
  1950. Block loop until signal emitted, timeout (ms) elapses
  1951. or unhandled exception happens in a thread.
  1952. :param signal: Signal to wait for.
  1953. """
  1954. loop = QtCore.QEventLoop()
  1955. # Normal termination
  1956. signal.connect(loop.quit)
  1957. # Termination by exception in thread
  1958. self.thread_exception.connect(loop.quit)
  1959. status = {'timed_out': False}
  1960. def report_quit():
  1961. status['timed_out'] = True
  1962. loop.quit()
  1963. yield
  1964. # Temporarily change how exceptions are managed.
  1965. oeh = sys.excepthook
  1966. ex = []
  1967. def except_hook(type_, value, traceback_):
  1968. ex.append(value)
  1969. oeh(type_, value, traceback_)
  1970. sys.excepthook = except_hook
  1971. # Terminate on timeout
  1972. if timeout is not None:
  1973. QtCore.QTimer.singleShot(timeout, report_quit)
  1974. #### Block ####
  1975. loop.exec_()
  1976. # Restore exception management
  1977. sys.excepthook = oeh
  1978. if ex:
  1979. self.raiseTclError(str(ex[0]))
  1980. if status['timed_out']:
  1981. raise Exception('Timed out!')
  1982. # def wait_signal2(signal, timeout=10000):
  1983. # """Block loop until signal emitted, or timeout (ms) elapses."""
  1984. # loop = QtCore.QEventLoop()
  1985. # signal.connect(loop.quit)
  1986. # status = {'timed_out': False}
  1987. #
  1988. # def report_quit():
  1989. # status['timed_out'] = True
  1990. # loop.quit()
  1991. #
  1992. # if timeout is not None:
  1993. # QtCore.QTimer.singleShot(timeout, report_quit)
  1994. # loop.exec_()
  1995. #
  1996. # if status['timed_out']:
  1997. # raise Exception('Timed out!')
  1998. # def mytest(*args):
  1999. # to = int(args[0])
  2000. #
  2001. # try:
  2002. # for rec in self.recent:
  2003. # if rec['kind'] == 'gerber':
  2004. # self.open_gerber(str(rec['filename']))
  2005. # break
  2006. #
  2007. # basename = self.collection.get_names()[0]
  2008. # isolate(basename, '-passes', '10', '-combine', '1')
  2009. # iso = self.collection.get_by_name(basename + "_iso")
  2010. #
  2011. # with wait_signal(self.new_object_available, to):
  2012. # iso.generatecncjob()
  2013. # # iso.generatecncjob()
  2014. # # wait_signal2(self.new_object_available, to)
  2015. #
  2016. # return str(self.collection.get_names())
  2017. #
  2018. # except Exception as e:
  2019. # return str(e)
  2020. #
  2021. # def mytest2(*args):
  2022. # to = int(args[0])
  2023. #
  2024. # for rec in self.recent:
  2025. # if rec['kind'] == 'gerber':
  2026. # self.open_gerber(str(rec['filename']))
  2027. # break
  2028. #
  2029. # basename = self.collection.get_names()[0]
  2030. # isolate(basename, '-passes', '10', '-combine', '1')
  2031. # iso = self.collection.get_by_name(basename + "_iso")
  2032. #
  2033. # with wait_signal(self.new_object_available, to):
  2034. # 1/0 # Force exception
  2035. # iso.generatecncjob()
  2036. #
  2037. # return str(self.collection.get_names())
  2038. #
  2039. # def mytest3(*args):
  2040. # to = int(args[0])
  2041. #
  2042. # def sometask(*args):
  2043. # time.sleep(2)
  2044. # self.inform.emit("mytest3")
  2045. #
  2046. # with wait_signal(self.inform, to):
  2047. # self.worker_task.emit({'fcn': sometask, 'params': []})
  2048. #
  2049. # return "mytest3 done"
  2050. #
  2051. # def mytest4(*args):
  2052. # to = int(args[0])
  2053. #
  2054. # def sometask(*args):
  2055. # time.sleep(2)
  2056. # 1/0 # Force exception
  2057. # self.inform.emit("mytest4")
  2058. #
  2059. # with wait_signal(self.inform, to):
  2060. # self.worker_task.emit({'fcn': sometask, 'params': []})
  2061. #
  2062. # return "mytest3 done"
  2063. # --- Migrated to new architecture ---
  2064. # def export_svg(name, filename, *args):
  2065. # a, kwa = h(*args)
  2066. # types = {'scale_factor': float}
  2067. #
  2068. # for key in kwa:
  2069. # if key not in types:
  2070. # return 'Unknown parameter: %s' % key
  2071. # kwa[key] = types[key](kwa[key])
  2072. #
  2073. # self.export_svg(str(name), str(filename), **kwa)
  2074. # --- Migrated to new architecture ---
  2075. # def import_svg(filename, *args):
  2076. # a, kwa = h(*args)
  2077. # types = {'outname': str}
  2078. #
  2079. # for key in kwa:
  2080. # if key not in types:
  2081. # return 'Unknown parameter: %s' % key
  2082. # kwa[key] = types[key](kwa[key])
  2083. #
  2084. # self.import_svg(str(filename), **kwa)
  2085. # --- Migrated to new architecture
  2086. # def open_gerber(filename, *args):
  2087. # a, kwa = h(*args)
  2088. # types = {'follow': bool,
  2089. # 'outname': str}
  2090. #
  2091. # for key in kwa:
  2092. # if key not in types:
  2093. # return 'Unknown parameter: %s' % key
  2094. # kwa[key] = types[key](kwa[key])
  2095. #
  2096. # self.open_gerber(str(filename), **kwa)
  2097. # --- Migrated to new architecture ---
  2098. # def open_excellon(filename, *args):
  2099. # a, kwa = h(*args)
  2100. # types = {'outname': str}
  2101. #
  2102. # for key in kwa:
  2103. # if key not in types:
  2104. # return 'Unknown parameter: %s' % key
  2105. # kwa[key] = types[key](kwa[key])
  2106. #
  2107. # self.open_excellon(str(filename), **kwa)
  2108. # --- Migrated to new architecture ---
  2109. # def open_gcode(filename, *args):
  2110. # a, kwa = h(*args)
  2111. # types = {'outname': str}
  2112. #
  2113. # for key in kwa:
  2114. # if key not in types:
  2115. # return 'Unknown parameter: %s' % key
  2116. # kwa[key] = types[key](kwa[key])
  2117. #
  2118. # self.open_gcode(str(filename), **kwa)
  2119. # def cutout(name, *args):
  2120. # a, kwa = h(*args)
  2121. # types = {'dia': float,
  2122. # 'margin': float,
  2123. # 'gapsize': float,
  2124. # 'gaps': str}
  2125. #
  2126. # for key in kwa:
  2127. # if key not in types:
  2128. # return 'Unknown parameter: %s' % key
  2129. # kwa[key] = types[key](kwa[key])
  2130. #
  2131. # try:
  2132. # obj = self.collection.get_by_name(str(name))
  2133. # except:
  2134. # return "Could not retrieve object: %s" % name
  2135. #
  2136. # def geo_init_me(geo_obj, app_obj):
  2137. # margin = kwa['margin'] + kwa['dia'] / 2
  2138. # gap_size = kwa['dia'] + kwa['gapsize']
  2139. # minx, miny, maxx, maxy = obj.bounds()
  2140. # minx -= margin
  2141. # maxx += margin
  2142. # miny -= margin
  2143. # maxy += margin
  2144. # midx = 0.5 * (minx + maxx)
  2145. # midy = 0.5 * (miny + maxy)
  2146. # hgap = 0.5 * gap_size
  2147. # pts = [[midx - hgap, maxy],
  2148. # [minx, maxy],
  2149. # [minx, midy + hgap],
  2150. # [minx, midy - hgap],
  2151. # [minx, miny],
  2152. # [midx - hgap, miny],
  2153. # [midx + hgap, miny],
  2154. # [maxx, miny],
  2155. # [maxx, midy - hgap],
  2156. # [maxx, midy + hgap],
  2157. # [maxx, maxy],
  2158. # [midx + hgap, maxy]]
  2159. # cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  2160. # [pts[6], pts[7], pts[10], pts[11]]],
  2161. # "lr": [[pts[9], pts[10], pts[1], pts[2]],
  2162. # [pts[3], pts[4], pts[7], pts[8]]],
  2163. # "4": [[pts[0], pts[1], pts[2]],
  2164. # [pts[3], pts[4], pts[5]],
  2165. # [pts[6], pts[7], pts[8]],
  2166. # [pts[9], pts[10], pts[11]]]}
  2167. # cuts = cases[kwa['gaps']]
  2168. # geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  2169. #
  2170. # try:
  2171. # obj.app.new_object("geometry", name + "_cutout", geo_init_me)
  2172. # except Exception, e:
  2173. # return "Operation failed: %s" % str(e)
  2174. #
  2175. # return 'Ok'
  2176. # --- Migrated to new architecture ---
  2177. # def geocutout(name=None, *args):
  2178. # """
  2179. # TCL shell command - see help section
  2180. #
  2181. # Subtract gaps from geometry, this will not create new object
  2182. #
  2183. # :param name: name of object
  2184. # :param args: array of arguments
  2185. # :return: "Ok" if completed without errors
  2186. # """
  2187. #
  2188. # try:
  2189. # a, kwa = h(*args)
  2190. # types = {'dia': float,
  2191. # 'gapsize': float,
  2192. # 'gaps': str}
  2193. #
  2194. # # How gaps wil be rendered:
  2195. # # lr - left + right
  2196. # # tb - top + bottom
  2197. # # 4 - left + right +top + bottom
  2198. # # 2lr - 2*left + 2*right
  2199. # # 2tb - 2*top + 2*bottom
  2200. # # 8 - 2*left + 2*right +2*top + 2*bottom
  2201. #
  2202. # if name is None:
  2203. # self.raise_tcl_error('Argument name is missing.')
  2204. #
  2205. # for key in kwa:
  2206. # if key not in types:
  2207. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2208. # try:
  2209. # kwa[key] = types[key](kwa[key])
  2210. # except Exception, e:
  2211. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, str(types[key])))
  2212. #
  2213. # try:
  2214. # obj = self.collection.get_by_name(str(name))
  2215. # except:
  2216. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2217. #
  2218. # # Get min and max data for each object as we just cut rectangles across X or Y
  2219. # xmin, ymin, xmax, ymax = obj.bounds()
  2220. # px = 0.5 * (xmin + xmax)
  2221. # py = 0.5 * (ymin + ymax)
  2222. # lenghtx = (xmax - xmin)
  2223. # lenghty = (ymax - ymin)
  2224. # gapsize = kwa['gapsize'] + kwa['dia'] / 2
  2225. #
  2226. # if kwa['gaps'] == '8' or kwa['gaps'] == '2lr':
  2227. #
  2228. # subtract_rectangle(name,
  2229. # xmin - gapsize,
  2230. # py - gapsize + lenghty / 4,
  2231. # xmax + gapsize,
  2232. # py + gapsize + lenghty / 4)
  2233. # subtract_rectangle(name,
  2234. # xmin - gapsize,
  2235. # py - gapsize - lenghty / 4,
  2236. # xmax + gapsize,
  2237. # py + gapsize - lenghty / 4)
  2238. #
  2239. # if kwa['gaps'] == '8' or kwa['gaps'] == '2tb':
  2240. # subtract_rectangle(name,
  2241. # px - gapsize + lenghtx / 4,
  2242. # ymin - gapsize,
  2243. # px + gapsize + lenghtx / 4,
  2244. # ymax + gapsize)
  2245. # subtract_rectangle(name,
  2246. # px - gapsize - lenghtx / 4,
  2247. # ymin - gapsize,
  2248. # px + gapsize - lenghtx / 4,
  2249. # ymax + gapsize)
  2250. #
  2251. # if kwa['gaps'] == '4' or kwa['gaps'] == 'lr':
  2252. # subtract_rectangle(name,
  2253. # xmin - gapsize,
  2254. # py - gapsize,
  2255. # xmax + gapsize,
  2256. # py + gapsize)
  2257. #
  2258. # if kwa['gaps'] == '4' or kwa['gaps'] == 'tb':
  2259. # subtract_rectangle(name,
  2260. # px - gapsize,
  2261. # ymin - gapsize,
  2262. # px + gapsize,
  2263. # ymax + gapsize)
  2264. #
  2265. # except Exception as unknown:
  2266. # self.raise_tcl_unknown_error(unknown)
  2267. # --- Migrated to new architecture ---
  2268. # def mirror(name, *args):
  2269. # a, kwa = h(*args)
  2270. # types = {'box': str,
  2271. # 'axis': str,
  2272. # 'dist': float}
  2273. #
  2274. # for key in kwa:
  2275. # if key not in types:
  2276. # return 'Unknown parameter: %s' % key
  2277. # kwa[key] = types[key](kwa[key])
  2278. #
  2279. # # Get source object.
  2280. # try:
  2281. # obj = self.collection.get_by_name(str(name))
  2282. # except:
  2283. # return "Could not retrieve object: %s" % name
  2284. #
  2285. # if obj is None:
  2286. # return "Object not found: %s" % name
  2287. #
  2288. # if not isinstance(obj, FlatCAMGerber) and \
  2289. # not isinstance(obj, FlatCAMExcellon) and \
  2290. # not isinstance(obj, FlatCAMGeometry):
  2291. # return "ERROR: Only Gerber, Excellon and Geometry objects can be mirrored."
  2292. #
  2293. # # Axis
  2294. # try:
  2295. # axis = kwa['axis'].upper()
  2296. # except KeyError:
  2297. # return "ERROR: Specify -axis X or -axis Y"
  2298. #
  2299. # # Box
  2300. # if 'box' in kwa:
  2301. # try:
  2302. # box = self.collection.get_by_name(kwa['box'])
  2303. # except:
  2304. # return "Could not retrieve object box: %s" % kwa['box']
  2305. #
  2306. # if box is None:
  2307. # return "Object box not found: %s" % kwa['box']
  2308. #
  2309. # try:
  2310. # xmin, ymin, xmax, ymax = box.bounds()
  2311. # px = 0.5 * (xmin + xmax)
  2312. # py = 0.5 * (ymin + ymax)
  2313. #
  2314. # obj.mirror(axis, [px, py])
  2315. # obj.plot()
  2316. #
  2317. # except Exception, e:
  2318. # return "Operation failed: %s" % str(e)
  2319. #
  2320. # else:
  2321. # try:
  2322. # dist = float(kwa['dist'])
  2323. # except KeyError:
  2324. # dist = 0.0
  2325. # except ValueError:
  2326. # return "Invalid distance: %s" % kwa['dist']
  2327. #
  2328. # try:
  2329. # obj.mirror(axis, [dist, dist])
  2330. # obj.plot()
  2331. # except Exception, e:
  2332. # return "Operation failed: %s" % str(e)
  2333. #
  2334. # return 'Ok'
  2335. # --- Migrated to new architecture ---
  2336. # def aligndrillgrid(outname, *args):
  2337. # a, kwa = h(*args)
  2338. # types = {'gridx': float,
  2339. # 'gridy': float,
  2340. # 'gridoffsetx': float,
  2341. # 'gridoffsety': float,
  2342. # 'columns':int,
  2343. # 'rows':int,
  2344. # 'dia': float
  2345. # }
  2346. # for key in kwa:
  2347. # if key not in types:
  2348. # return 'Unknown parameter: %s' % key
  2349. # kwa[key] = types[key](kwa[key])
  2350. #
  2351. # if 'columns' not in kwa or 'rows' not in kwa:
  2352. # return "ERROR: Specify -columns and -rows"
  2353. #
  2354. # if 'gridx' not in kwa or 'gridy' not in kwa:
  2355. # return "ERROR: Specify -gridx and -gridy"
  2356. #
  2357. # if 'dia' not in kwa:
  2358. # return "ERROR: Specify -dia"
  2359. #
  2360. # if 'gridoffsetx' not in kwa:
  2361. # gridoffsetx = 0
  2362. # else:
  2363. # gridoffsetx = kwa['gridoffsetx']
  2364. #
  2365. # if 'gridoffsety' not in kwa:
  2366. # gridoffsety = 0
  2367. # else:
  2368. # gridoffsety = kwa['gridoffsety']
  2369. #
  2370. # # Tools
  2371. # tools = {"1": {"C": kwa['dia']}}
  2372. #
  2373. # def aligndrillgrid_init_me(init_obj, app_obj):
  2374. # drills = []
  2375. # currenty = 0
  2376. #
  2377. # for row in range(kwa['rows']):
  2378. # currentx = 0
  2379. #
  2380. # for col in range(kwa['columns']):
  2381. # point = Point(currentx + gridoffsetx, currenty + gridoffsety)
  2382. # drills.append({"point": point, "tool": "1"})
  2383. # currentx = currentx + kwa['gridx']
  2384. #
  2385. # currenty = currenty + kwa['gridy']
  2386. #
  2387. # init_obj.tools = tools
  2388. # init_obj.drills = drills
  2389. # init_obj.create_geometry()
  2390. #
  2391. # self.new_object("excellon", outname, aligndrillgrid_init_me)
  2392. # --- Migrated to new architecture ---
  2393. # def aligndrill(name, *args):
  2394. # a, kwa = h(*args)
  2395. # types = {'box': str,
  2396. # 'axis': str,
  2397. # 'holes': str,
  2398. # 'grid': float,
  2399. # 'minoffset': float,
  2400. # 'gridoffset': float,
  2401. # 'axisoffset': float,
  2402. # 'dia': float,
  2403. # 'dist': float}
  2404. #
  2405. # for key in kwa:
  2406. # if key not in types:
  2407. # return 'Unknown parameter: %s' % key
  2408. # kwa[key] = types[key](kwa[key])
  2409. #
  2410. # # Get source object.
  2411. # try:
  2412. # obj = self.collection.get_by_name(str(name))
  2413. # except:
  2414. # return "Could not retrieve object: %s" % name
  2415. #
  2416. # if obj is None:
  2417. # return "Object not found: %s" % name
  2418. #
  2419. # if not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMExcellon):
  2420. # return "ERROR: Only Gerber, Geometry and Excellon objects can be used."
  2421. #
  2422. # # Axis
  2423. # try:
  2424. # axis = kwa['axis'].upper()
  2425. # except KeyError:
  2426. # return "ERROR: Specify -axis X or -axis Y"
  2427. #
  2428. # if not ('holes' in kwa or ('grid' in kwa and 'gridoffset' in kwa)):
  2429. # return "ERROR: Specify -holes or -grid with -gridoffset "
  2430. #
  2431. # if 'holes' in kwa:
  2432. # try:
  2433. # holes = eval("[" + kwa['holes'] + "]")
  2434. # except KeyError:
  2435. # return "ERROR: Wrong -holes format (X1,Y1),(X2,Y2)"
  2436. #
  2437. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2438. #
  2439. # # Tools
  2440. # tools = {"1": {"C": kwa['dia']}}
  2441. #
  2442. # def alligndrill_init_me(init_obj, app_obj):
  2443. #
  2444. # drills = []
  2445. # if 'holes' in kwa:
  2446. # for hole in holes:
  2447. # point = Point(hole)
  2448. # point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2449. # drills.append({"point": point, "tool": "1"})
  2450. # drills.append({"point": point_mirror, "tool": "1"})
  2451. # else:
  2452. # if 'box' not in kwa:
  2453. # return "ERROR: -grid can be used only for -box"
  2454. #
  2455. # if 'axisoffset' in kwa:
  2456. # axisoffset = kwa['axisoffset']
  2457. # else:
  2458. # axisoffset = 0
  2459. #
  2460. # # This will align hole to given aligngridoffset and minimal offset from pcb, based on selected axis
  2461. # if axis == "X":
  2462. # firstpoint = kwa['gridoffset']
  2463. #
  2464. # while (xmin - kwa['minoffset']) < firstpoint:
  2465. # firstpoint = firstpoint - kwa['grid']
  2466. #
  2467. # lastpoint = kwa['gridoffset']
  2468. #
  2469. # while (xmax + kwa['minoffset']) > lastpoint:
  2470. # lastpoint = lastpoint + kwa['grid']
  2471. #
  2472. # localholes = (firstpoint, axisoffset), (lastpoint, axisoffset)
  2473. #
  2474. # else:
  2475. # firstpoint = kwa['gridoffset']
  2476. #
  2477. # while (ymin - kwa['minoffset']) < firstpoint:
  2478. # firstpoint = firstpoint - kwa['grid']
  2479. #
  2480. # lastpoint = kwa['gridoffset']
  2481. #
  2482. # while (ymax + kwa['minoffset']) > lastpoint:
  2483. # lastpoint = lastpoint + kwa['grid']
  2484. #
  2485. # localholes = (axisoffset, firstpoint), (axisoffset, lastpoint)
  2486. #
  2487. # for hole in localholes:
  2488. # point = Point(hole)
  2489. # point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2490. # drills.append({"point": point, "tool": "1"})
  2491. # drills.append({"point": point_mirror, "tool": "1"})
  2492. #
  2493. # init_obj.tools = tools
  2494. # init_obj.drills = drills
  2495. # init_obj.create_geometry()
  2496. #
  2497. # # Box
  2498. # if 'box' in kwa:
  2499. # try:
  2500. # box = self.collection.get_by_name(kwa['box'])
  2501. # except:
  2502. # return "Could not retrieve object box: %s" % kwa['box']
  2503. #
  2504. # if box is None:
  2505. # return "Object box not found: %s" % kwa['box']
  2506. #
  2507. # try:
  2508. # xmin, ymin, xmax, ymax = box.bounds()
  2509. # px = 0.5 * (xmin + xmax)
  2510. # py = 0.5 * (ymin + ymax)
  2511. #
  2512. # obj.app.new_object("excellon", name + "_aligndrill", alligndrill_init_me)
  2513. #
  2514. # except Exception, e:
  2515. # return "Operation failed: %s" % str(e)
  2516. #
  2517. # else:
  2518. # try:
  2519. # dist = float(kwa['dist'])
  2520. # except KeyError:
  2521. # dist = 0.0
  2522. # except ValueError:
  2523. # return "Invalid distance: %s" % kwa['dist']
  2524. #
  2525. # try:
  2526. # px=dist
  2527. # py=dist
  2528. # obj.app.new_object("excellon", name + "_alligndrill", alligndrill_init_me)
  2529. # except Exception, e:
  2530. # return "Operation failed: %s" % str(e)
  2531. #
  2532. # return 'Ok'
  2533. # Migrated but still used?
  2534. # def drillcncjob(name=None, *args):
  2535. # """
  2536. # TCL shell command - see help section
  2537. #
  2538. # :param name: name of object
  2539. # :param args: array of arguments
  2540. # :return: "Ok" if completed without errors
  2541. # """
  2542. #
  2543. # try:
  2544. # a, kwa = h(*args)
  2545. # types = {'tools': str,
  2546. # 'outname': str,
  2547. # 'drillz': float,
  2548. # 'travelz': float,
  2549. # 'feedrate': float,
  2550. # 'spindlespeed': int,
  2551. # 'toolchange': int
  2552. # }
  2553. #
  2554. # if name is None:
  2555. # self.raise_tcl_error('Argument name is missing.')
  2556. #
  2557. # for key in kwa:
  2558. # if key not in types:
  2559. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2560. # try:
  2561. # kwa[key] = types[key](kwa[key])
  2562. # except Exception as e:
  2563. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, str(types[key])))
  2564. #
  2565. # try:
  2566. # obj = self.collection.get_by_name(str(name))
  2567. # except:
  2568. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2569. #
  2570. # if obj is None:
  2571. # self.raise_tcl_error('Object not found: %s' % name)
  2572. #
  2573. # if not isinstance(obj, FlatCAMExcellon):
  2574. # self.raise_tcl_error('Only Excellon objects can be drilled, got %s %s.' % (name, type(obj)))
  2575. #
  2576. # try:
  2577. # # Get the tools from the list
  2578. # job_name = kwa["outname"]
  2579. #
  2580. # # Object initialization function for app.new_object()
  2581. # def job_init(job_obj, app_obj):
  2582. # job_obj.z_cut = kwa["drillz"]
  2583. # job_obj.z_move = kwa["travelz"]
  2584. # job_obj.feedrate = kwa["feedrate"]
  2585. # job_obj.spindlespeed = kwa["spindlespeed"] if "spindlespeed" in kwa else None
  2586. # toolchange = True if "toolchange" in kwa and kwa["toolchange"] == 1 else False
  2587. # job_obj.generate_from_excellon_by_tool(obj, kwa["tools"], toolchange)
  2588. # job_obj.gcode_parse()
  2589. # job_obj.create_geometry()
  2590. #
  2591. # obj.app.new_object("cncjob", job_name, job_init)
  2592. #
  2593. # except Exception, e:
  2594. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2595. #
  2596. # except Exception as unknown:
  2597. # self.raise_tcl_unknown_error(unknown)
  2598. # --- Migrated to new architecture ---
  2599. # def millholes(name=None, *args):
  2600. # """
  2601. # TCL shell command - see help section
  2602. # :param name: name of object
  2603. # :param args: array of arguments
  2604. # :return: "Ok" if completed without errors
  2605. # """
  2606. #
  2607. # try:
  2608. # a, kwa = h(*args)
  2609. # types = {'tooldia': float,
  2610. # 'tools': str,
  2611. # 'outname': str}
  2612. #
  2613. # if name is None:
  2614. # self.raise_tcl_error('Argument name is missing.')
  2615. #
  2616. # for key in kwa:
  2617. # if key not in types:
  2618. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2619. # try:
  2620. # kwa[key] = types[key](kwa[key])
  2621. # except Exception, e:
  2622. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2623. #
  2624. # try:
  2625. # if 'tools' in kwa:
  2626. # kwa['tools'] = [x.strip() for x in kwa['tools'].split(",")]
  2627. # except Exception as e:
  2628. # self.raise_tcl_error("Bad tools: %s" % str(e))
  2629. #
  2630. # try:
  2631. # obj = self.collection.get_by_name(str(name))
  2632. # except:
  2633. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2634. #
  2635. # if obj is None:
  2636. # self.raise_tcl_error("Object not found: %s" % name)
  2637. #
  2638. # if not isinstance(obj, FlatCAMExcellon):
  2639. # self.raise_tcl_error('Only Excellon objects can be mill-drilled, got %s %s.' % (name, type(obj)))
  2640. #
  2641. # try:
  2642. # # This runs in the background: Block until done.
  2643. # with wait_signal(self.new_object_available):
  2644. # success, msg = obj.generate_milling(**kwa)
  2645. #
  2646. # except Exception as e:
  2647. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2648. #
  2649. # if not success:
  2650. # self.raise_tcl_error(msg)
  2651. #
  2652. # except Exception as unknown:
  2653. # self.raise_tcl_unknown_error(unknown)
  2654. # --- Migrated to new architecture ---
  2655. # def exteriors(name=None, *args):
  2656. # """
  2657. # TCL shell command - see help section
  2658. # :param name: name of object
  2659. # :param args: array of arguments
  2660. # :return: "Ok" if completed without errors
  2661. # """
  2662. #
  2663. # try:
  2664. # a, kwa = h(*args)
  2665. # types = {'outname': str}
  2666. #
  2667. # if name is None:
  2668. # self.raise_tcl_error('Argument name is missing.')
  2669. #
  2670. # for key in kwa:
  2671. # if key not in types:
  2672. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2673. # try:
  2674. # kwa[key] = types[key](kwa[key])
  2675. # except Exception, e:
  2676. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2677. #
  2678. # try:
  2679. # obj = self.collection.get_by_name(str(name))
  2680. # except:
  2681. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2682. #
  2683. # if obj is None:
  2684. # self.raise_tcl_error("Object not found: %s" % name)
  2685. #
  2686. # if not isinstance(obj, Geometry):
  2687. # self.raise_tcl_error('Expected Geometry, got %s %s.' % (name, type(obj)))
  2688. #
  2689. # def geo_init(geo_obj, app_obj):
  2690. # geo_obj.solid_geometry = obj_exteriors
  2691. #
  2692. # if 'outname' in kwa:
  2693. # outname = kwa['outname']
  2694. # else:
  2695. # outname = name + ".exteriors"
  2696. #
  2697. # try:
  2698. # obj_exteriors = obj.get_exteriors()
  2699. # self.new_object('geometry', outname, geo_init)
  2700. # except Exception as e:
  2701. # self.raise_tcl_error("Failed: %s" % str(e))
  2702. #
  2703. # except Exception as unknown:
  2704. # self.raise_tcl_unknown_error(unknown)
  2705. # --- Migrated to new architecture ---
  2706. # def interiors(name=None, *args):
  2707. # '''
  2708. # TCL shell command - see help section
  2709. # :param name: name of object
  2710. # :param args: array of arguments
  2711. # :return: "Ok" if completed without errors
  2712. # '''
  2713. #
  2714. # try:
  2715. # a, kwa = h(*args)
  2716. # types = {'outname': str}
  2717. #
  2718. # for key in kwa:
  2719. # if key not in types:
  2720. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2721. # try:
  2722. # kwa[key] = types[key](kwa[key])
  2723. # except Exception, e:
  2724. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2725. #
  2726. # if name is None:
  2727. # self.raise_tcl_error('Argument name is missing.')
  2728. #
  2729. # try:
  2730. # obj = self.collection.get_by_name(str(name))
  2731. # except:
  2732. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2733. #
  2734. # if obj is None:
  2735. # self.raise_tcl_error("Object not found: %s" % name)
  2736. #
  2737. # if not isinstance(obj, Geometry):
  2738. # self.raise_tcl_error('Expected Geometry, got %s %s.' % (name, type(obj)))
  2739. #
  2740. # def geo_init(geo_obj, app_obj):
  2741. # geo_obj.solid_geometry = obj_interiors
  2742. #
  2743. # if 'outname' in kwa:
  2744. # outname = kwa['outname']
  2745. # else:
  2746. # outname = name + ".interiors"
  2747. #
  2748. # try:
  2749. # obj_interiors = obj.get_interiors()
  2750. # self.new_object('geometry', outname, geo_init)
  2751. # except Exception as e:
  2752. # self.raise_tcl_error("Failed: %s" % str(e))
  2753. #
  2754. # except Exception as unknown:
  2755. # self.raise_tcl_unknown_error(unknown)
  2756. # --- Migrated to new architecture ---
  2757. # def isolate(name=None, *args):
  2758. # """
  2759. # TCL shell command - see help section
  2760. # :param name: name of object
  2761. # :param args: array of arguments
  2762. # :return: "Ok" if completed without errors
  2763. # """
  2764. #
  2765. # a, kwa = h(*args)
  2766. # types = {'dia': float,
  2767. # 'passes': int,
  2768. # 'overlap': float,
  2769. # 'outname': str,
  2770. # 'combine': int}
  2771. #
  2772. # for key in kwa:
  2773. # if key not in types:
  2774. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2775. # try:
  2776. # kwa[key] = types[key](kwa[key])
  2777. # except Exception, e:
  2778. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2779. # try:
  2780. # obj = self.collection.get_by_name(str(name))
  2781. # except:
  2782. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2783. #
  2784. # if obj is None:
  2785. # self.raise_tcl_error("Object not found: %s" % name)
  2786. #
  2787. # assert isinstance(obj, FlatCAMGerber), \
  2788. # "Expected a FlatCAMGerber, got %s" % type(obj)
  2789. #
  2790. # if not isinstance(obj, FlatCAMGerber):
  2791. # self.raise_tcl_error('Expected FlatCAMGerber, got %s %s.' % (name, type(obj)))
  2792. #
  2793. # try:
  2794. # obj.isolate(**kwa)
  2795. # except Exception, e:
  2796. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2797. #
  2798. # return 'Ok'
  2799. # --- Migrated to new architecture ---
  2800. # def cncjob(obj_name, *args):
  2801. # a, kwa = h(*args)
  2802. #
  2803. # types = {'z_cut': float,
  2804. # 'z_move': float,
  2805. # 'feedrate': float,
  2806. # 'tooldia': float,
  2807. # 'outname': str,
  2808. # 'spindlespeed': int,
  2809. # 'multidepth' : bool,
  2810. # 'depthperpass' : float
  2811. # }
  2812. #
  2813. # for key in kwa:
  2814. # if key not in types:
  2815. # return 'Unknown parameter: %s' % key
  2816. # kwa[key] = types[key](kwa[key])
  2817. #
  2818. # try:
  2819. # obj = self.collection.get_by_name(str(obj_name))
  2820. # except:
  2821. # return "Could not retrieve object: %s" % obj_name
  2822. # if obj is None:
  2823. # return "Object not found: %s" % obj_name
  2824. #
  2825. # try:
  2826. # obj.generatecncjob(**kwa)
  2827. # except Exception, e:
  2828. # return "Operation failed: %s" % str(e)
  2829. #
  2830. # return 'Ok'
  2831. # --- Migrated to new architecture ---
  2832. # def write_gcode(obj_name, filename, preamble='', postamble=''):
  2833. # """
  2834. # Requires obj_name to be available. It might still be in the
  2835. # making at the time this function is called, so check for
  2836. # promises and send to background if there are promises.
  2837. # """
  2838. #
  2839. # # If there are promised objects, wait until all promises have been fulfilled.
  2840. # if self.collection.has_promises():
  2841. #
  2842. # def write_gcode_on_object(new_object):
  2843. # self.log.debug("write_gcode_on_object(): Disconnecting %s" % write_gcode_on_object)
  2844. # self.new_object_available.disconnect(write_gcode_on_object)
  2845. # write_gcode(obj_name, filename, preamble, postamble)
  2846. #
  2847. # # Try again when a new object becomes available.
  2848. # self.log.debug("write_gcode(): Collection has promises. Queued for %s." % obj_name)
  2849. # self.log.debug("write_gcode(): Queued function: %s" % write_gcode_on_object)
  2850. # self.new_object_available.connect(write_gcode_on_object)
  2851. #
  2852. # return
  2853. #
  2854. # self.log.debug("write_gcode(): No promises. Continuing for %s." % obj_name)
  2855. #
  2856. # try:
  2857. # obj = self.collection.get_by_name(str(obj_name))
  2858. # except:
  2859. # return "Could not retrieve object: %s" % obj_name
  2860. #
  2861. # try:
  2862. # obj.export_gcode(str(filename), str(preamble), str(postamble))
  2863. # except Exception, e:
  2864. # return "Operation failed: %s" % str(e)
  2865. # --- Migrated to new architecture ---
  2866. # def paint_poly(obj_name, inside_pt_x, inside_pt_y, tooldia, overlap):
  2867. # try:
  2868. # obj = self.collection.get_by_name(str(obj_name))
  2869. # except:
  2870. # return "Could not retrieve object: %s" % obj_name
  2871. # if obj is None:
  2872. # return "Object not found: %s" % obj_name
  2873. # obj.paint_poly([float(inside_pt_x), float(inside_pt_y)], float(tooldia), float(overlap))
  2874. # --- New version in new geometry exists, but required here temporarily. ---
  2875. # def add_poly(obj_name, *args):
  2876. # """
  2877. # Required by: add_rectangle()
  2878. #
  2879. # :param obj_name:
  2880. # :param args:
  2881. # :return:
  2882. # """
  2883. # if len(args) % 2 != 0:
  2884. # return "Incomplete coordinate."
  2885. #
  2886. # points = [[float(args[2*i]), float(args[2*i+1])] for i in range(len(args)/2)]
  2887. #
  2888. # try:
  2889. # obj = self.collection.get_by_name(str(obj_name))
  2890. # except:
  2891. # return "Could not retrieve object: %s" % obj_name
  2892. # if obj is None:
  2893. # return "Object not found: %s" % obj_name
  2894. #
  2895. # obj.add_polygon(points)
  2896. # --- Migrated to new architecture ---
  2897. # def add_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  2898. # return add_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  2899. # topright_x, topright_y, topright_x, botleft_y)
  2900. # --- Migrated to new architecture ---
  2901. # def subtract_poly(obj_name, *args):
  2902. # """
  2903. # Required by: subtract_rectangle()
  2904. #
  2905. # :param obj_name:
  2906. # :param args:
  2907. # :return:
  2908. # """
  2909. # if len(args) % 2 != 0:
  2910. # return "Incomplete coordinate."
  2911. #
  2912. # points = [[float(args[2 * i]), float(args[2 * i +1])] for i in range(len(args)/2)]
  2913. #
  2914. # try:
  2915. # obj = self.collection.get_by_name(str(obj_name))
  2916. # except:
  2917. # return "Could not retrieve object: %s" % obj_name
  2918. # if obj is None:
  2919. # return "Object not found: %s" % obj_name
  2920. #
  2921. # obj.subtract_polygon(points)
  2922. # obj.plot()
  2923. #
  2924. # return "OK."
  2925. # --- Migrated to new architecture ---
  2926. # def subtract_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  2927. # return subtract_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  2928. # topright_x, topright_y, topright_x, botleft_y)
  2929. # --- Migrated to new architecture ---
  2930. # def add_circle(obj_name, center_x, center_y, radius):
  2931. # try:
  2932. # obj = self.collection.get_by_name(str(obj_name))
  2933. # except:
  2934. # return "Could not retrieve object: %s" % obj_name
  2935. # if obj is None:
  2936. # return "Object not found: %s" % obj_name
  2937. #
  2938. # obj.add_circle([float(center_x), float(center_y)], float(radius))
  2939. # --- Migrated to new architecture ---
  2940. # def set_active(obj_name):
  2941. # try:
  2942. # self.collection.set_active(str(obj_name))
  2943. # except Exception, e:
  2944. # return "Command failed: %s" % str(e)
  2945. # --- Migrated to new architecture ---
  2946. # def delete(obj_name):
  2947. # try:
  2948. # #deselect all to avoid delete selected object when run delete from shell
  2949. # self.collection.set_all_inactive()
  2950. # self.collection.set_active(str(obj_name))
  2951. # self.on_delete()
  2952. # except Exception, e:
  2953. # return "Command failed: %s" % str(e)
  2954. # --- Migrated to new architecture ---
  2955. # def geo_union(obj_name):
  2956. #
  2957. # try:
  2958. # obj = self.collection.get_by_name(str(obj_name))
  2959. # except:
  2960. # return "Could not retrieve object: %s" % obj_name
  2961. # if obj is None:
  2962. # return "Object not found: %s" % obj_name
  2963. #
  2964. # obj.union()
  2965. # --- Migrated to new architecture ---
  2966. # def join_geometries(obj_name, *obj_names):
  2967. # objs = []
  2968. # for obj_n in obj_names:
  2969. # obj = self.collection.get_by_name(str(obj_n))
  2970. # if obj is None:
  2971. # return "Object not found: %s" % obj_n
  2972. # else:
  2973. # objs.append(obj)
  2974. #
  2975. # def initialize(obj, app):
  2976. # FlatCAMGeometry.merge(objs, obj)
  2977. #
  2978. # if objs is not None:
  2979. # self.new_object("geometry", obj_name, initialize)
  2980. # --- Migrated to new architecture ---
  2981. # def join_excellons(obj_name, *obj_names):
  2982. # objs = []
  2983. # for obj_n in obj_names:
  2984. # obj = self.collection.get_by_name(str(obj_n))
  2985. # if obj is None:
  2986. # return "Object not found: %s" % obj_n
  2987. # else:
  2988. # objs.append(obj)
  2989. #
  2990. # def initialize(obj, app):
  2991. # FlatCAMExcellon.merge(objs, obj)
  2992. #
  2993. # if objs is not None:
  2994. # self.new_object("excellon", obj_name, initialize)
  2995. # --- Migrated to new architecture ---
  2996. # def panelize(name, *args):
  2997. # a, kwa = h(*args)
  2998. # types = {'box': str,
  2999. # 'spacing_columns': float,
  3000. # 'spacing_rows': float,
  3001. # 'columns': int,
  3002. # 'rows': int,
  3003. # 'outname': str}
  3004. #
  3005. # for key in kwa:
  3006. # if key not in types:
  3007. # return 'Unknown parameter: %s' % key
  3008. # kwa[key] = types[key](kwa[key])
  3009. #
  3010. # # Get source object.
  3011. # try:
  3012. # obj = self.collection.get_by_name(str(name))
  3013. # except:
  3014. # return "Could not retrieve object: %s" % name
  3015. #
  3016. # if obj is None:
  3017. # return "Object not found: %s" % name
  3018. #
  3019. # if 'box' in kwa:
  3020. # boxname = kwa['box']
  3021. # try:
  3022. # box = self.collection.get_by_name(boxname)
  3023. # except:
  3024. # return "Could not retrieve object: %s" % name
  3025. # else:
  3026. # box = obj
  3027. #
  3028. # if 'columns' not in kwa or 'rows' not in kwa:
  3029. # return "ERROR: Specify -columns and -rows"
  3030. #
  3031. # if 'outname' in kwa:
  3032. # outname = kwa['outname']
  3033. # else:
  3034. # outname = name + '_panelized'
  3035. #
  3036. # if 'spacing_columns' in kwa:
  3037. # spacing_columns = kwa['spacing_columns']
  3038. # else:
  3039. # spacing_columns = 5
  3040. #
  3041. # if 'spacing_rows' in kwa:
  3042. # spacing_rows = kwa['spacing_rows']
  3043. # else:
  3044. # spacing_rows = 5
  3045. #
  3046. # xmin, ymin, xmax, ymax = box.bounds()
  3047. # lenghtx = xmax - xmin + spacing_columns
  3048. # lenghty = ymax - ymin + spacing_rows
  3049. #
  3050. # currenty = 0
  3051. #
  3052. # def initialize_local(obj_init, app):
  3053. # obj_init.solid_geometry = obj.solid_geometry
  3054. # obj_init.offset([float(currentx), float(currenty)]),
  3055. #
  3056. # def initialize_local_excellon(obj_init, app):
  3057. # FlatCAMExcellon.merge(obj, obj_init)
  3058. # obj_init.offset([float(currentx), float(currenty)]),
  3059. #
  3060. # def initialize_geometry(obj_init, app):
  3061. # FlatCAMGeometry.merge(objs, obj_init)
  3062. #
  3063. # def initialize_excellon(obj_init, app):
  3064. # FlatCAMExcellon.merge(objs, obj_init)
  3065. #
  3066. # objs = []
  3067. # if obj is not None:
  3068. #
  3069. # for row in range(kwa['rows']):
  3070. # currentx = 0
  3071. # for col in range(kwa['columns']):
  3072. # local_outname = outname + ".tmp." + str(col) + "." + str(row)
  3073. # if isinstance(obj, FlatCAMExcellon):
  3074. # self.new_object("excellon", local_outname, initialize_local_excellon)
  3075. # else:
  3076. # self.new_object("geometry", local_outname, initialize_local)
  3077. #
  3078. # currentx += lenghtx
  3079. # currenty += lenghty
  3080. #
  3081. # if isinstance(obj, FlatCAMExcellon):
  3082. # self.new_object("excellon", outname, initialize_excellon)
  3083. # else:
  3084. # self.new_object("geometry", outname, initialize_geometry)
  3085. #
  3086. # #deselect all to avoid delete selected object when run delete from shell
  3087. # self.collection.set_all_inactive()
  3088. # for delobj in objs:
  3089. # self.collection.set_active(delobj.options['name'])
  3090. # self.on_delete()
  3091. #
  3092. # else:
  3093. # return "ERROR: obj is None"
  3094. #
  3095. # return "Ok"
  3096. def make_docs():
  3097. output = ''
  3098. import collections
  3099. od = collections.OrderedDict(sorted(commands.items()))
  3100. for cmd_, val in list(od.items()):
  3101. #print cmd, '\n', ''.join(['~']*len(cmd))
  3102. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  3103. t = val['help']
  3104. usage_i = t.find('>')
  3105. if usage_i < 0:
  3106. expl = t
  3107. #print expl + '\n'
  3108. output += expl + '\n\n'
  3109. continue
  3110. expl = t[:usage_i - 1]
  3111. #print expl + '\n'
  3112. output += expl + '\n\n'
  3113. end_usage_i = t[usage_i:].find('\n')
  3114. if end_usage_i < 0:
  3115. end_usage_i = len(t[usage_i:])
  3116. #print ' ' + t[usage_i:]
  3117. #print ' No parameters.\n'
  3118. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  3119. else:
  3120. extras = t[usage_i+end_usage_i+1:]
  3121. parts = [s.strip() for s in extras.split('\n')]
  3122. #print ' ' + t[usage_i:usage_i+end_usage_i]
  3123. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  3124. for p in parts:
  3125. #print ' ' + p + '\n'
  3126. output += ' ' + p + '\n\n'
  3127. return output
  3128. def follow(obj_name, *args):
  3129. a, kwa = h(*args)
  3130. types = {'outname': str}
  3131. for key in kwa:
  3132. if key not in types:
  3133. return 'Unknown parameter: %s' % key
  3134. kwa[key] = types[key](kwa[key])
  3135. try:
  3136. obj = self.collection.get_by_name(str(obj_name))
  3137. except:
  3138. return "Could not retrieve object: %s" % obj_name
  3139. if obj is None:
  3140. return "Object not found: %s" % obj_name
  3141. try:
  3142. obj.follow(**kwa)
  3143. except Exception as e:
  3144. return "ERROR: %s" % str(e)
  3145. # def get_sys(param):
  3146. # if param in self.defaults:
  3147. # return self.defaults[param]
  3148. #
  3149. # return "ERROR: No such system parameter."
  3150. # def set_sys(param, value):
  3151. # # tcl string to python keywords:
  3152. # tcl2py = {
  3153. # "None": None,
  3154. # "none": None,
  3155. # "false": False,
  3156. # "False": False,
  3157. # "true": True,
  3158. # "True": True
  3159. # }
  3160. #
  3161. # if param in self.defaults:
  3162. #
  3163. # try:
  3164. # value = tcl2py[value]
  3165. # except KeyError:
  3166. # pass
  3167. #
  3168. # self.defaults[param] = value
  3169. #
  3170. # self.propagate_defaults()
  3171. # return "Ok"
  3172. #
  3173. # return "ERROR: No such system parameter."
  3174. '''
  3175. Howto implement TCL shell commands:
  3176. All parameters passed to command should be possible to set as None and test it afterwards.
  3177. This is because we need to see error caused in tcl,
  3178. if None value as default parameter is not allowed TCL will return empty error.
  3179. Use:
  3180. def mycommand(name=None,...):
  3181. Test it like this:
  3182. if name is None:
  3183. self.raise_tcl_error('Argument name is missing.')
  3184. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  3185. otherwise we will miss it and processing will silently continue.
  3186. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  3187. which is catched in exec_command and displayed in TCL shell console with red background.
  3188. Error in console is displayed with TCL trace.
  3189. This behavior works only within main thread,
  3190. errors with promissed tasks can be catched and detected only with log.
  3191. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  3192. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  3193. '''
  3194. commands = {
  3195. # 'mytest': {
  3196. # 'fcn': mytest,
  3197. # 'help': "Test function. Only for testing."
  3198. # },
  3199. # 'mytest2': {
  3200. # 'fcn': mytest2,
  3201. # 'help': "Test function. Only for testing."
  3202. # },
  3203. # 'mytest3': {
  3204. # 'fcn': mytest3,
  3205. # 'help': "Test function. Only for testing."
  3206. # },
  3207. # 'mytest4': {
  3208. # 'fcn': mytest4,
  3209. # 'help': "Test function. Only for testing."
  3210. # },
  3211. 'help': {
  3212. 'fcn': shelp,
  3213. 'help': "Shows list of commands."
  3214. },
  3215. # --- Migrated to new architecture ---
  3216. # 'import_svg': {
  3217. # 'fcn': import_svg,
  3218. # 'help': "Import an SVG file as a Geometry Object.\n" +
  3219. # "> import_svg <filename>" +
  3220. # " filename: Path to the file to import."
  3221. # },
  3222. # --- Migrated to new architecture ---
  3223. # 'export_svg': {
  3224. # 'fcn': export_svg,
  3225. # 'help': "Export a Geometry Object as a SVG File\n" +
  3226. # "> export_svg <name> <filename> [-scale_factor <0.0 (float)>]\n" +
  3227. # " name: Name of the geometry object to export.\n" +
  3228. # " filename: Path to the file to export.\n" +
  3229. # " scale_factor: Multiplication factor used for scaling line widths during export."
  3230. # },
  3231. # --- Migrated to new architecture ---
  3232. # 'open_gerber': {
  3233. # 'fcn': open_gerber,
  3234. # 'help': "Opens a Gerber file.\n"
  3235. # "> open_gerber <filename> [-follow <0|1>] [-outname <o>]\n"
  3236. # " filename: Path to file to open.\n" +
  3237. # " follow: If 1, does not create polygons, just follows the gerber path.\n" +
  3238. # " outname: Name of the created gerber object."
  3239. # },
  3240. # --- Migrated to new architecture ---
  3241. # 'open_excellon': {
  3242. # 'fcn': open_excellon,
  3243. # 'help': "Opens an Excellon file.\n" +
  3244. # "> open_excellon <filename> [-outname <o>]\n" +
  3245. # " filename: Path to file to open.\n" +
  3246. # " outname: Name of the created excellon object."
  3247. # },
  3248. # --- Migrated to new architecture ---
  3249. # 'open_gcode': {
  3250. # 'fcn': open_gcode,
  3251. # 'help': "Opens an G-Code file.\n" +
  3252. # "> open_gcode <filename> [-outname <o>]\n" +
  3253. # " filename: Path to file to open.\n" +
  3254. # " outname: Name of the created CNC Job object."
  3255. # },
  3256. # --- Migrated to new architecture ---
  3257. # 'open_project': {
  3258. # 'fcn': self.open_project,
  3259. # "help": "Opens a FlatCAM project.\n" +
  3260. # "> open_project <filename>\n" +
  3261. # " filename: Path to file to open."
  3262. # },
  3263. # --- Migrated to new architecture ---
  3264. # 'save_project': {
  3265. # 'fcn': self.save_project,
  3266. # 'help': "Saves the FlatCAM project to file.\n" +
  3267. # "> save_project <filename>\n" +
  3268. # " filename: Path to file to save."
  3269. # },
  3270. # --- Migrated to new architecture ---
  3271. # 'set_active': {
  3272. # 'fcn': set_active,
  3273. # 'help': "Sets a FlatCAM object as active.\n" +
  3274. # "> set_active <name>\n" +
  3275. # " name: Name of the object."
  3276. # },
  3277. # --- Migrated to new architecture ---
  3278. # 'get_names': {
  3279. # 'fcn': lambda: '\n'.join(self.collection.get_names()),
  3280. # 'help': "Lists the names of objects in the project.\n" +
  3281. # "> get_names"
  3282. # },
  3283. # --- Migrated to new architecture ---
  3284. # 'new': {
  3285. # 'fcn': self.on_file_new,
  3286. # 'help': "Starts a new project. Clears objects from memory.\n" +
  3287. # "> new"
  3288. # },
  3289. # --- Migrated to new architecture ---
  3290. # 'options': {
  3291. # 'fcn': options,
  3292. # 'help': "Shows the settings for an object.\n" +
  3293. # "> options <name>\n" +
  3294. # " name: Object name."
  3295. # },
  3296. # --- Migrated to new architecture ---
  3297. # 'isolate': {
  3298. # 'fcn': isolate,
  3299. # 'help': "Creates isolation routing geometry for the given Gerber.\n" +
  3300. # "> isolate <name> [-dia <d>] [-passes <p>] [-overlap <o>] [-combine 0|1]\n" +
  3301. # " name: Name of the object.\n"
  3302. # " dia: Tool diameter\n passes: # of tool width.\n" +
  3303. # " overlap: Fraction of tool diameter to overlap passes." +
  3304. # " combine: combine all passes into one geometry." +
  3305. # " outname: Name of the resulting Geometry object."
  3306. # },
  3307. # 'cutout': {
  3308. # 'fcn': cutout,
  3309. # 'help': "Creates board cutout.\n" +
  3310. # "> cutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (4|tb|lr)>]\n" +
  3311. # " name: Name of the object\n" +
  3312. # " dia: Tool diameter\n" +
  3313. # " margin: Margin over bounds\n" +
  3314. # " gapsize: size of gap\n" +
  3315. # " gaps: type of gaps"
  3316. # },
  3317. # --- Migrated to new architecture ---
  3318. # 'geocutout': {
  3319. # 'fcn': geocutout,
  3320. # 'help': "Cut holding gaps from geometry.\n" +
  3321. # "> geocutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (8|4|tb|lr|2tb|2lr)>]\n" +
  3322. # " name: Name of the geometry object\n" +
  3323. # " dia: Tool diameter\n" +
  3324. # " margin: Margin over bounds\n" +
  3325. # " gapsize: size of gap\n" +
  3326. # " gaps: type of gaps\n" +
  3327. # "\n" +
  3328. # " example:\n" +
  3329. # "\n" +
  3330. # " #isolate margin for example from fritzing arduino shield or any svg etc\n" +
  3331. # " isolate BCu_margin -dia 3 -overlap 1\n" +
  3332. # "\n" +
  3333. # " #create exteriors from isolated object\n" +
  3334. # " exteriors BCu_margin_iso -outname BCu_margin_iso_exterior\n" +
  3335. # "\n" +
  3336. # " #delete isolated object if you dond need id anymore\n" +
  3337. # " delete BCu_margin_iso\n" +
  3338. # "\n" +
  3339. # " #finally cut holding gaps\n" +
  3340. # " geocutout BCu_margin_iso_exterior -dia 3 -gapsize 0.6 -gaps 4\n"
  3341. # },
  3342. # --- Migrated to new architecture ---
  3343. # 'mirror': {
  3344. # 'fcn': mirror,
  3345. # 'help': "Mirror a layer.\n" +
  3346. # "> mirror <name> -axis <X|Y> [-box <nameOfBox> | -dist <number>]\n" +
  3347. # " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  3348. # " box: Name of object which act as box (cutout for example.)\n" +
  3349. # " axis: Mirror axis parallel to the X or Y axis.\n" +
  3350. # " dist: Distance of the mirror axis to the X or Y axis."
  3351. #},
  3352. # --- Migrated to new architecture ---
  3353. # 'aligndrillgrid': {
  3354. # 'fcn': aligndrillgrid,
  3355. # 'help': "Create excellon with drills for aligment grid.\n" +
  3356. # "> aligndrillgrid <outname> [-dia <3.0 (float)>] -gridx <float> [-gridoffsetx <0 (float)>] -gridy <float> [-gridoffsety <0 (float)>] -columns <int> -rows <int>\n" +
  3357. # " outname: Name of the object to create.\n" +
  3358. # " dia: Tool diameter\n" +
  3359. # " gridx: grid size in X axis\n" +
  3360. # " gridoffsetx: move grid from origin\n" +
  3361. # " gridy: grid size in Y axis\n" +
  3362. # " gridoffsety: move grid from origin\n" +
  3363. # " colums: grid holes on X axis\n" +
  3364. # " rows: grid holes on Y axis\n"
  3365. # },
  3366. # --- Migrated to new architecture ---
  3367. # 'aligndrill': {
  3368. # 'fcn': aligndrill,
  3369. # 'help': "Create excellon with drills for aligment.\n" +
  3370. # "> 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" +
  3371. # " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  3372. # " dia: Tool diameter\n" +
  3373. # " box: Name of object which act as box (cutout for example.)\n" +
  3374. # " grid: aligning to grid, for thouse, who have aligning pins inside table in grid (-5,0),(5,0),(15,0)..." +
  3375. # " gridoffset: offset of grid from 0 position" +
  3376. # " minoffset: min and max distance between align hole and pcb" +
  3377. # " axisoffset: offset on second axis before aligment holes" +
  3378. # " axis: Mirror axis parallel to the X or Y axis.\n" +
  3379. # " dist: Distance of the mirror axis to the X or Y axis."
  3380. # },
  3381. # --- Migrated to new architecture ---
  3382. # 'exteriors': {
  3383. # 'fcn': exteriors,
  3384. # 'help': "Get exteriors of polygons.\n" +
  3385. # "> exteriors <name> [-outname <outname>]\n" +
  3386. # " name: Name of the source Geometry object.\n" +
  3387. # " outname: Name of the resulting Geometry object."
  3388. # },
  3389. # --- Migrated to new architecture ---
  3390. # 'interiors': {
  3391. # 'fcn': interiors,
  3392. # 'help': "Get interiors of polygons.\n" +
  3393. # "> interiors <name> [-outname <outname>]\n" +
  3394. # " name: Name of the source Geometry object.\n" +
  3395. # " outname: Name of the resulting Geometry object."
  3396. # },
  3397. # --- Migrated to new architecture ---
  3398. # 'drillcncjob': {
  3399. # 'fcn': drillcncjob,
  3400. # 'help': "Drill CNC job.\n" +
  3401. # "> drillcncjob <name> -tools <str> -drillz <float> " +
  3402. # "-travelz <float> -feedrate <float> -outname <str> " +
  3403. # "[-spindlespeed (int)] [-toolchange (int)] \n" +
  3404. # " name: Name of the object\n" +
  3405. # " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  3406. # " drillz: Drill depth into material (example: -2.0)\n" +
  3407. # " travelz: Travel distance above material (example: 2.0)\n" +
  3408. # " feedrate: Drilling feed rate\n" +
  3409. # " outname: Name of object to create\n" +
  3410. # " spindlespeed: Speed of the spindle in rpm (example: 4000)\n" +
  3411. # " toolchange: Enable tool changes (example: 1)\n"
  3412. # },
  3413. # 'millholes': {
  3414. # 'fcn': millholes,
  3415. # 'help': "Create Geometry Object for milling holes from Excellon.\n" +
  3416. # "> millholes <name> -tools <str> -tooldia <float> -outname <str> \n" +
  3417. # " name: Name of the Excellon Object\n" +
  3418. # " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  3419. # " tooldia: Diameter of the milling tool (example: 0.1)\n" +
  3420. # " outname: Name of object to create\n"
  3421. # },
  3422. # --- Migrated to the new architecture ---
  3423. # 'scale': {
  3424. # 'fcn': lambda name, factor: self.collection.get_by_name(str(name)).scale(float(factor)),
  3425. # 'help': "Resizes the object by a factor.\n" +
  3426. # "> scale <name> <factor>\n" +
  3427. # " name: Name of the object\n factor: Fraction by which to scale"
  3428. # },
  3429. # --- Migrated to the new architecture ---
  3430. # 'offset': {
  3431. # 'fcn': lambda name, x, y: self.collection.get_by_name(str(name)).offset([float(x), float(y)]),
  3432. # 'help': "Changes the position of the object.\n" +
  3433. # "> offset <name> <x> <y>\n" +
  3434. # " name: Name of the object\n" +
  3435. # " x: X-axis distance\n" +
  3436. # " y: Y-axis distance"
  3437. # },
  3438. # --- Migrated to new architecture ---
  3439. # 'plot': {
  3440. # 'fcn': self.plot_all,
  3441. # 'help': 'Updates the plot on the user interface'
  3442. # },
  3443. # --- Migrated to new architecture ---
  3444. # 'cncjob': {
  3445. # 'fcn': cncjob,
  3446. # 'help': 'Generates a CNC Job from a Geometry Object.\n' +
  3447. # '> cncjob <name> [-z_cut <c>] [-z_move <float>] [-feedrate <float>] [-tooldia <float>] [-spindlespeed <int>] [-multidepth <bool>] [-depthperpass <float>] [-outname <str>]\n' +
  3448. # ' name: Name of the source object\n' +
  3449. # ' z_cut: Z-axis cutting position\n' +
  3450. # ' z_move: Z-axis moving position\n' +
  3451. # ' feedrate: Moving speed when cutting\n' +
  3452. # ' tooldia: Tool diameter to show on screen\n' +
  3453. # ' spindlespeed: Speed of the spindle in rpm (example: 4000)\n' +
  3454. # ' multidepth: Use or not multidepth cnccut\n'+
  3455. # ' depthperpass: Height of one layer for multidepth\n'+
  3456. # ' outname: Name of the output object'
  3457. # },
  3458. # --- Migrated to new architecture ---
  3459. # 'write_gcode': {
  3460. # 'fcn': write_gcode,
  3461. # 'help': 'Saves G-code of a CNC Job object to file.\n' +
  3462. # '> write_gcode <name> <filename>\n' +
  3463. # ' name: Source CNC Job object\n' +
  3464. # ' filename: Output filename'
  3465. # },
  3466. # --- Migrated to new architecture ---
  3467. # 'paint_poly': {
  3468. # 'fcn': paint_poly,
  3469. # 'help': 'Creates a geometry object with toolpath to cover the inside of a polygon.\n' +
  3470. # '> paint_poly <name> <inside_pt_x> <inside_pt_y> <tooldia> <overlap>\n' +
  3471. # ' name: Name of the sourge geometry object.\n' +
  3472. # ' inside_pt_x, inside_pt_y: Coordinates of a point inside the polygon.\n' +
  3473. # ' tooldia: Diameter of the tool to be used.\n' +
  3474. # ' overlap: Fraction of the tool diameter to overlap cuts.'
  3475. # },
  3476. # --- Migrated to new architecture ---
  3477. # 'new_geometry': {
  3478. # 'fcn': lambda name: self.new_object('geometry', str(name), lambda x, y: None),
  3479. # 'help': 'Creates a new empty geometry object.\n' +
  3480. # '> new_geometry <name>\n' +
  3481. # ' name: New object name'
  3482. # },
  3483. # --- Migrated to new architecture ---
  3484. # 'add_poly': {
  3485. # 'fcn': add_poly,
  3486. # 'help': 'Creates a polygon in the given Geometry object.\n' +
  3487. # '> create_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3488. # ' name: Name of the geometry object to which to append the polygon.\n' +
  3489. # ' xi, yi: Coordinates of points in the polygon.'
  3490. # },
  3491. # --- Migrated to new architecture ---
  3492. # 'subtract_poly': {
  3493. # 'fcn': subtract_poly,
  3494. # 'help': 'Subtract polygon from the given Geometry object.\n' +
  3495. # '> subtract_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3496. # ' name: Name of the geometry object, which will be sutracted.\n' +
  3497. # ' xi, yi: Coordinates of points in the polygon.'
  3498. # },
  3499. # --- Migrated to new architecture ---
  3500. # 'delete': {
  3501. # 'fcn': delete,
  3502. # 'help': 'Deletes the give object.\n' +
  3503. # '> delete <name>\n' +
  3504. # ' name: Name of the object to delete.'
  3505. # },
  3506. # --- Migrated to new architecture ---
  3507. # 'geo_union': {
  3508. # 'fcn': geo_union,
  3509. # 'help': 'Runs a union operation (addition) on the components ' +
  3510. # 'of the geometry object. For example, if it contains ' +
  3511. # '2 intersecting polygons, this opperation adds them into' +
  3512. # 'a single larger polygon.\n' +
  3513. # '> geo_union <name>\n' +
  3514. # ' name: Name of the geometry object.'
  3515. # },
  3516. # --- Migrated to new architecture ---
  3517. # 'join_geometries': {
  3518. # 'fcn': join_geometries,
  3519. # 'help': 'Runs a merge operation (join) on the geometry ' +
  3520. # 'objects.' +
  3521. # '> join_geometries <out_name> <obj_name_0>....\n' +
  3522. # ' out_name: Name of the new geometry object.' +
  3523. # ' obj_name_0... names of the objects to join'
  3524. # },
  3525. # --- Migrated to new architecture ---
  3526. # 'join_excellons': {
  3527. # 'fcn': join_excellons,
  3528. # 'help': 'Runs a merge operation (join) on the excellon ' +
  3529. # 'objects.' +
  3530. # '> join_excellons <out_name> <obj_name_0>....\n' +
  3531. # ' out_name: Name of the new excellon object.' +
  3532. # ' obj_name_0... names of the objects to join'
  3533. # },
  3534. # --- Migrated to new architecture ---
  3535. # 'panelize': {
  3536. # 'fcn': panelize,
  3537. # 'help': "Simple panelize geometries.\n" +
  3538. # "> panelize <name> [-box <nameOfBox>] [-spacing_columns <5 (float)>] [-spacing_rows <5 (float)>] -columns <int> -rows <int> [-outname <n>]\n" +
  3539. # " name: Name of the object to panelize.\n" +
  3540. # " box: Name of object which act as box (cutout for example.) for cutout boundary. Object from name is used if not specified.\n" +
  3541. # " spacing_columns: spacing between columns\n"+
  3542. # " spacing_rows: spacing between rows\n"+
  3543. # " columns: number of columns\n"+
  3544. # " rows: number of rows\n"+
  3545. # " outname: Name of the new geometry object."
  3546. # },
  3547. # 'subtract_rect': {
  3548. # 'fcn': subtract_rectangle,
  3549. # 'help': 'Subtract rectange from the given Geometry object.\n' +
  3550. # '> subtract_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3551. # ' name: Name of the geometry object, which will be subtracted.\n' +
  3552. # ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3553. # ' topright_x, topright_y Coordinates of the top right corner.'
  3554. # },
  3555. # --- Migrated to new architecture ---
  3556. # 'add_rect': {
  3557. # 'fcn': add_rectangle,
  3558. # 'help': 'Creates a rectange in the given Geometry object.\n' +
  3559. # '> add_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3560. # ' name: Name of the geometry object to which to append the rectangle.\n' +
  3561. # ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3562. # ' topright_x, topright_y Coordinates of the top right corner.'
  3563. # },
  3564. # --- Migrated to new architecture ---
  3565. # 'add_circle': {
  3566. # 'fcn': add_circle,
  3567. # 'help': 'Creates a circle in the given Geometry object.\n' +
  3568. # '> add_circle <name> <center_x> <center_y> <radius>\n' +
  3569. # ' name: Name of the geometry object to which to append the circle.\n' +
  3570. # ' center_x, center_y: Coordinates of the center of the circle.\n' +
  3571. # ' radius: Radius of the circle.'
  3572. # },
  3573. 'make_docs': {
  3574. 'fcn': make_docs,
  3575. 'help': 'Prints command rererence in reStructuredText format.'
  3576. },
  3577. 'follow': {
  3578. 'fcn': follow,
  3579. 'help': 'Creates a geometry object following gerber paths.\n' +
  3580. '> follow <name> [-outname <oname>]\n' +
  3581. ' name: Name of the gerber object.\n' +
  3582. ' outname: Name of the output geometry object.'
  3583. },
  3584. # 'get_sys': {
  3585. # 'fcn': get_sys,
  3586. # 'help': 'Get the value of a system parameter (FlatCAM constant)\n' +
  3587. # '> get_sys <sysparam>\n' +
  3588. # ' sysparam: Name of the parameter.'
  3589. # },
  3590. # --- Migrated to new architecture ---
  3591. # 'set_sys': {
  3592. # 'fcn': set_sys,
  3593. # 'help': 'Set the value of a system parameter (FlatCAM constant)\n' +
  3594. # '> set_sys <sysparam> <paramvalue>\n' +
  3595. # ' sysparam: Name of the parameter.\n' +
  3596. # ' paramvalue: Value to set.'
  3597. # }
  3598. }
  3599. # Import/overwrite tcl commands as objects of TclCommand descendants
  3600. # This modifies the variable 'commands'.
  3601. tclCommands.register_all_commands(self, commands)
  3602. # Add commands to the tcl interpreter
  3603. for cmd in commands:
  3604. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  3605. # Make the tcl puts function return instead of print to stdout
  3606. self.tcl.eval('''
  3607. rename puts original_puts
  3608. proc puts {args} {
  3609. if {[llength $args] == 1} {
  3610. return "[lindex $args 0]"
  3611. } else {
  3612. eval original_puts $args
  3613. }
  3614. }
  3615. ''')
  3616. def setup_recent_items(self):
  3617. self.log.debug("setup_recent_items()")
  3618. # TODO: Move this to constructor
  3619. icons = {
  3620. "gerber": "share/flatcam_icon16.png",
  3621. "excellon": "share/drill16.png",
  3622. "cncjob": "share/cnc16.png",
  3623. "project": "share/project16.png",
  3624. "svg": "share/geometry16.png"
  3625. }
  3626. openers = {
  3627. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  3628. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  3629. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  3630. 'project': self.open_project,
  3631. 'svg': self.import_svg
  3632. }
  3633. # Open file
  3634. try:
  3635. f = open(self.data_path + '/recent.json')
  3636. except IOError:
  3637. App.log.error("Failed to load recent item list.")
  3638. self.inform.emit("[error] Failed to load recent item list.")
  3639. return
  3640. try:
  3641. self.recent = json.load(f)
  3642. except json.scanner.JSONDecodeError:
  3643. App.log.error("Failed to parse recent item list.")
  3644. self.inform.emit("[error] Failed to parse recent item list.")
  3645. f.close()
  3646. return
  3647. f.close()
  3648. # Closure needed to create callbacks in a loop.
  3649. # Otherwise late binding occurs.
  3650. def make_callback(func, fname):
  3651. def opener():
  3652. func(fname)
  3653. return opener
  3654. # Reset menu
  3655. self.ui.recent.clear()
  3656. # Create menu items
  3657. for recent in self.recent:
  3658. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  3659. try:
  3660. action = QtGui.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  3661. # Attach callback
  3662. o = make_callback(openers[recent["kind"]], recent['filename'])
  3663. action.triggered.connect(o)
  3664. self.ui.recent.addAction(action)
  3665. except KeyError:
  3666. App.log.error("Unsupported file type: %s" % recent["kind"])
  3667. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  3668. # self.ui.menufilerecent.set_submenu(recent_menu)
  3669. # recent_menu.show_all()
  3670. # self.ui.recent.show()
  3671. def setup_component_editor(self):
  3672. label = QtGui.QLabel("Choose an item from Project")
  3673. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  3674. self.ui.selected_scroll_area.setWidget(label)
  3675. def setup_obj_classes(self):
  3676. """
  3677. Sets up application specifics on the FlatCAMObj class.
  3678. :return: None
  3679. """
  3680. FlatCAMObj.app = self
  3681. FCProcess.app = self
  3682. FCProcessContainer.app = self
  3683. def version_check(self):
  3684. """
  3685. Checks for the latest version of the program. Alerts the
  3686. user if theirs is outdated. This method is meant to be run
  3687. in a separate thread.
  3688. :return: None
  3689. """
  3690. self.log.debug("version_check()")
  3691. full_url = App.version_url + \
  3692. "?s=" + str(self.defaults['serial']) + \
  3693. "&v=" + str(self.version) + \
  3694. "&os=" + str(self.os) + \
  3695. "&" + urllib.parse.urlencode(self.defaults["stats"])
  3696. App.log.debug("Checking for updates @ %s" % full_url)
  3697. ### Get the data
  3698. try:
  3699. f = urllib.request.urlopen(full_url)
  3700. except:
  3701. # App.log.warning("Failed checking for latest version. Could not connect.")
  3702. self.log.warning("Failed checking for latest version. Could not connect.")
  3703. self.inform.emit("[warning] Failed checking for latest version. Could not connect.")
  3704. return
  3705. try:
  3706. data = json.load(f)
  3707. except Exception as e:
  3708. App.log.error("Could not parse information about latest version.")
  3709. self.inform.emit("[error] Could not parse information about latest version.")
  3710. App.log.debug("json.load(): %s" % str(e))
  3711. f.close()
  3712. return
  3713. f.close()
  3714. ### Latest version?
  3715. if self.version >= data["version"]:
  3716. App.log.debug("FlatCAM is up to date!")
  3717. self.inform.emit("[success] FlatCAM is up to date!")
  3718. return
  3719. App.log.debug("Newer version available.")
  3720. self.message.emit(
  3721. "Newer Version Available",
  3722. str("There is a newer version of FlatCAM " +
  3723. "available for download:<br><br>" +
  3724. "<B>" + data["name"] + "</b><br>" +
  3725. data["message"].replace("\n", "<br>")),
  3726. "info"
  3727. )
  3728. def enable_all_plots(self, *args):
  3729. self.plotcanvas.clear()
  3730. def worker_task(app_obj):
  3731. percentage = 0.1
  3732. try:
  3733. delta = 0.9 / len(self.collection.get_list())
  3734. except ZeroDivisionError:
  3735. self.progress.emit(0)
  3736. return
  3737. for obj in self.collection.get_list():
  3738. obj.options['plot'] = True
  3739. obj.plot()
  3740. percentage += delta
  3741. self.progress.emit(int(percentage*100))
  3742. self.progress.emit(0)
  3743. self.plots_updated.emit()
  3744. # Send to worker
  3745. # self.worker.add_task(worker_task, [self])
  3746. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  3747. def save_project(self, filename):
  3748. """
  3749. Saves the current project to the specified file.
  3750. :param filename: Name of the file in which to save.
  3751. :type filename: str
  3752. :return: None
  3753. """
  3754. self.log.debug("save_project()")
  3755. ## Capture the latest changes
  3756. # Current object
  3757. try:
  3758. self.collection.get_active().read_form()
  3759. except:
  3760. self.log.debug("[warning] There was no active object")
  3761. pass
  3762. # Project options
  3763. self.options_read_form()
  3764. # Serialize the whole project
  3765. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  3766. "options": self.options,
  3767. "version": self.version}
  3768. # Open file
  3769. try:
  3770. f = open(filename, 'w')
  3771. except IOError:
  3772. App.log.error("[error] Failed to open file for saving: %s", filename)
  3773. return
  3774. # Write
  3775. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  3776. # try:
  3777. # json.dump(d, f, default=to_dict)
  3778. # except Exception, e:
  3779. # print str(e)
  3780. # App.log.error("[error] File open but failed to write: %s", filename)
  3781. # f.close()
  3782. # return
  3783. f.close()
  3784. self.inform.emit("Project saved to: %s" % filename)
  3785. # def main():
  3786. #
  3787. # app = QtGui.QApplication(sys.argv)
  3788. # fc = App()
  3789. # sys.exit(app.exec_())
  3790. #
  3791. #
  3792. # if __name__ == '__main__':
  3793. # main()