FlatCAMApp.py 166 KB

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