FlatCAMObj.py 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996
  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 copy
  9. import inspect # TODO: For debugging only.
  10. from datetime import datetime
  11. from flatcamGUI.ObjectUI import *
  12. from FlatCAMCommon import LoudDict
  13. from camlib import *
  14. import itertools
  15. import gettext
  16. import FlatCAMTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. class ObjectDeleted(Exception):
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. pass
  24. class ValidationError(Exception):
  25. def __init__(self, message, errors):
  26. super().__init__(message)
  27. self.errors = errors
  28. # ##################################### ##
  29. # # FlatCAMObj # ##
  30. # ##################################### ##
  31. class FlatCAMObj(QtCore.QObject):
  32. """
  33. Base type of objects handled in FlatCAM. These become interactive
  34. in the GUI, can be plotted, and their options can be modified
  35. by the user in their respective forms.
  36. """
  37. # Instance of the application to which these are related.
  38. # The app should set this value.
  39. app = None
  40. def __init__(self, name):
  41. """
  42. Constructor.
  43. :param name: Name of the object given by the user.
  44. :return: FlatCAMObj
  45. """
  46. QtCore.QObject.__init__(self)
  47. # View
  48. self.ui = None
  49. self.options = LoudDict(name=name)
  50. self.options.set_change_callback(self.on_options_change)
  51. self.form_fields = {}
  52. # store here the default data for Geometry Data
  53. self.default_data = {}
  54. self.kind = None # Override with proper name
  55. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  56. self.shapes = self.app.plotcanvas.new_shape_group()
  57. # self.mark_shapes = self.app.plotcanvas.new_shape_collection(layers=2)
  58. self.mark_shapes = {}
  59. self.item = None # Link with project view item
  60. self.muted_ui = False
  61. self.deleted = False
  62. try:
  63. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  64. self.app.defaults["global_tolerance"] else 0.01
  65. except ValueError:
  66. self._drawing_tolerance = 0.01
  67. self.isHovering = False
  68. self.notHovering = True
  69. self.units = 'IN'
  70. # assert isinstance(self.ui, ObjectUI)
  71. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  72. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  73. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  74. def __del__(self):
  75. pass
  76. def __str__(self):
  77. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  78. def from_dict(self, d):
  79. """
  80. This supersedes ``from_dict`` in derived classes. Derived classes
  81. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  82. ``self.options`` is only updated, not overwritten. This ensures that
  83. options set by the app do not vanish when reading the objects
  84. from a project file.
  85. :param d: Dictionary with attributes to set.
  86. :return: None
  87. """
  88. for attr in self.ser_attrs:
  89. if attr == 'options':
  90. self.options.update(d[attr])
  91. else:
  92. try:
  93. setattr(self, attr, d[attr])
  94. except KeyError:
  95. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  96. "Means that we are loading an old project that don't"
  97. "have all attributes in the latest FlatCAM." % str(attr))
  98. pass
  99. def on_options_change(self, key):
  100. # Update form on programmatically options change
  101. self.set_form_item(key)
  102. # Set object visibility
  103. if key == 'plot':
  104. self.visible = self.options['plot']
  105. self.optionChanged.emit(key)
  106. def set_ui(self, ui):
  107. self.ui = ui
  108. self.form_fields = {"name": self.ui.name_entry}
  109. assert isinstance(self.ui, ObjectUI)
  110. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  111. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  112. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  113. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  114. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  115. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  116. def build_ui(self):
  117. """
  118. Sets up the UI/form for this object. Show the UI
  119. in the App.
  120. :return: None
  121. :rtype: None
  122. """
  123. self.muted_ui = True
  124. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  125. # Remove anything else in the box
  126. # box_children = self.app.ui.notebook.selected_contents.get_children()
  127. # for child in box_children:
  128. # self.app.ui.notebook.selected_contents.remove(child)
  129. # while self.app.ui.selected_layout.count():
  130. # self.app.ui.selected_layout.takeAt(0)
  131. # Put in the UI
  132. # box_selected.pack_start(sw, True, True, 0)
  133. # self.app.ui.notebook.selected_contents.add(self.ui)
  134. # self.app.ui.selected_layout.addWidget(self.ui)
  135. try:
  136. self.app.ui.selected_scroll_area.takeWidget()
  137. except:
  138. self.app.log.debug("Nothing to remove")
  139. self.app.ui.selected_scroll_area.setWidget(self.ui)
  140. self.muted_ui = False
  141. def on_name_activate(self):
  142. old_name = copy(self.options["name"])
  143. new_name = self.ui.name_entry.get_value()
  144. if new_name != old_name:
  145. # update the SHELL auto-completer model data
  146. try:
  147. self.app.myKeywords.remove(old_name)
  148. self.app.myKeywords.append(new_name)
  149. self.app.shell._edit.set_model_data(self.app.myKeywords)
  150. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  151. except:
  152. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  153. self.options["name"] = self.ui.name_entry.get_value()
  154. self.default_data["name"] = self.ui.name_entry.get_value()
  155. self.app.collection.update_view()
  156. self.app.inform.emit(_("[success] Name changed from {old} to {new}").format(old=old_name, new=new_name))
  157. def on_offset_button_click(self):
  158. self.app.report_usage("obj_on_offset_button")
  159. self.read_form()
  160. vector_val = self.ui.offsetvector_entry.get_value()
  161. self.offset(vector_val)
  162. self.plot()
  163. self.app.object_changed.emit(self)
  164. def on_scale_button_click(self):
  165. self.app.report_usage("obj_on_scale_button")
  166. self.read_form()
  167. factor = self.ui.scale_entry.get_value()
  168. self.scale(factor)
  169. self.plot()
  170. self.app.object_changed.emit(self)
  171. def on_skew_button_click(self):
  172. self.app.report_usage("obj_on_skew_button")
  173. self.read_form()
  174. x_angle = self.ui.xangle_entry.get_value()
  175. y_angle = self.ui.yangle_entry.get_value()
  176. self.skew(x_angle, y_angle)
  177. self.plot()
  178. self.app.object_changed.emit(self)
  179. def to_form(self):
  180. """
  181. Copies options to the UI form.
  182. :return: None
  183. """
  184. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  185. for option in self.options:
  186. try:
  187. self.set_form_item(option)
  188. except:
  189. self.app.log.warning("Unexpected error:", sys.exc_info())
  190. def read_form(self):
  191. """
  192. Reads form into ``self.options``.
  193. :return: None
  194. :rtype: None
  195. """
  196. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  197. for option in self.options:
  198. try:
  199. self.read_form_item(option)
  200. except:
  201. self.app.log.warning("Unexpected error:", sys.exc_info())
  202. def set_form_item(self, option):
  203. """
  204. Copies the specified option to the UI form.
  205. :param option: Name of the option (Key in ``self.options``).
  206. :type option: str
  207. :return: None
  208. """
  209. try:
  210. self.form_fields[option].set_value(self.options[option])
  211. except KeyError:
  212. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  213. pass
  214. def read_form_item(self, option):
  215. """
  216. Reads the specified option from the UI form into ``self.options``.
  217. :param option: Name of the option.
  218. :type option: str
  219. :return: None
  220. """
  221. try:
  222. self.options[option] = self.form_fields[option].get_value()
  223. except KeyError:
  224. self.app.log.warning("Failed to read option from field: %s" % option)
  225. def plot(self):
  226. """
  227. Plot this object (Extend this method to implement the actual plotting).
  228. Call this in descendants before doing the plotting.
  229. :return: Whether to continue plotting or not depending on the "plot" option.
  230. :rtype: bool
  231. """
  232. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  233. if self.deleted:
  234. return False
  235. self.clear()
  236. return True
  237. def serialize(self):
  238. """
  239. Returns a representation of the object as a dictionary so
  240. it can be later exported as JSON. Override this method.
  241. :return: Dictionary representing the object
  242. :rtype: dict
  243. """
  244. return
  245. def deserialize(self, obj_dict):
  246. """
  247. Re-builds an object from its serialized version.
  248. :param obj_dict: Dictionary representing a FlatCAMObj
  249. :type obj_dict: dict
  250. :return: None
  251. """
  252. return
  253. def add_shape(self, **kwargs):
  254. if self.deleted:
  255. raise ObjectDeleted()
  256. else:
  257. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  258. return key
  259. def add_mark_shape(self, apid, **kwargs):
  260. if self.deleted:
  261. raise ObjectDeleted()
  262. else:
  263. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, **kwargs)
  264. return key
  265. @property
  266. def visible(self):
  267. return self.shapes.visible
  268. @visible.setter
  269. def visible(self, value, threaded=False):
  270. log.debug("FlatCAMObj.visible()")
  271. def worker_task(app_obj):
  272. app_obj.shapes.visible = value
  273. # Not all object types has annotations
  274. try:
  275. app_obj.annotation.visible = value
  276. except Exception as e:
  277. pass
  278. if threaded is False:
  279. worker_task(self)
  280. else:
  281. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  282. @property
  283. def drawing_tolerance(self):
  284. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  285. @drawing_tolerance.setter
  286. def drawing_tolerance(self, value):
  287. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  288. def clear(self, update=False):
  289. self.shapes.clear(update)
  290. # Not all object types has annotations
  291. try:
  292. self.annotation.clear(update)
  293. except AttributeError:
  294. pass
  295. def delete(self):
  296. # Free resources
  297. del self.ui
  298. del self.options
  299. # Set flag
  300. self.deleted = True
  301. class FlatCAMGerber(FlatCAMObj, Gerber):
  302. """
  303. Represents Gerber code.
  304. """
  305. optionChanged = QtCore.pyqtSignal(str)
  306. replotApertures = QtCore.pyqtSignal()
  307. ui_type = GerberObjectUI
  308. def merge(self, grb_list, grb_final):
  309. """
  310. Merges the geometry of objects in geo_list into
  311. the geometry of geo_final.
  312. :param grb_list: List of FlatCAMGerber Objects to join.
  313. :param grb_final: Destination FlatCAMGeometry object.
  314. :return: None
  315. """
  316. if grb_final.solid_geometry is None:
  317. grb_final.solid_geometry = []
  318. grb_final.follow_geometry = []
  319. if not grb_final.apertures:
  320. grb_final.apertures = {}
  321. if type(grb_final.solid_geometry) is not list:
  322. grb_final.solid_geometry = [grb_final.solid_geometry]
  323. grb_final.follow_geometry = [grb_final.follow_geometry]
  324. for grb in grb_list:
  325. # Expand lists
  326. if type(grb) is list:
  327. FlatCAMGerber.merge(grb, grb_final)
  328. else: # If not list, just append
  329. for option in grb.options:
  330. if option is not 'name':
  331. try:
  332. grb_final.options[option] = grb.options[option]
  333. except KeyError:
  334. log.warning("Failed to copy option.", option)
  335. try:
  336. for geos in grb.solid_geometry:
  337. grb_final.solid_geometry.append(geos)
  338. grb_final.follow_geometry.append(geos)
  339. except TypeError:
  340. grb_final.solid_geometry.append(grb.solid_geometry)
  341. grb_final.follow_geometry.append(grb.solid_geometry)
  342. for ap in grb.apertures:
  343. if ap not in grb_final.apertures:
  344. grb_final.apertures[ap] = grb.apertures[ap]
  345. else:
  346. # create a list of integers out of the grb.apertures keys and find the max of that value
  347. # then, the aperture duplicate is assigned an id value incremented with 1,
  348. # and finally made string because the apertures dict keys are strings
  349. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  350. grb_final.apertures[max_ap] = {}
  351. grb_final.apertures[max_ap]['geometry'] = []
  352. for k, v in grb.apertures[ap].items():
  353. grb_final.apertures[max_ap][k] = deepcopy(v)
  354. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  355. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  356. def __init__(self, name):
  357. Gerber.__init__(self, steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  358. FlatCAMObj.__init__(self, name)
  359. self.kind = "gerber"
  360. # The 'name' is already in self.options from FlatCAMObj
  361. # Automatically updates the UI
  362. self.options.update({
  363. "plot": True,
  364. "multicolored": False,
  365. "solid": False,
  366. "isotooldia": 0.016,
  367. "isopasses": 1,
  368. "isooverlap": 0.15,
  369. "milling_type": "cl",
  370. "combine_passes": True,
  371. "noncoppermargin": 0.0,
  372. "noncopperrounded": False,
  373. "bboxmargin": 0.0,
  374. "bboxrounded": False,
  375. "aperture_display": False,
  376. "follow": False
  377. })
  378. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  379. self.iso_type = 2
  380. self.multigeo = False
  381. self.follow = False
  382. self.apertures_row = 0
  383. # store the source file here
  384. self.source_file = ""
  385. # list of rows with apertures plotted
  386. self.marked_rows = []
  387. # Attributes to be included in serialization
  388. # Always append to it because it carries contents
  389. # from predecessors.
  390. self.ser_attrs += ['options', 'kind']
  391. def set_ui(self, ui):
  392. """
  393. Maps options with GUI inputs.
  394. Connects GUI events to methods.
  395. :param ui: GUI object.
  396. :type ui: GerberObjectUI
  397. :return: None
  398. """
  399. FlatCAMObj.set_ui(self, ui)
  400. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  401. self.replotApertures.connect(self.on_mark_cb_click_table)
  402. self.form_fields.update({
  403. "plot": self.ui.plot_cb,
  404. "multicolored": self.ui.multicolored_cb,
  405. "solid": self.ui.solid_cb,
  406. "isotooldia": self.ui.iso_tool_dia_entry,
  407. "isopasses": self.ui.iso_width_entry,
  408. "isooverlap": self.ui.iso_overlap_entry,
  409. "milling_type": self.ui.milling_type_radio,
  410. "combine_passes": self.ui.combine_passes_cb,
  411. "noncoppermargin": self.ui.noncopper_margin_entry,
  412. "noncopperrounded": self.ui.noncopper_rounded_cb,
  413. "bboxmargin": self.ui.bbmargin_entry,
  414. "bboxrounded": self.ui.bbrounded_cb,
  415. "aperture_display": self.ui.aperture_table_visibility_cb,
  416. "follow": self.ui.follow_cb
  417. })
  418. # Fill form fields only on object create
  419. self.to_form()
  420. assert isinstance(self.ui, GerberObjectUI)
  421. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  422. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  423. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  424. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  425. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  426. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  427. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  428. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  429. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  430. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  431. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  432. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  433. # Show/Hide Advanced Options
  434. if self.app.defaults["global_app_level"] == 'b':
  435. self.ui.level.setText(_(
  436. '<span style="color:green;"><b>Basic</b></span>'
  437. ))
  438. self.ui.apertures_table_label.hide()
  439. self.ui.aperture_table_visibility_cb.hide()
  440. self.ui.milling_type_label.hide()
  441. self.ui.milling_type_radio.hide()
  442. self.ui.generate_ext_iso_button.hide()
  443. self.ui.generate_int_iso_button.hide()
  444. self.ui.follow_cb.hide()
  445. self.ui.padding_area_label.show()
  446. else:
  447. self.ui.level.setText(_(
  448. '<span style="color:red;"><b>Advanced</b></span>'
  449. ))
  450. self.ui.padding_area_label.hide()
  451. # add the shapes storage for marking apertures
  452. for ap_code in self.apertures:
  453. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=2)
  454. # set initial state of the aperture table and associated widgets
  455. self.on_aperture_table_visibility_change()
  456. self.build_ui()
  457. def build_ui(self):
  458. FlatCAMObj.build_ui(self)
  459. try:
  460. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  461. self.ui.apertures_table.itemChanged.disconnect()
  462. except:
  463. pass
  464. self.apertures_row = 0
  465. aper_no = self.apertures_row + 1
  466. sort = []
  467. for k, v in list(self.apertures.items()):
  468. sort.append(int(k))
  469. sorted_apertures = sorted(sort)
  470. # sort = []
  471. # for k, v in list(self.aperture_macros.items()):
  472. # sort.append(k)
  473. # sorted_macros = sorted(sort)
  474. # n = len(sorted_apertures) + len(sorted_macros)
  475. n = len(sorted_apertures)
  476. self.ui.apertures_table.setRowCount(n)
  477. for ap_code in sorted_apertures:
  478. ap_code = str(ap_code)
  479. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  480. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  481. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  482. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  483. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  484. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  485. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  486. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  487. ap_dim_item = QtWidgets.QTableWidgetItem(
  488. '%.4f, %.4f' % (self.apertures[ap_code]['width'] * self.file_units_factor,
  489. self.apertures[ap_code]['height'] * self.file_units_factor
  490. )
  491. )
  492. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  493. elif str(self.apertures[ap_code]['type']) == 'P':
  494. ap_dim_item = QtWidgets.QTableWidgetItem(
  495. '%.4f, %.4f' % (self.apertures[ap_code]['diam'] * self.file_units_factor,
  496. self.apertures[ap_code]['nVertices'] * self.file_units_factor)
  497. )
  498. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  499. else:
  500. ap_dim_item = QtWidgets.QTableWidgetItem('')
  501. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  502. try:
  503. if self.apertures[ap_code]['size'] is not None:
  504. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  505. float(self.apertures[ap_code]['size'] *
  506. self.file_units_factor))
  507. else:
  508. ap_size_item = QtWidgets.QTableWidgetItem('')
  509. except KeyError:
  510. ap_size_item = QtWidgets.QTableWidgetItem('')
  511. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  512. mark_item = FCCheckBox()
  513. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  514. # if self.ui.aperture_table_visibility_cb.isChecked():
  515. # mark_item.setChecked(True)
  516. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  517. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  518. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  519. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  520. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  521. self.apertures_row += 1
  522. # for ap_code in sorted_macros:
  523. # ap_code = str(ap_code)
  524. #
  525. # ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  526. # ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  527. # self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  528. #
  529. # ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  530. #
  531. # ap_type_item = QtWidgets.QTableWidgetItem('AM')
  532. # ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  533. #
  534. # mark_item = FCCheckBox()
  535. # mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  536. # # if self.ui.aperture_table_visibility_cb.isChecked():
  537. # # mark_item.setChecked(True)
  538. #
  539. # self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  540. # self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  541. # self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  542. #
  543. # self.apertures_row += 1
  544. self.ui.apertures_table.selectColumn(0)
  545. self.ui.apertures_table.resizeColumnsToContents()
  546. self.ui.apertures_table.resizeRowsToContents()
  547. vertical_header = self.ui.apertures_table.verticalHeader()
  548. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  549. vertical_header.hide()
  550. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  551. horizontal_header = self.ui.apertures_table.horizontalHeader()
  552. horizontal_header.setMinimumSectionSize(10)
  553. horizontal_header.setDefaultSectionSize(70)
  554. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  555. horizontal_header.resizeSection(0, 27)
  556. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  557. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  558. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  559. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  560. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  561. horizontal_header.resizeSection(5, 17)
  562. self.ui.apertures_table.setColumnWidth(5, 17)
  563. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  564. self.ui.apertures_table.setSortingEnabled(False)
  565. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  566. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  567. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  568. if self.marked_rows:
  569. for row in range(self.ui.apertures_table.rowCount()):
  570. try:
  571. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  572. except IndexError:
  573. pass
  574. self.ui_connect()
  575. def ui_connect(self):
  576. for row in range(self.ui.apertures_table.rowCount()):
  577. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  578. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  579. def ui_disconnect(self):
  580. for row in range(self.ui.apertures_table.rowCount()):
  581. try:
  582. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  583. except:
  584. pass
  585. try:
  586. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  587. except:
  588. pass
  589. def on_generatenoncopper_button_click(self, *args):
  590. self.app.report_usage("gerber_on_generatenoncopper_button")
  591. self.read_form()
  592. name = self.options["name"] + "_noncopper"
  593. def geo_init(geo_obj, app_obj):
  594. assert isinstance(geo_obj, FlatCAMGeometry)
  595. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  596. if not self.options["noncopperrounded"]:
  597. bounding_box = bounding_box.envelope
  598. non_copper = bounding_box.difference(self.solid_geometry)
  599. geo_obj.solid_geometry = non_copper
  600. # TODO: Check for None
  601. self.app.new_object("geometry", name, geo_init)
  602. def on_generatebb_button_click(self, *args):
  603. self.app.report_usage("gerber_on_generatebb_button")
  604. self.read_form()
  605. name = self.options["name"] + "_bbox"
  606. def geo_init(geo_obj, app_obj):
  607. assert isinstance(geo_obj, FlatCAMGeometry)
  608. # Bounding box with rounded corners
  609. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  610. if not self.options["bboxrounded"]: # Remove rounded corners
  611. bounding_box = bounding_box.envelope
  612. geo_obj.solid_geometry = bounding_box
  613. self.app.new_object("geometry", name, geo_init)
  614. def on_ext_iso_button_click(self, *args):
  615. if self.ui.follow_cb.get_value() == True:
  616. obj = self.app.collection.get_active()
  617. obj.follow()
  618. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  619. obj.ui.plot_cb.toggle()
  620. else:
  621. self.app.report_usage("gerber_on_iso_button")
  622. self.read_form()
  623. self.isolate(iso_type=0)
  624. def on_int_iso_button_click(self, *args):
  625. if self.ui.follow_cb.get_value() is True:
  626. obj = self.app.collection.get_active()
  627. obj.follow()
  628. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  629. obj.ui.plot_cb.toggle()
  630. else:
  631. self.app.report_usage("gerber_on_iso_button")
  632. self.read_form()
  633. self.isolate(iso_type=1)
  634. def on_iso_button_click(self, *args):
  635. if self.ui.follow_cb.get_value() is True:
  636. obj = self.app.collection.get_active()
  637. obj.follow_geo()
  638. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  639. obj.ui.plot_cb.toggle()
  640. else:
  641. self.app.report_usage("gerber_on_iso_button")
  642. self.read_form()
  643. self.isolate()
  644. def follow_geo(self, outname=None):
  645. """
  646. Creates a geometry object "following" the gerber paths.
  647. :return: None
  648. """
  649. # default_name = self.options["name"] + "_follow"
  650. # follow_name = outname or default_name
  651. if outname is None:
  652. follow_name = self.options["name"] + "_follow"
  653. else:
  654. follow_name = outname
  655. def follow_init(follow_obj, app):
  656. # Propagate options
  657. follow_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  658. follow_obj.solid_geometry = self.follow_geometry
  659. # TODO: Do something if this is None. Offer changing name?
  660. try:
  661. self.app.new_object("geometry", follow_name, follow_init)
  662. except Exception as e:
  663. return "Operation failed: %s" % str(e)
  664. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  665. outname=None, combine=None, milling_type=None, follow=None):
  666. """
  667. Creates an isolation routing geometry object in the project.
  668. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  669. :param dia: Tool diameter
  670. :param passes: Number of tool widths to cut
  671. :param overlap: Overlap between passes in fraction of tool diameter
  672. :param outname: Base name of the output object
  673. :return: None
  674. """
  675. if dia is None:
  676. dia = float(self.options["isotooldia"])
  677. if passes is None:
  678. passes = int(self.options["isopasses"])
  679. if overlap is None:
  680. overlap = float(self.options["isooverlap"])
  681. if combine is None:
  682. combine = self.options["combine_passes"]
  683. else:
  684. combine = bool(combine)
  685. if milling_type is None:
  686. milling_type = self.options["milling_type"]
  687. if iso_type is None:
  688. self.iso_type = 2
  689. else:
  690. self.iso_type = iso_type
  691. base_name = self.options["name"] + "_iso"
  692. base_name = outname or base_name
  693. def generate_envelope(offset, invert, envelope_iso_type=2, follow=None):
  694. # isolation_geometry produces an envelope that is going on the left of the geometry
  695. # (the copper features). To leave the least amount of burrs on the features
  696. # the tool needs to travel on the right side of the features (this is called conventional milling)
  697. # the first pass is the one cutting all of the features, so it needs to be reversed
  698. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  699. # to cut on the right side of the left over copper i.e on the left side of the features.
  700. try:
  701. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  702. except Exception as e:
  703. log.debug(str(e))
  704. return 'fail'
  705. if invert:
  706. try:
  707. if type(geom) is MultiPolygon:
  708. pl = []
  709. for p in geom:
  710. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  711. geom = MultiPolygon(pl)
  712. elif type(geom) is Polygon:
  713. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  714. else:
  715. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  716. except Exception as e:
  717. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  718. return geom
  719. if combine:
  720. if self.iso_type == 0:
  721. iso_name = self.options["name"] + "_ext_iso"
  722. elif self.iso_type == 1:
  723. iso_name = self.options["name"] + "_int_iso"
  724. else:
  725. iso_name = base_name
  726. # TODO: This is ugly. Create way to pass data into init function.
  727. def iso_init(geo_obj, app_obj):
  728. # Propagate options
  729. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  730. geo_obj.solid_geometry = []
  731. for i in range(passes):
  732. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  733. # if milling type is climb then the move is counter-clockwise around features
  734. if milling_type == 'cl':
  735. # geom = generate_envelope (offset, i == 0)
  736. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type, follow=follow)
  737. else:
  738. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type, follow=follow)
  739. geo_obj.solid_geometry.append(geom)
  740. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  741. # or just looking in the lists (they are one level depth) and if any is not empty
  742. # proceed with object creation, if there are empty and the number of them is the length
  743. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  744. empty_cnt = 0
  745. if not isinstance(geo_obj.solid_geometry, list):
  746. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  747. for g in geo_obj.solid_geometry:
  748. if g:
  749. app_obj.inform.emit(_(
  750. "[success] Isolation geometry created: %s"
  751. ) % geo_obj.options["name"])
  752. break
  753. else:
  754. empty_cnt += 1
  755. if empty_cnt == len(geo_obj.solid_geometry):
  756. raise ValidationError("Empty Geometry", None)
  757. geo_obj.multigeo = False
  758. # TODO: Do something if this is None. Offer changing name?
  759. self.app.new_object("geometry", iso_name, iso_init)
  760. else:
  761. for i in range(passes):
  762. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  763. if passes > 1:
  764. if self.iso_type == 0:
  765. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  766. elif self.iso_type == 1:
  767. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  768. else:
  769. iso_name = base_name + str(i + 1)
  770. else:
  771. if self.iso_type == 0:
  772. iso_name = self.options["name"] + "_ext_iso"
  773. elif self.iso_type == 1:
  774. iso_name = self.options["name"] + "_int_iso"
  775. else:
  776. iso_name = base_name
  777. # TODO: This is ugly. Create way to pass data into init function.
  778. def iso_init(geo_obj, app_obj):
  779. # Propagate options
  780. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  781. # if milling type is climb then the move is counter-clockwise around features
  782. if milling_type == 'cl':
  783. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  784. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type,
  785. follow=follow)
  786. else:
  787. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type,
  788. follow=follow)
  789. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  790. # or just looking in the lists (they are one level depth) and if any is not empty
  791. # proceed with object creation, if there are empty and the number of them is the length
  792. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  793. empty_cnt = 0
  794. if not isinstance(geo_obj.solid_geometry, list):
  795. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  796. for g in geo_obj.solid_geometry:
  797. if g:
  798. app_obj.inform.emit(_(
  799. "[success] Isolation geometry created: %s"
  800. ) % geo_obj.options["name"])
  801. break
  802. else:
  803. empty_cnt += 1
  804. if empty_cnt == len(geo_obj.solid_geometry):
  805. raise ValidationError("Empty Geometry", None)
  806. geo_obj.multigeo = False
  807. # TODO: Do something if this is None. Offer changing name?
  808. self.app.new_object("geometry", iso_name, iso_init)
  809. def on_plot_cb_click(self, *args):
  810. if self.muted_ui:
  811. return
  812. self.read_form_item('plot')
  813. self.plot()
  814. def on_solid_cb_click(self, *args):
  815. if self.muted_ui:
  816. return
  817. self.read_form_item('solid')
  818. self.plot()
  819. def on_multicolored_cb_click(self, *args):
  820. if self.muted_ui:
  821. return
  822. self.read_form_item('multicolored')
  823. self.plot()
  824. def on_follow_cb_click(self):
  825. if self.muted_ui:
  826. return
  827. self.plot()
  828. def on_aperture_table_visibility_change(self):
  829. if self.ui.aperture_table_visibility_cb.isChecked():
  830. self.ui.apertures_table.setVisible(True)
  831. for ap in self.mark_shapes:
  832. self.mark_shapes[ap].enabled = True
  833. self.ui.mark_all_cb.setVisible(True)
  834. self.ui.mark_all_cb.setChecked(False)
  835. else:
  836. self.ui.apertures_table.setVisible(False)
  837. self.ui.mark_all_cb.setVisible(False)
  838. # on hide disable all mark plots
  839. for row in range(self.ui.apertures_table.rowCount()):
  840. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  841. self.clear_plot_apertures()
  842. for ap in self.mark_shapes:
  843. self.mark_shapes[ap].enabled = False
  844. def convert_units(self, units):
  845. """
  846. Converts the units of the object by scaling dimensions in all geometry
  847. and options.
  848. :param units: Units to which to convert the object: "IN" or "MM".
  849. :type units: str
  850. :return: None
  851. :rtype: None
  852. """
  853. factor = Gerber.convert_units(self, units)
  854. self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  855. self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  856. def plot(self, **kwargs):
  857. """
  858. :param kwargs: color and face_color
  859. :return:
  860. """
  861. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  862. # Does all the required setup and returns False
  863. # if the 'ptint' option is set to False.
  864. if not FlatCAMObj.plot(self):
  865. return
  866. if 'color' in kwargs:
  867. color = kwargs['color']
  868. else:
  869. color = self.app.defaults['global_plot_line']
  870. if 'face_color' in kwargs:
  871. face_color = kwargs['face_color']
  872. else:
  873. face_color = self.app.defaults['global_plot_fill']
  874. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  875. if self.ui.follow_cb.get_value():
  876. geometry = self.follow_geometry
  877. else:
  878. geometry = self.solid_geometry
  879. # Make sure geometry is iterable.
  880. try:
  881. __ = iter(geometry)
  882. except TypeError:
  883. geometry = [geometry]
  884. def random_color():
  885. color = np.random.rand(4)
  886. color[3] = 1
  887. return color
  888. try:
  889. if self.options["solid"]:
  890. for g in geometry:
  891. if type(g) == Polygon or type(g) == LineString:
  892. self.add_shape(shape=g, color=color,
  893. face_color=random_color() if self.options['multicolored']
  894. else face_color, visible=self.options['plot'])
  895. elif type(g) == Point:
  896. pass
  897. else:
  898. try:
  899. for el in g:
  900. self.add_shape(shape=el, color=color,
  901. face_color=random_color() if self.options['multicolored']
  902. else face_color, visible=self.options['plot'])
  903. except TypeError:
  904. self.add_shape(shape=g, color=color,
  905. face_color=random_color() if self.options['multicolored']
  906. else face_color, visible=self.options['plot'])
  907. else:
  908. for g in geometry:
  909. if type(g) == Polygon or type(g) == LineString:
  910. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  911. visible=self.options['plot'])
  912. elif type(g) == Point:
  913. pass
  914. else:
  915. for el in g:
  916. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  917. visible=self.options['plot'])
  918. self.shapes.redraw()
  919. except (ObjectDeleted, AttributeError):
  920. self.shapes.clear(update=True)
  921. # experimental plot() when the solid_geometry is stored in the self.apertures
  922. def plot_aperture(self, **kwargs):
  923. """
  924. :param kwargs: color and face_color
  925. :return:
  926. """
  927. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  928. # Does all the required setup and returns False
  929. # if the 'ptint' option is set to False.
  930. if not FlatCAMObj.plot(self):
  931. return
  932. # for marking apertures, line color and fill color are the same
  933. if 'color' in kwargs:
  934. color = kwargs['color']
  935. else:
  936. color = self.app.defaults['global_plot_fill']
  937. if 'marked_aperture' not in kwargs:
  938. return
  939. else:
  940. aperture_to_plot_mark = kwargs['marked_aperture']
  941. if aperture_to_plot_mark is None:
  942. return
  943. if 'visible' not in kwargs:
  944. visibility = True
  945. else:
  946. visibility = kwargs['visible']
  947. with self.app.proc_container.new(_("Plotting Apertures")) as proc:
  948. self.app.progress.emit(30)
  949. def job_thread(app_obj):
  950. self.app.progress.emit(30)
  951. try:
  952. if aperture_to_plot_mark in self.apertures:
  953. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  954. if 'solid' in elem:
  955. geo = elem['solid']
  956. if type(geo) == Polygon or type(geo) == LineString:
  957. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  958. face_color=color, visible=visibility)
  959. else:
  960. for el in geo:
  961. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  962. face_color=color, visible=visibility)
  963. self.mark_shapes[aperture_to_plot_mark].redraw()
  964. self.app.progress.emit(100)
  965. except (ObjectDeleted, AttributeError):
  966. self.clear_plot_apertures()
  967. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  968. def clear_plot_apertures(self, aperture='all'):
  969. """
  970. :param aperture: string; aperture for which to clear the mark shapes
  971. :return:
  972. """
  973. if aperture == 'all':
  974. for apid in self.apertures:
  975. self.mark_shapes[apid].clear(update=True)
  976. else:
  977. self.mark_shapes[aperture].clear(update=True)
  978. def clear_mark_all(self):
  979. self.ui.mark_all_cb.set_value(False)
  980. self.marked_rows[:] = []
  981. def on_mark_cb_click_table(self):
  982. """
  983. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  984. :return:
  985. """
  986. self.ui_disconnect()
  987. cw = self.sender()
  988. try:
  989. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  990. cw_row = cw_index.row()
  991. except AttributeError:
  992. cw_row = 0
  993. self.marked_rows[:] = []
  994. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  995. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  996. self.marked_rows.append(True)
  997. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  998. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'], marked_aperture=aperture, visible=True)
  999. self.mark_shapes[aperture].redraw()
  1000. else:
  1001. self.marked_rows.append(False)
  1002. self.clear_plot_apertures(aperture=aperture)
  1003. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1004. # if all the row mark's are enabled also enable the Mark All checkbox
  1005. cb_cnt = 0
  1006. total_row = self.ui.apertures_table.rowCount()
  1007. for row in range(total_row):
  1008. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1009. cb_cnt += 1
  1010. else:
  1011. cb_cnt -= 1
  1012. if cb_cnt < total_row:
  1013. self.ui.mark_all_cb.setChecked(False)
  1014. else:
  1015. self.ui.mark_all_cb.setChecked(True)
  1016. self.ui_connect()
  1017. def on_mark_all_click(self, signal):
  1018. self.ui_disconnect()
  1019. mark_all = self.ui.mark_all_cb.isChecked()
  1020. for row in range(self.ui.apertures_table.rowCount()):
  1021. # update the mark_rows list
  1022. if mark_all:
  1023. self.marked_rows.append(True)
  1024. else:
  1025. self.marked_rows[:] = []
  1026. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1027. mark_cb.setChecked(mark_all)
  1028. if mark_all:
  1029. for aperture in self.apertures:
  1030. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1031. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'],
  1032. marked_aperture=aperture, visible=True)
  1033. # HACK: enable/disable the grid for a better look
  1034. self.app.ui.grid_snap_btn.trigger()
  1035. self.app.ui.grid_snap_btn.trigger()
  1036. else:
  1037. self.clear_plot_apertures()
  1038. self.ui_connect()
  1039. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1040. """
  1041. :return: Gerber_code
  1042. """
  1043. def tz_format(x, y ,fac):
  1044. x_c = x * fac
  1045. y_c = y * fac
  1046. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1047. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1048. # extract whole part and decimal part
  1049. x_form = x_form.partition('.')
  1050. y_form = y_form.partition('.')
  1051. # left padd the 'whole' part with zeros
  1052. x_whole = x_form[0].rjust(whole, '0')
  1053. y_whole = y_form[0].rjust(whole, '0')
  1054. # restore the coordinate padded in the left with 0 and added the decimal part
  1055. # without the decinal dot
  1056. x_form = x_whole + x_form[2]
  1057. y_form = y_whole + y_form[2]
  1058. return x_form, y_form
  1059. def lz_format(x, y, fac):
  1060. x_c = x * fac
  1061. y_c = y * fac
  1062. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1063. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1064. # pad with rear zeros
  1065. x_form.ljust(length, '0')
  1066. y_form.ljust(length, '0')
  1067. return x_form, y_form
  1068. # Gerber code is stored here
  1069. gerber_code = ''
  1070. # apertures processing
  1071. try:
  1072. length = whole + fract
  1073. if '0' in self.apertures:
  1074. if 'geometry' in self.apertures['0']:
  1075. for geo_elem in self.apertures['0']['geometry']:
  1076. if 'solid' in geo_elem:
  1077. geo = geo_elem['solid']
  1078. if not geo.is_empty:
  1079. gerber_code += 'G36*\n'
  1080. geo_coords = list(geo.exterior.coords)
  1081. # first command is a move with pen-up D02 at the beginning of the geo
  1082. if g_zeros == 'T':
  1083. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1084. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1085. yform=y_formatted)
  1086. else:
  1087. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1088. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1089. yform=y_formatted)
  1090. for coord in geo_coords[1:]:
  1091. if g_zeros == 'T':
  1092. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1093. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1094. yform=y_formatted)
  1095. else:
  1096. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1097. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1098. yform=y_formatted)
  1099. gerber_code += 'D02*\n'
  1100. gerber_code += 'G37*\n'
  1101. clear_list = list(geo.interiors)
  1102. if clear_list:
  1103. gerber_code += '%LPC*%\n'
  1104. for clear_geo in clear_list:
  1105. gerber_code += 'G36*\n'
  1106. geo_coords = list(clear_geo.coords)
  1107. # first command is a move with pen-up D02 at the beginning of the geo
  1108. if g_zeros == 'T':
  1109. x_formatted, y_formatted = tz_format(
  1110. geo_coords[0][0], geo_coords[0][1], factor)
  1111. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1112. yform=y_formatted)
  1113. else:
  1114. x_formatted, y_formatted = lz_format(
  1115. geo_coords[0][0], geo_coords[0][1], factor)
  1116. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1117. yform=y_formatted)
  1118. prev_coord = geo_coords[0]
  1119. for coord in geo_coords[1:]:
  1120. if coord != prev_coord:
  1121. if g_zeros == 'T':
  1122. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1123. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1124. yform=y_formatted)
  1125. else:
  1126. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1127. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1128. yform=y_formatted)
  1129. prev_coord = coord
  1130. gerber_code += 'D02*\n'
  1131. gerber_code += 'G37*\n'
  1132. gerber_code += '%LPD*%\n'
  1133. if 'clear' in geo_elem:
  1134. geo = geo_elem['clear']
  1135. if not geo.is_empty:
  1136. gerber_code += '%LPC*%\n'
  1137. gerber_code += 'G36*\n'
  1138. geo_coords = list(geo.exterior.coords)
  1139. # first command is a move with pen-up D02 at the beginning of the geo
  1140. if g_zeros == 'T':
  1141. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1142. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1143. yform=y_formatted)
  1144. else:
  1145. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1146. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1147. yform=y_formatted)
  1148. prev_coord = geo_coords[0]
  1149. for coord in geo_coords[1:]:
  1150. if coord != prev_coord:
  1151. if g_zeros == 'T':
  1152. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1153. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1154. yform=y_formatted)
  1155. else:
  1156. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1157. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1158. yform=y_formatted)
  1159. prev_coord = coord
  1160. gerber_code += 'D02*\n'
  1161. gerber_code += 'G37*\n'
  1162. gerber_code += '%LPD*%\n'
  1163. for apid in self.apertures:
  1164. if apid == '0':
  1165. continue
  1166. else:
  1167. gerber_code += 'D%s*\n' % str(apid)
  1168. if 'geometry' in self.apertures[apid]:
  1169. for geo_elem in self.apertures[apid]['geometry']:
  1170. if 'follow' in geo_elem:
  1171. geo = geo_elem['follow']
  1172. if not geo.is_empty:
  1173. if isinstance(geo, Point):
  1174. if g_zeros == 'T':
  1175. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1176. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1177. yform=y_formatted)
  1178. else:
  1179. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1180. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1181. yform=y_formatted)
  1182. else:
  1183. geo_coords = list(geo.coords)
  1184. # first command is a move with pen-up D02 at the beginning of the geo
  1185. if g_zeros == 'T':
  1186. x_formatted, y_formatted = tz_format(
  1187. geo_coords[0][0], geo_coords[0][1], factor)
  1188. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1189. yform=y_formatted)
  1190. else:
  1191. x_formatted, y_formatted = lz_format(
  1192. geo_coords[0][0], geo_coords[0][1], factor)
  1193. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1194. yform=y_formatted)
  1195. prev_coord = geo_coords[0]
  1196. for coord in geo_coords[1:]:
  1197. if coord != prev_coord:
  1198. if g_zeros == 'T':
  1199. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1200. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1201. yform=y_formatted)
  1202. else:
  1203. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1204. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1205. yform=y_formatted)
  1206. prev_coord = coord
  1207. # gerber_code += "D02*\n"
  1208. if 'clear' in geo_elem:
  1209. gerber_code += '%LPC*%\n'
  1210. geo = geo_elem['clear']
  1211. if not geo.is_empty:
  1212. if isinstance(geo, Point):
  1213. if g_zeros == 'T':
  1214. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1215. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1216. yform=y_formatted)
  1217. else:
  1218. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1219. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1220. yform=y_formatted)
  1221. else:
  1222. geo_coords = list(geo.coords)
  1223. # first command is a move with pen-up D02 at the beginning of the geo
  1224. if g_zeros == 'T':
  1225. x_formatted, y_formatted = tz_format(
  1226. geo_coords[0][0], geo_coords[0][1], factor)
  1227. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1228. yform=y_formatted)
  1229. else:
  1230. x_formatted, y_formatted = lz_format(
  1231. geo_coords[0][0], geo_coords[0][1], factor)
  1232. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1233. yform=y_formatted)
  1234. prev_coord = geo_coords[0]
  1235. for coord in geo_coords[1:]:
  1236. if coord != prev_coord:
  1237. if g_zeros == 'T':
  1238. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1239. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1240. yform=y_formatted)
  1241. else:
  1242. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1243. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1244. yform=y_formatted)
  1245. prev_coord = coord
  1246. # gerber_code += "D02*\n"
  1247. gerber_code += '%LPD*%\n'
  1248. except Exception as e:
  1249. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> %s" % str(e))
  1250. if not self.apertures:
  1251. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1252. return 'fail'
  1253. return gerber_code
  1254. def mirror(self, axis, point):
  1255. Gerber.mirror(self, axis=axis, point=point)
  1256. self.replotApertures.emit()
  1257. def offset(self, vect):
  1258. Gerber.offset(self, vect=vect)
  1259. self.replotApertures.emit()
  1260. def rotate(self, angle, point):
  1261. Gerber.rotate(self, angle=angle, point=point)
  1262. self.replotApertures.emit()
  1263. def scale(self, xfactor, yfactor=None, point=None):
  1264. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1265. self.replotApertures.emit()
  1266. def skew(self, angle_x, angle_y, point):
  1267. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1268. self.replotApertures.emit()
  1269. def serialize(self):
  1270. return {
  1271. "options": self.options,
  1272. "kind": self.kind
  1273. }
  1274. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1275. """
  1276. Represents Excellon/Drill code.
  1277. """
  1278. ui_type = ExcellonObjectUI
  1279. optionChanged = QtCore.pyqtSignal(str)
  1280. def __init__(self, name):
  1281. Excellon.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  1282. FlatCAMObj.__init__(self, name)
  1283. self.kind = "excellon"
  1284. self.options.update({
  1285. "plot": True,
  1286. "solid": False,
  1287. "drillz": -0.1,
  1288. "travelz": 0.1,
  1289. "feedrate": 5.0,
  1290. "feedrate_rapid": 5.0,
  1291. "tooldia": 0.1,
  1292. "slot_tooldia": 0.1,
  1293. "toolchange": False,
  1294. "toolchangez": 1.0,
  1295. "toolchangexy": "0.0, 0.0",
  1296. "endz": 2.0,
  1297. "startz": None,
  1298. "spindlespeed": None,
  1299. "dwell": True,
  1300. "dwelltime": 1000,
  1301. "ppname_e": 'defaults',
  1302. "z_pdepth": -0.02,
  1303. "feedrate_probe": 3.0,
  1304. "optimization_type": "R",
  1305. "gcode_type": "drills"
  1306. })
  1307. # TODO: Document this.
  1308. self.tool_cbs = {}
  1309. # dict to hold the tool number as key and tool offset as value
  1310. self.tool_offset ={}
  1311. # variable to store the total amount of drills per job
  1312. self.tot_drill_cnt = 0
  1313. self.tool_row = 0
  1314. # variable to store the total amount of slots per job
  1315. self.tot_slot_cnt = 0
  1316. self.tool_row_slots = 0
  1317. # variable to store the distance travelled
  1318. self.travel_distance = 0.0
  1319. # store the source file here
  1320. self.source_file = ""
  1321. self.multigeo = False
  1322. # Attributes to be included in serialization
  1323. # Always append to it because it carries contents
  1324. # from predecessors.
  1325. self.ser_attrs += ['options', 'kind']
  1326. def merge(self, exc_list, exc_final):
  1327. """
  1328. Merge Excellon objects found in exc_list parameter into exc_final object.
  1329. Options are always copied from source .
  1330. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1331. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1332. tool_name to be used in the final Excellon object, exc_final.
  1333. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1334. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1335. :param exc_final: Destination FlatCAMExcellon object.
  1336. :return: None
  1337. """
  1338. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1339. flag_order = False
  1340. try:
  1341. flattened_list = list(itertools.chain(*exc_list))
  1342. except TypeError:
  1343. flattened_list = exc_list
  1344. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1345. # values will be list of Shapely Points; for drills
  1346. custom_dict_drills = {}
  1347. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1348. # values will be list of Shapely Points; for slots
  1349. custom_dict_slots = {}
  1350. for exc in flattened_list:
  1351. # copy options of the current excellon obj to the final excellon obj
  1352. for option in exc.options:
  1353. if option is not 'name':
  1354. try:
  1355. exc_final.options[option] = exc.options[option]
  1356. except:
  1357. exc.app.log.warning("Failed to copy option.", option)
  1358. for drill in exc.drills:
  1359. exc_tool_dia = float('%.4f' % exc.tools[drill['tool']]['C'])
  1360. if exc_tool_dia not in custom_dict_drills:
  1361. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1362. else:
  1363. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1364. for slot in exc.slots:
  1365. exc_tool_dia = float('%.4f' % exc.tools[slot['tool']]['C'])
  1366. if exc_tool_dia not in custom_dict_slots:
  1367. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1368. else:
  1369. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1370. # add the zeros and units to the exc_final object
  1371. exc_final.zeros = exc.zeros
  1372. exc_final.units = exc.units
  1373. # ##########################################
  1374. # Here we add data to the exc_final object #
  1375. # ##########################################
  1376. # variable to make tool_name for the tools
  1377. current_tool = 0
  1378. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1379. # drills
  1380. for tool_dia in custom_dict_drills:
  1381. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1382. current_tool += 1
  1383. tool_name = str(current_tool)
  1384. spec = {"C": float(tool_dia)}
  1385. exc_final.tools[tool_name] = spec
  1386. # rebuild the drills list of dict's that belong to the exc_final object
  1387. for point in custom_dict_drills[tool_dia]:
  1388. exc_final.drills.append(
  1389. {
  1390. "point": point,
  1391. "tool": str(current_tool)
  1392. }
  1393. )
  1394. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1395. # of two Shapely Points in case of slots
  1396. for tool_dia in custom_dict_slots:
  1397. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1398. # but only if there are no drills
  1399. if not exc_final.tools:
  1400. current_tool += 1
  1401. tool_name = str(current_tool)
  1402. spec = {"C": float(tool_dia)}
  1403. exc_final.tools[tool_name] = spec
  1404. else:
  1405. dia_list = []
  1406. for v in exc_final.tools.values():
  1407. dia_list.append(float(v["C"]))
  1408. if tool_dia not in dia_list:
  1409. flag_order = True
  1410. current_tool = len(dia_list) + 1
  1411. tool_name = str(current_tool)
  1412. spec = {"C": float(tool_dia)}
  1413. exc_final.tools[tool_name] = spec
  1414. else:
  1415. for k, v in exc_final.tools.items():
  1416. if v["C"] == tool_dia:
  1417. current_tool = int(k)
  1418. break
  1419. # rebuild the slots list of dict's that belong to the exc_final object
  1420. for point in custom_dict_slots[tool_dia]:
  1421. exc_final.slots.append(
  1422. {
  1423. "start": point[0],
  1424. "stop": point[1],
  1425. "tool": str(current_tool)
  1426. }
  1427. )
  1428. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1429. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1430. current_tool = 0
  1431. if flag_order is True:
  1432. dia_list = []
  1433. temp_drills = []
  1434. temp_slots = []
  1435. temp_tools = {}
  1436. for v in exc_final.tools.values():
  1437. dia_list.append(float(v["C"]))
  1438. dia_list.sort()
  1439. for ordered_dia in dia_list:
  1440. current_tool += 1
  1441. tool_name_temp = str(current_tool)
  1442. spec_temp = {"C": float(ordered_dia)}
  1443. temp_tools[tool_name_temp] = spec_temp
  1444. for drill in exc_final.drills:
  1445. exc_tool_dia = float('%.4f' % exc_final.tools[drill['tool']]['C'])
  1446. if exc_tool_dia == ordered_dia:
  1447. temp_drills.append(
  1448. {
  1449. "point": drill["point"],
  1450. "tool": str(current_tool)
  1451. }
  1452. )
  1453. for slot in exc_final.slots:
  1454. slot_tool_dia = float('%.4f' % exc_final.tools[slot['tool']]['C'])
  1455. if slot_tool_dia == ordered_dia:
  1456. temp_slots.append(
  1457. {
  1458. "start": slot["start"],
  1459. "stop": slot["stop"],
  1460. "tool": str(current_tool)
  1461. }
  1462. )
  1463. # delete the exc_final tools, drills and slots
  1464. exc_final.tools = dict()
  1465. exc_final.drills[:] = []
  1466. exc_final.slots[:] = []
  1467. # update the exc_final tools, drills and slots with the ordered values
  1468. exc_final.tools = temp_tools
  1469. exc_final.drills[:] = temp_drills
  1470. exc_final.slots[:] = temp_slots
  1471. # create the geometry for the exc_final object
  1472. exc_final.create_geometry()
  1473. def build_ui(self):
  1474. FlatCAMObj.build_ui(self)
  1475. try:
  1476. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1477. self.ui.tools_table.itemChanged.disconnect()
  1478. except:
  1479. pass
  1480. n = len(self.tools)
  1481. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1482. self.ui.tools_table.setRowCount(n + 2)
  1483. self.tot_drill_cnt = 0
  1484. self.tot_slot_cnt = 0
  1485. self.tool_row = 0
  1486. sort = []
  1487. for k, v in list(self.tools.items()):
  1488. sort.append((k, v.get('C')))
  1489. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1490. tools = [i[0] for i in sorted_tools]
  1491. for tool_no in tools:
  1492. drill_cnt = 0 # variable to store the nr of drills per tool
  1493. slot_cnt = 0 # variable to store the nr of slots per tool
  1494. # Find no of drills for the current tool
  1495. for drill in self.drills:
  1496. if drill['tool'] == tool_no:
  1497. drill_cnt += 1
  1498. self.tot_drill_cnt += drill_cnt
  1499. # Find no of slots for the current tool
  1500. for slot in self.slots:
  1501. if slot['tool'] == tool_no:
  1502. slot_cnt += 1
  1503. self.tot_slot_cnt += slot_cnt
  1504. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1505. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1506. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1507. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1508. # There are no drill bits in MM with more than 3 decimals diameter
  1509. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1510. if self.units == 'MM':
  1511. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1512. else:
  1513. dia = QtWidgets.QTableWidgetItem('%.4f' % (self.tools[tool_no]['C']))
  1514. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1515. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1516. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1517. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1518. if slot_cnt > 0:
  1519. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1520. else:
  1521. slot_count = QtWidgets.QTableWidgetItem('')
  1522. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1523. try:
  1524. if self.units == 'MM':
  1525. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1526. else:
  1527. t_offset = self.tool_offset[float('%.4f' % float(self.tools[tool_no]['C']))]
  1528. except KeyError:
  1529. t_offset = self.app.defaults['excellon_offset']
  1530. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1531. plot_item = FCCheckBox()
  1532. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1533. if self.ui.plot_cb.isChecked():
  1534. plot_item.setChecked(True)
  1535. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1536. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1537. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1538. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1539. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1540. self.tool_row += 1
  1541. # add a last row with the Total number of drills
  1542. empty = QtWidgets.QTableWidgetItem('')
  1543. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1544. empty_1 = QtWidgets.QTableWidgetItem('')
  1545. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1546. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1547. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1548. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1549. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1550. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1551. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1552. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1553. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1554. font = QtGui.QFont()
  1555. font.setBold(True)
  1556. font.setWeight(75)
  1557. for k in [1, 2]:
  1558. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1559. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1560. self.tool_row += 1
  1561. # add a last row with the Total number of slots
  1562. empty_2 = QtWidgets.QTableWidgetItem('')
  1563. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1564. empty_3 = QtWidgets.QTableWidgetItem('')
  1565. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1566. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1567. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1568. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1569. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1570. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1571. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1572. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1573. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1574. for kl in [1, 2, 3]:
  1575. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1576. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1577. # sort the tool diameter column
  1578. # self.ui.tools_table.sortItems(1)
  1579. # all the tools are selected by default
  1580. self.ui.tools_table.selectColumn(0)
  1581. #
  1582. self.ui.tools_table.resizeColumnsToContents()
  1583. self.ui.tools_table.resizeRowsToContents()
  1584. vertical_header = self.ui.tools_table.verticalHeader()
  1585. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1586. vertical_header.hide()
  1587. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1588. horizontal_header = self.ui.tools_table.horizontalHeader()
  1589. horizontal_header.setMinimumSectionSize(10)
  1590. horizontal_header.setDefaultSectionSize(70)
  1591. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1592. horizontal_header.resizeSection(0, 20)
  1593. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1594. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1595. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1596. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1597. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1598. horizontal_header.resizeSection(5, 17)
  1599. self.ui.tools_table.setColumnWidth(5, 17)
  1600. # horizontal_header.setStretchLastSection(True)
  1601. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1602. # horizontal_header.setStretchLastSection(True)
  1603. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1604. self.ui.tools_table.setSortingEnabled(False)
  1605. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1606. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1607. if not self.drills:
  1608. self.ui.tdlabel.hide()
  1609. self.ui.tooldia_entry.hide()
  1610. self.ui.generate_milling_button.hide()
  1611. else:
  1612. self.ui.tdlabel.show()
  1613. self.ui.tooldia_entry.show()
  1614. self.ui.generate_milling_button.show()
  1615. if not self.slots:
  1616. self.ui.stdlabel.hide()
  1617. self.ui.slot_tooldia_entry.hide()
  1618. self.ui.generate_milling_slots_button.hide()
  1619. else:
  1620. self.ui.stdlabel.show()
  1621. self.ui.slot_tooldia_entry.show()
  1622. self.ui.generate_milling_slots_button.show()
  1623. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1624. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1625. self.ui_connect()
  1626. def set_ui(self, ui):
  1627. """
  1628. Configures the user interface for this object.
  1629. Connects options to form fields.
  1630. :param ui: User interface object.
  1631. :type ui: ExcellonObjectUI
  1632. :return: None
  1633. """
  1634. FlatCAMObj.set_ui(self, ui)
  1635. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1636. self.form_fields.update({
  1637. "plot": self.ui.plot_cb,
  1638. "solid": self.ui.solid_cb,
  1639. "drillz": self.ui.cutz_entry,
  1640. "travelz": self.ui.travelz_entry,
  1641. "feedrate": self.ui.feedrate_entry,
  1642. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1643. "tooldia": self.ui.tooldia_entry,
  1644. "slot_tooldia": self.ui.slot_tooldia_entry,
  1645. "toolchange": self.ui.toolchange_cb,
  1646. "toolchangez": self.ui.toolchangez_entry,
  1647. "spindlespeed": self.ui.spindlespeed_entry,
  1648. "dwell": self.ui.dwell_cb,
  1649. "dwelltime": self.ui.dwelltime_entry,
  1650. "startz": self.ui.estartz_entry,
  1651. "endz": self.ui.eendz_entry,
  1652. "ppname_e": self.ui.pp_excellon_name_cb,
  1653. "z_pdepth": self.ui.pdepth_entry,
  1654. "feedrate_probe": self.ui.feedrate_probe_entry,
  1655. "gcode_type": self.ui.excellon_gcode_type_radio
  1656. })
  1657. for name in list(self.app.postprocessors.keys()):
  1658. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1659. if name == 'hpgl':
  1660. continue
  1661. self.ui.pp_excellon_name_cb.addItem(name)
  1662. # Fill form fields
  1663. self.to_form()
  1664. # initialize the dict that holds the tools offset
  1665. t_default_offset = self.app.defaults["excellon_offset"]
  1666. if not self.tool_offset:
  1667. for value in self.tools.values():
  1668. if self.units == 'MM':
  1669. dia = float('%.2f' % float(value['C']))
  1670. else:
  1671. dia = float('%.4f' % float(value['C']))
  1672. self.tool_offset[dia] = t_default_offset
  1673. # Show/Hide Advanced Options
  1674. if self.app.defaults["global_app_level"] == 'b':
  1675. self.ui.level.setText(_(
  1676. '<span style="color:green;"><b>Basic</b></span>'
  1677. ))
  1678. self.ui.tools_table.setColumnHidden(4, True)
  1679. self.ui.estartz_label.hide()
  1680. self.ui.estartz_entry.hide()
  1681. self.ui.eendz_label.hide()
  1682. self.ui.eendz_entry.hide()
  1683. self.ui.feedrate_rapid_label.hide()
  1684. self.ui.feedrate_rapid_entry.hide()
  1685. self.ui.pdepth_label.hide()
  1686. self.ui.pdepth_entry.hide()
  1687. self.ui.feedrate_probe_label.hide()
  1688. self.ui.feedrate_probe_entry.hide()
  1689. else:
  1690. self.ui.level.setText(_(
  1691. '<span style="color:red;"><b>Advanced</b></span>'
  1692. ))
  1693. assert isinstance(self.ui, ExcellonObjectUI), \
  1694. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1695. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1696. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1697. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1698. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1699. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1700. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1701. def ui_connect(self):
  1702. for row in range(self.ui.tools_table.rowCount() - 2):
  1703. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1704. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1705. def ui_disconnect(self):
  1706. for row in range(self.ui.tools_table.rowCount()):
  1707. try:
  1708. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1709. except:
  1710. pass
  1711. try:
  1712. self.ui.plot_cb.stateChanged.disconnect()
  1713. except:
  1714. pass
  1715. def on_tool_offset_edit(self):
  1716. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1717. self.ui.tools_table.itemChanged.disconnect()
  1718. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1719. self.is_modified = True
  1720. row_of_item_changed = self.ui.tools_table.currentRow()
  1721. if self.units == 'MM':
  1722. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1723. else:
  1724. dia = float('%.4f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1725. current_table_offset_edited = None
  1726. if self.ui.tools_table.currentItem() is not None:
  1727. try:
  1728. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1729. except ValueError:
  1730. # try to convert comma to decimal point. if it's still not working error message and return
  1731. try:
  1732. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1733. self.ui.tools_table.currentItem().setText(
  1734. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1735. except ValueError:
  1736. self.app.inform.emit(_(
  1737. "[ERROR_NOTCL] Wrong value format entered, use a number."
  1738. ))
  1739. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1740. return
  1741. self.tool_offset[dia] = current_table_offset_edited
  1742. # we reactivate the signals after the after the tool editing
  1743. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1744. def get_selected_tools_list(self):
  1745. """
  1746. Returns the keys to the self.tools dictionary corresponding
  1747. to the selections on the tool list in the GUI.
  1748. :return: List of tools.
  1749. :rtype: list
  1750. """
  1751. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1752. def get_selected_tools_table_items(self):
  1753. """
  1754. Returns a list of lists, each list in the list is made out of row elements
  1755. :return: List of table_tools items.
  1756. :rtype: list
  1757. """
  1758. table_tools_items = []
  1759. for x in self.ui.tools_table.selectedItems():
  1760. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1761. # which does not have text
  1762. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1763. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1764. for item in table_tools_items:
  1765. item[0] = str(item[0])
  1766. return table_tools_items
  1767. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1768. """
  1769. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1770. :return: has_slots and Excellon_code
  1771. """
  1772. excellon_code = ''
  1773. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1774. has_slots = 0
  1775. # drills processing
  1776. try:
  1777. if self.drills:
  1778. length = whole + fract
  1779. for tool in self.tools:
  1780. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1781. for drill in self.drills:
  1782. if form == 'dec' and tool == drill['tool']:
  1783. drill_x = drill['point'].x * factor
  1784. drill_y = drill['point'].y * factor
  1785. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1786. elif e_zeros == 'LZ' and tool == drill['tool']:
  1787. drill_x = drill['point'].x * factor
  1788. drill_y = drill['point'].y * factor
  1789. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1790. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1791. # extract whole part and decimal part
  1792. exc_x_formatted = exc_x_formatted.partition('.')
  1793. exc_y_formatted = exc_y_formatted.partition('.')
  1794. # left padd the 'whole' part with zeros
  1795. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1796. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1797. # restore the coordinate padded in the left with 0 and added the decimal part
  1798. # without the decinal dot
  1799. exc_x_formatted = x_whole + exc_x_formatted[2]
  1800. exc_y_formatted = y_whole + exc_y_formatted[2]
  1801. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1802. yform=exc_y_formatted)
  1803. elif tool == drill['tool']:
  1804. drill_x = drill['point'].x * factor
  1805. drill_y = drill['point'].y * factor
  1806. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1807. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1808. # pad with rear zeros
  1809. exc_x_formatted.ljust(length, '0')
  1810. exc_y_formatted.ljust(length, '0')
  1811. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1812. yform=exc_y_formatted)
  1813. except Exception as e:
  1814. log.debug(str(e))
  1815. # slots processing
  1816. try:
  1817. if self.slots:
  1818. has_slots = 1
  1819. for tool in self.tools:
  1820. if int(tool) < 10:
  1821. excellon_code += 'T0' + str(tool) + '\n'
  1822. else:
  1823. excellon_code += 'T' + str(tool) + '\n'
  1824. for slot in self.slots:
  1825. if form == 'dec' and tool == slot['tool']:
  1826. start_slot_x = slot['start'].x * factor
  1827. start_slot_y = slot['start'].y * factor
  1828. stop_slot_x = slot['stop'].x * factor
  1829. stop_slot_y = slot['stop'].y * factor
  1830. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1831. start_slot_y,
  1832. dec=fract)
  1833. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1834. stop_slot_y,
  1835. dec=fract)
  1836. elif e_zeros == 'LZ' and tool == slot['tool']:
  1837. start_slot_x = slot['start'].x * factor
  1838. start_slot_y = slot['start'].y * factor
  1839. stop_slot_x = slot['stop'].x * factor
  1840. stop_slot_y = slot['stop'].y * factor
  1841. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1842. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1843. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1844. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1845. # extract whole part and decimal part
  1846. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1847. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1848. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1849. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1850. # left padd the 'whole' part with zeros
  1851. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1852. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1853. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1854. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1855. # restore the coordinate padded in the left with 0 and added the decimal part
  1856. # without the decinal dot
  1857. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1858. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1859. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1860. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1861. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1862. ystart=start_slot_y_formatted)
  1863. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1864. ystop=stop_slot_y_formatted)
  1865. elif tool == slot['tool']:
  1866. start_slot_x = slot['start'].x * factor
  1867. start_slot_y = slot['start'].y * factor
  1868. stop_slot_x = slot['stop'].x * factor
  1869. stop_slot_y = slot['stop'].y * factor
  1870. length = whole + fract
  1871. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1872. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1873. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1874. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1875. # pad with rear zeros
  1876. start_slot_x_formatted.ljust(length, '0')
  1877. start_slot_y_formatted.ljust(length, '0')
  1878. stop_slot_x_formatted.ljust(length, '0')
  1879. stop_slot_y_formatted.ljust(length, '0')
  1880. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1881. ystart=start_slot_y_formatted)
  1882. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1883. ystop=stop_slot_y_formatted)
  1884. except Exception as e:
  1885. log.debug(str(e))
  1886. if not self.drills and not self.slots:
  1887. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1888. return 'fail'
  1889. return has_slots, excellon_code
  1890. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1891. """
  1892. Note: This method is a good template for generic operations as
  1893. it takes it's options from parameters or otherwise from the
  1894. object's options and returns a (success, msg) tuple as feedback
  1895. for shell operations.
  1896. :return: Success/failure condition tuple (bool, str).
  1897. :rtype: tuple
  1898. """
  1899. # Get the tools from the list. These are keys
  1900. # to self.tools
  1901. if tools is None:
  1902. tools = self.get_selected_tools_list()
  1903. if outname is None:
  1904. outname = self.options["name"] + "_mill"
  1905. if tooldia is None:
  1906. tooldia = float(self.options["tooldia"])
  1907. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1908. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1909. sort = []
  1910. for k, v in self.tools.items():
  1911. sort.append((k, v.get('C')))
  1912. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1913. if tools == "all":
  1914. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1915. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1916. if len(tools) == 0:
  1917. self.app.inform.emit(_(
  1918. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1919. ))
  1920. return False, "Error: No tools."
  1921. for tool in tools:
  1922. if tooldia > self.tools[tool]["C"]:
  1923. self.app.inform.emit(_(
  1924. "[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled."
  1925. ))
  1926. return False, "Error: Milling tool is larger than hole."
  1927. def geo_init(geo_obj, app_obj):
  1928. assert isinstance(geo_obj, FlatCAMGeometry), \
  1929. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1930. app_obj.progress.emit(20)
  1931. # ## Add properties to the object
  1932. # get the tool_table items in a list of row items
  1933. tool_table_items = self.get_selected_tools_table_items()
  1934. # insert an information only element in the front
  1935. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1936. geo_obj.options['Tools_in_use'] = tool_table_items
  1937. geo_obj.options['type'] = 'Excellon Geometry'
  1938. geo_obj.options["cnctooldia"] = str(tooldia)
  1939. geo_obj.solid_geometry = []
  1940. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1941. # for FlatCAM is 6 decimals,
  1942. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1943. for hole in self.drills:
  1944. if hole['tool'] in tools:
  1945. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1946. if buffer_value == 0:
  1947. geo_obj.solid_geometry.append(
  1948. Point(hole['point']).buffer(0.0000001).exterior)
  1949. else:
  1950. geo_obj.solid_geometry.append(
  1951. Point(hole['point']).buffer(buffer_value).exterior)
  1952. if use_thread:
  1953. def geo_thread(app_obj):
  1954. app_obj.new_object("geometry", outname, geo_init)
  1955. app_obj.progress.emit(100)
  1956. # Create a promise with the new name
  1957. self.app.collection.promise(outname)
  1958. # Send to worker
  1959. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1960. else:
  1961. self.app.new_object("geometry", outname, geo_init)
  1962. return True, ""
  1963. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1964. """
  1965. Note: This method is a good template for generic operations as
  1966. it takes it's options from parameters or otherwise from the
  1967. object's options and returns a (success, msg) tuple as feedback
  1968. for shell operations.
  1969. :return: Success/failure condition tuple (bool, str).
  1970. :rtype: tuple
  1971. """
  1972. # Get the tools from the list. These are keys
  1973. # to self.tools
  1974. if tools is None:
  1975. tools = self.get_selected_tools_list()
  1976. if outname is None:
  1977. outname = self.options["name"] + "_mill"
  1978. if tooldia is None:
  1979. tooldia = float(self.options["slot_tooldia"])
  1980. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1981. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1982. sort = []
  1983. for k, v in self.tools.items():
  1984. sort.append((k, v.get('C')))
  1985. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1986. if tools == "all":
  1987. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1988. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1989. if len(tools) == 0:
  1990. self.app.inform.emit(_(
  1991. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1992. ))
  1993. return False, "Error: No tools."
  1994. for tool in tools:
  1995. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1996. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  1997. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  1998. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1999. self.app.inform.emit(_(
  2000. "[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled."
  2001. ))
  2002. return False, "Error: Milling tool is larger than hole."
  2003. def geo_init(geo_obj, app_obj):
  2004. assert isinstance(geo_obj, FlatCAMGeometry), \
  2005. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2006. app_obj.progress.emit(20)
  2007. # ## Add properties to the object
  2008. # get the tool_table items in a list of row items
  2009. tool_table_items = self.get_selected_tools_table_items()
  2010. # insert an information only element in the front
  2011. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2012. geo_obj.options['Tools_in_use'] = tool_table_items
  2013. geo_obj.options['type'] = 'Excellon Geometry'
  2014. geo_obj.options["cnctooldia"] = str(tooldia)
  2015. geo_obj.solid_geometry = []
  2016. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2017. # for FlatCAM is 6 decimals,
  2018. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2019. for slot in self.slots:
  2020. if slot['tool'] in tools:
  2021. toolstable_tool = float('%.4f' % float(tooldia))
  2022. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  2023. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2024. # for the file_tool (tooldia actually)
  2025. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2026. if buffer_value == 0:
  2027. start = slot['start']
  2028. stop = slot['stop']
  2029. lines_string = LineString([start, stop])
  2030. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2031. geo_obj.solid_geometry.append(poly)
  2032. else:
  2033. start = slot['start']
  2034. stop = slot['stop']
  2035. lines_string = LineString([start, stop])
  2036. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2037. geo_obj.solid_geometry.append(poly)
  2038. if use_thread:
  2039. def geo_thread(app_obj):
  2040. app_obj.new_object("geometry", outname + '_slot', geo_init)
  2041. app_obj.progress.emit(100)
  2042. # Create a promise with the new name
  2043. self.app.collection.promise(outname)
  2044. # Send to worker
  2045. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2046. else:
  2047. self.app.new_object("geometry", outname + '_slot', geo_init)
  2048. return True, ""
  2049. def on_generate_milling_button_click(self, *args):
  2050. self.app.report_usage("excellon_on_create_milling_drills button")
  2051. self.read_form()
  2052. self.generate_milling_drills(use_thread=False)
  2053. def on_generate_milling_slots_button_click(self, *args):
  2054. self.app.report_usage("excellon_on_create_milling_slots_button")
  2055. self.read_form()
  2056. self.generate_milling_slots(use_thread=False)
  2057. def on_pp_changed(self):
  2058. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2059. if "toolchange_probe" in current_pp.lower():
  2060. self.ui.pdepth_entry.setVisible(True)
  2061. self.ui.pdepth_label.show()
  2062. self.ui.feedrate_probe_entry.setVisible(True)
  2063. self.ui.feedrate_probe_label.show()
  2064. else:
  2065. self.ui.pdepth_entry.setVisible(False)
  2066. self.ui.pdepth_label.hide()
  2067. self.ui.feedrate_probe_entry.setVisible(False)
  2068. self.ui.feedrate_probe_label.hide()
  2069. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2070. self.ui.feedrate_rapid_label.show()
  2071. self.ui.feedrate_rapid_entry.show()
  2072. else:
  2073. self.ui.feedrate_rapid_label.hide()
  2074. self.ui.feedrate_rapid_entry.hide()
  2075. def on_create_cncjob_button_click(self, *args):
  2076. self.app.report_usage("excellon_on_create_cncjob_button")
  2077. self.read_form()
  2078. # Get the tools from the list
  2079. tools = self.get_selected_tools_list()
  2080. if len(tools) == 0:
  2081. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  2082. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  2083. # in this case regardless of the selection status of that tool, use it.
  2084. if self.ui.tools_table.rowCount() == 3:
  2085. tools.append(self.ui.tools_table.item(0, 0).text())
  2086. else:
  2087. self.app.inform.emit(_(
  2088. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  2089. ))
  2090. return
  2091. xmin = self.options['xmin']
  2092. ymin = self.options['ymin']
  2093. xmax = self.options['xmax']
  2094. ymax = self.options['ymax']
  2095. job_name = self.options["name"] + "_cnc"
  2096. pp_excellon_name = self.options["ppname_e"]
  2097. # Object initialization function for app.new_object()
  2098. def job_init(job_obj, app_obj):
  2099. assert isinstance(job_obj, FlatCAMCNCjob), \
  2100. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2101. # get the tool_table items in a list of row items
  2102. tool_table_items = self.get_selected_tools_table_items()
  2103. # insert an information only element in the front
  2104. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2105. # ## Add properties to the object
  2106. job_obj.origin_kind = 'excellon'
  2107. job_obj.options['Tools_in_use'] = tool_table_items
  2108. job_obj.options['type'] = 'Excellon'
  2109. job_obj.options['ppname_e'] = pp_excellon_name
  2110. app_obj.progress.emit(20)
  2111. job_obj.z_cut = float(self.options["drillz"])
  2112. job_obj.tool_offset = self.tool_offset
  2113. job_obj.z_move = float(self.options["travelz"])
  2114. job_obj.feedrate = float(self.options["feedrate"])
  2115. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  2116. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  2117. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  2118. job_obj.dwell = self.options["dwell"]
  2119. job_obj.dwelltime = float(self.options["dwelltime"])
  2120. job_obj.pp_excellon_name = pp_excellon_name
  2121. job_obj.toolchange_xy_type = "excellon"
  2122. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  2123. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  2124. job_obj.options['xmin'] = xmin
  2125. job_obj.options['ymin'] = ymin
  2126. job_obj.options['xmax'] = xmax
  2127. job_obj.options['ymax'] = ymax
  2128. try:
  2129. job_obj.z_pdepth = float(self.options["z_pdepth"])
  2130. except ValueError:
  2131. # try to convert comma to decimal point. if it's still not working error message and return
  2132. try:
  2133. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  2134. except ValueError:
  2135. self.app.inform.emit(
  2136. _(
  2137. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  2138. ))
  2139. try:
  2140. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  2141. except ValueError:
  2142. # try to convert comma to decimal point. if it's still not working error message and return
  2143. try:
  2144. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  2145. except ValueError:
  2146. self.app.inform.emit(
  2147. _(
  2148. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  2149. 'or self.options["feedrate_probe"]'
  2150. )
  2151. )
  2152. # There could be more than one drill size...
  2153. # job_obj.tooldia = # TODO: duplicate variable!
  2154. # job_obj.options["tooldia"] =
  2155. tools_csv = ','.join(tools)
  2156. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  2157. drillz=float(self.options['drillz']),
  2158. toolchange=self.options["toolchange"],
  2159. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  2160. toolchangez=float(self.options["toolchangez"]),
  2161. startz=float(self.options["startz"]) if
  2162. self.options["startz"] else None,
  2163. endz=float(self.options["endz"]),
  2164. excellon_optimization_type=self.app.defaults[
  2165. "excellon_optimization_type"])
  2166. if ret_val == 'fail':
  2167. return 'fail'
  2168. app_obj.progress.emit(50)
  2169. job_obj.gcode_parse()
  2170. app_obj.progress.emit(60)
  2171. job_obj.create_geometry()
  2172. app_obj.progress.emit(80)
  2173. # To be run in separate thread
  2174. def job_thread(app_obj):
  2175. with self.app.proc_container.new(_("Generating CNC Code")):
  2176. app_obj.new_object("cncjob", job_name, job_init)
  2177. app_obj.progress.emit(100)
  2178. # Create promise for the new name.
  2179. self.app.collection.promise(job_name)
  2180. # Send to worker
  2181. # self.app.worker.add_task(job_thread, [self.app])
  2182. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2183. def convert_units(self, units):
  2184. factor = Excellon.convert_units(self, units)
  2185. self.options['drillz'] = float(self.options['drillz']) * factor
  2186. self.options['travelz'] = float(self.options['travelz']) * factor
  2187. self.options['feedrate'] = float(self.options['feedrate']) * factor
  2188. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  2189. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  2190. if self.app.defaults["excellon_toolchangexy"] == '':
  2191. self.options['toolchangexy'] = "0.0, 0.0"
  2192. else:
  2193. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  2194. if len(coords_xy) < 2:
  2195. self.app.inform.emit(_(
  2196. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  2197. "in the format (x, y) \nbut now there is only one value, not two. "
  2198. ))
  2199. return 'fail'
  2200. coords_xy[0] *= factor
  2201. coords_xy[1] *= factor
  2202. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2203. if self.options['startz'] is not None:
  2204. self.options['startz'] = float(self.options['startz']) * factor
  2205. self.options['endz'] = float(self.options['endz']) * factor
  2206. def on_solid_cb_click(self, *args):
  2207. if self.muted_ui:
  2208. return
  2209. self.read_form_item('solid')
  2210. self.plot()
  2211. def on_plot_cb_click(self, *args):
  2212. if self.muted_ui:
  2213. return
  2214. self.plot()
  2215. self.read_form_item('plot')
  2216. self.ui_disconnect()
  2217. cb_flag = self.ui.plot_cb.isChecked()
  2218. for row in range(self.ui.tools_table.rowCount() - 2):
  2219. table_cb = self.ui.tools_table.cellWidget(row, 5)
  2220. if cb_flag:
  2221. table_cb.setChecked(True)
  2222. else:
  2223. table_cb.setChecked(False)
  2224. self.ui_connect()
  2225. def on_plot_cb_click_table(self):
  2226. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2227. self.ui_disconnect()
  2228. # cw = self.sender()
  2229. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  2230. # cw_row = cw_index.row()
  2231. check_row = 0
  2232. self.shapes.clear(update=True)
  2233. for tool_key in self.tools:
  2234. solid_geometry = self.tools[tool_key]['solid_geometry']
  2235. # find the geo_tool_table row associated with the tool_key
  2236. for row in range(self.ui.tools_table.rowCount()):
  2237. tool_item = int(self.ui.tools_table.item(row, 0).text())
  2238. if tool_item == int(tool_key):
  2239. check_row = row
  2240. break
  2241. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  2242. self.options['plot'] = True
  2243. # self.plot_element(element=solid_geometry, visible=True)
  2244. # Plot excellon (All polygons?)
  2245. if self.options["solid"]:
  2246. for geo in solid_geometry:
  2247. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2248. visible=self.options['plot'],
  2249. layer=2)
  2250. else:
  2251. for geo in solid_geometry:
  2252. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2253. for ints in geo.interiors:
  2254. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2255. self.shapes.redraw()
  2256. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2257. # if all the row plot's are enabled also enable the general plot checkbox
  2258. cb_cnt = 0
  2259. total_row = self.ui.tools_table.rowCount()
  2260. for row in range(total_row - 2):
  2261. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  2262. cb_cnt += 1
  2263. else:
  2264. cb_cnt -= 1
  2265. if cb_cnt < total_row - 2:
  2266. self.ui.plot_cb.setChecked(False)
  2267. else:
  2268. self.ui.plot_cb.setChecked(True)
  2269. self.ui_connect()
  2270. # def plot_element(self, element, color='red', visible=None, layer=None):
  2271. #
  2272. # visible = visible if visible else self.options['plot']
  2273. #
  2274. # try:
  2275. # for sub_el in element:
  2276. # self.plot_element(sub_el)
  2277. #
  2278. # except TypeError: # Element is not iterable...
  2279. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2280. def plot(self, kind=None):
  2281. # Does all the required setup and returns False
  2282. # if the 'ptint' option is set to False.
  2283. if not FlatCAMObj.plot(self):
  2284. return
  2285. # try:
  2286. # # Plot Excellon (All polygons?)
  2287. # if self.options["solid"]:
  2288. # for tool in self.tools:
  2289. # for geo in self.tools[tool]['solid_geometry']:
  2290. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2291. # visible=self.options['plot'],
  2292. # layer=2)
  2293. # else:
  2294. # for tool in self.tools:
  2295. # for geo in self.tools[tool]['solid_geometry']:
  2296. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2297. # for ints in geo.interiors:
  2298. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2299. #
  2300. # self.shapes.redraw()
  2301. # return
  2302. # except (ObjectDeleted, AttributeError, KeyError):
  2303. # self.shapes.clear(update=True)
  2304. # this stays for compatibility reasons, in case we try to open old projects
  2305. try:
  2306. __ = iter(self.solid_geometry)
  2307. except TypeError:
  2308. self.solid_geometry = [self.solid_geometry]
  2309. try:
  2310. # Plot Excellon (All polygons?)
  2311. if self.options["solid"]:
  2312. for geo in self.solid_geometry:
  2313. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2314. visible=self.options['plot'],
  2315. layer=2)
  2316. else:
  2317. for geo in self.solid_geometry:
  2318. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2319. for ints in geo.interiors:
  2320. self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2321. self.shapes.redraw()
  2322. except (ObjectDeleted, AttributeError):
  2323. self.shapes.clear(update=True)
  2324. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2325. """
  2326. Geometric object not associated with a specific
  2327. format.
  2328. """
  2329. optionChanged = QtCore.pyqtSignal(str)
  2330. ui_type = GeometryObjectUI
  2331. def merge(self, geo_list, geo_final, multigeo=None):
  2332. """
  2333. Merges the geometry of objects in grb_list into
  2334. the geometry of geo_final.
  2335. :param geo_list: List of FlatCAMGerber Objects to join.
  2336. :param geo_final: Destination FlatCAMGerber object.
  2337. :return: None
  2338. """
  2339. if geo_final.solid_geometry is None:
  2340. geo_final.solid_geometry = []
  2341. if type(geo_final.solid_geometry) is not list:
  2342. geo_final.solid_geometry = [geo_final.solid_geometry]
  2343. for geo in geo_list:
  2344. for option in geo.options:
  2345. if option is not 'name':
  2346. try:
  2347. geo_final.options[option] = geo.options[option]
  2348. except:
  2349. log.warning("Failed to copy option.", option)
  2350. # Expand lists
  2351. if type(geo) is list:
  2352. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  2353. # If not list, just append
  2354. else:
  2355. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  2356. if multigeo is None or multigeo is False:
  2357. geo_final.multigeo = False
  2358. try:
  2359. geo_final.solid_geometry.append(geo.solid_geometry)
  2360. except Exception as e:
  2361. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  2362. else:
  2363. geo_final.multigeo = True
  2364. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  2365. # tools object attribute, as a key value
  2366. geo_final.solid_geometry = []
  2367. # find the tool_uid maximum value in the geo_final
  2368. geo_final_uid_list = []
  2369. for key in geo_final.tools:
  2370. geo_final_uid_list.append(int(key))
  2371. try:
  2372. max_uid = max(geo_final_uid_list, key=int)
  2373. except ValueError:
  2374. max_uid = 0
  2375. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2376. # to merge the obj.tools as it is likely there is none to merge.
  2377. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  2378. for tool_uid in geo.tools:
  2379. max_uid += 1
  2380. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  2381. @staticmethod
  2382. def get_pts(o):
  2383. """
  2384. Returns a list of all points in the object, where
  2385. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2386. of such. Search is done recursively.
  2387. :param: geometric object
  2388. :return: List of points
  2389. :rtype: list
  2390. """
  2391. pts = []
  2392. # Iterable: descend into each item.
  2393. try:
  2394. for subo in o:
  2395. pts += FlatCAMGeometry.get_pts(subo)
  2396. # Non-iterable
  2397. except TypeError:
  2398. if o is not None:
  2399. if type(o) == MultiPolygon:
  2400. for poly in o:
  2401. pts += FlatCAMGeometry.get_pts(poly)
  2402. # ## Descend into .exerior and .interiors
  2403. elif type(o) == Polygon:
  2404. pts += FlatCAMGeometry.get_pts(o.exterior)
  2405. for i in o.interiors:
  2406. pts += FlatCAMGeometry.get_pts(i)
  2407. elif type(o) == MultiLineString:
  2408. for line in o:
  2409. pts += FlatCAMGeometry.get_pts(line)
  2410. # ## Has .coords: list them.
  2411. else:
  2412. pts += list(o.coords)
  2413. else:
  2414. return
  2415. return pts
  2416. def __init__(self, name):
  2417. FlatCAMObj.__init__(self, name)
  2418. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2419. self.kind = "geometry"
  2420. self.options.update({
  2421. "plot": True,
  2422. "cutz": -0.002,
  2423. "vtipdia": 0.1,
  2424. "vtipangle": 30,
  2425. "travelz": 0.1,
  2426. "feedrate": 5.0,
  2427. "feedrate_z": 5.0,
  2428. "feedrate_rapid": 5.0,
  2429. "spindlespeed": None,
  2430. "dwell": True,
  2431. "dwelltime": 1000,
  2432. "multidepth": False,
  2433. "depthperpass": 0.002,
  2434. "extracut": False,
  2435. "endz": 2.0,
  2436. "toolchange": False,
  2437. "toolchangez": 1.0,
  2438. "toolchangexy": "0.0, 0.0",
  2439. "startz": None,
  2440. "ppname_g": 'default',
  2441. "z_pdepth": -0.02,
  2442. "feedrate_probe": 3.0,
  2443. })
  2444. if "cnctooldia" not in self.options:
  2445. # self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2446. try:
  2447. self.options["cnctooldia"] = [
  2448. float(eval(dia)) for dia in str(self.app.defaults["geometry_cnctooldia"]).split(",")
  2449. ]
  2450. except Exception as e:
  2451. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> Geometry General -> "
  2452. "Tool dia. %s" % str(e))
  2453. return
  2454. self.options["startz"] = self.app.defaults["geometry_startz"]
  2455. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2456. self.tooluid = 0
  2457. '''
  2458. self.tools = {}
  2459. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2460. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2461. {tooluid: {
  2462. 'tooldia': 1,
  2463. 'offset': 'Path',
  2464. 'offset_value': 0.0
  2465. 'type': 'Rough',
  2466. 'tool_type': 'C1',
  2467. 'data': self.default_tool_data
  2468. 'solid_geometry': []
  2469. }
  2470. }
  2471. '''
  2472. self.tools = {}
  2473. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2474. # those elements are the ones used for generating GCode
  2475. self.sel_tools = {}
  2476. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2477. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  2478. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2479. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2480. self.v_tool_type = None
  2481. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2482. # the default value is False
  2483. self.multigeo = False
  2484. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2485. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2486. self. special_group = None
  2487. self.old_pp_state = ''
  2488. self.old_toolchangeg_state = ''
  2489. # Attributes to be included in serialization
  2490. # Always append to it because it carries contents
  2491. # from predecessors.
  2492. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2493. def build_ui(self):
  2494. self.ui_disconnect()
  2495. FlatCAMObj.build_ui(self)
  2496. offset = 0
  2497. tool_idx = 0
  2498. n = len(self.tools)
  2499. self.ui.geo_tools_table.setRowCount(n)
  2500. for tooluid_key, tooluid_value in self.tools.items():
  2501. tool_idx += 1
  2502. row_no = tool_idx - 1
  2503. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2504. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2505. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2506. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2507. # There are no tool bits in MM with more than 3 decimals diameter.
  2508. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2509. if self.units == 'MM':
  2510. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2511. else:
  2512. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2513. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2514. offset_item = QtWidgets.QComboBox()
  2515. for item in self.offset_item_options:
  2516. offset_item.addItem(item)
  2517. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2518. idx = offset_item.findText(tooluid_value['offset'])
  2519. offset_item.setCurrentIndex(idx)
  2520. type_item = QtWidgets.QComboBox()
  2521. for item in self.type_item_options:
  2522. type_item.addItem(item)
  2523. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2524. idx = type_item.findText(tooluid_value['type'])
  2525. type_item.setCurrentIndex(idx)
  2526. tool_type_item = QtWidgets.QComboBox()
  2527. for item in self.tool_type_item_options:
  2528. tool_type_item.addItem(item)
  2529. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2530. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2531. tool_type_item.setCurrentIndex(idx)
  2532. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2533. plot_item = FCCheckBox()
  2534. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2535. if self.ui.plot_cb.isChecked():
  2536. plot_item.setChecked(True)
  2537. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2538. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2539. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2540. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2541. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  2542. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2543. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2544. try:
  2545. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2546. except:
  2547. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2548. # make the diameter column editable
  2549. for row in range(tool_idx):
  2550. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2551. QtCore.Qt.ItemIsEditable |
  2552. QtCore.Qt.ItemIsEnabled)
  2553. # sort the tool diameter column
  2554. # self.ui.geo_tools_table.sortItems(1)
  2555. # all the tools are selected by default
  2556. # self.ui.geo_tools_table.selectColumn(0)
  2557. self.ui.geo_tools_table.resizeColumnsToContents()
  2558. self.ui.geo_tools_table.resizeRowsToContents()
  2559. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2560. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2561. vertical_header.hide()
  2562. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2563. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2564. horizontal_header.setMinimumSectionSize(10)
  2565. horizontal_header.setDefaultSectionSize(70)
  2566. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2567. horizontal_header.resizeSection(0, 20)
  2568. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2569. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2570. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2571. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2572. horizontal_header.resizeSection(4, 40)
  2573. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2574. horizontal_header.resizeSection(4, 17)
  2575. # horizontal_header.setStretchLastSection(True)
  2576. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2577. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2578. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2579. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2580. # self.ui.geo_tools_table.setSortingEnabled(True)
  2581. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2582. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2583. # update UI for all rows - useful after units conversion but only if there is at least one row
  2584. row_cnt = self.ui.geo_tools_table.rowCount()
  2585. if row_cnt > 0:
  2586. for r in range(row_cnt):
  2587. self.update_ui(r)
  2588. # select only the first tool / row
  2589. selected_row = 0
  2590. try:
  2591. self.select_tools_table_row(selected_row, clearsel=True)
  2592. # update the Geometry UI
  2593. self.update_ui()
  2594. except Exception as e:
  2595. # when the tools table is empty there will be this error but once the table is populated it will go away
  2596. log.debug(str(e))
  2597. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2598. # and can create some problems
  2599. if self.multigeo is False:
  2600. self.ui.geo_tools_table.setColumnHidden(6, True)
  2601. else:
  2602. self.ui.geo_tools_table.setColumnHidden(6, False)
  2603. self.set_tool_offset_visibility(selected_row)
  2604. self.ui_connect()
  2605. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  2606. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  2607. self.ui.name_entry.set_value(self.options['name'])
  2608. def set_ui(self, ui):
  2609. FlatCAMObj.set_ui(self, ui)
  2610. log.debug("FlatCAMGeometry.set_ui()")
  2611. assert isinstance(self.ui, GeometryObjectUI), \
  2612. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2613. # populate postprocessor names in the combobox
  2614. for name in list(self.app.postprocessors.keys()):
  2615. self.ui.pp_geometry_name_cb.addItem(name)
  2616. self.form_fields.update({
  2617. "plot": self.ui.plot_cb,
  2618. "cutz": self.ui.cutz_entry,
  2619. "vtipdia": self.ui.tipdia_entry,
  2620. "vtipangle": self.ui.tipangle_entry,
  2621. "travelz": self.ui.travelz_entry,
  2622. "feedrate": self.ui.cncfeedrate_entry,
  2623. "feedrate_z": self.ui.cncplunge_entry,
  2624. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2625. "spindlespeed": self.ui.cncspindlespeed_entry,
  2626. "dwell": self.ui.dwell_cb,
  2627. "dwelltime": self.ui.dwelltime_entry,
  2628. "multidepth": self.ui.mpass_cb,
  2629. "ppname_g": self.ui.pp_geometry_name_cb,
  2630. "z_pdepth": self.ui.pdepth_entry,
  2631. "feedrate_probe": self.ui.feedrate_probe_entry,
  2632. "depthperpass": self.ui.maxdepth_entry,
  2633. "extracut": self.ui.extracut_cb,
  2634. "toolchange": self.ui.toolchangeg_cb,
  2635. "toolchangez": self.ui.toolchangez_entry,
  2636. "endz": self.ui.gendz_entry,
  2637. })
  2638. # Fill form fields only on object create
  2639. self.to_form()
  2640. self.ui.tipdialabel.hide()
  2641. self.ui.tipdia_entry.hide()
  2642. self.ui.tipanglelabel.hide()
  2643. self.ui.tipangle_entry.hide()
  2644. self.ui.cutz_entry.setDisabled(False)
  2645. # store here the default data for Geometry Data
  2646. self.default_data = {}
  2647. self.default_data.update({
  2648. "name": None,
  2649. "plot": None,
  2650. "cutz": None,
  2651. "vtipdia": None,
  2652. "vtipangle": None,
  2653. "travelz": None,
  2654. "feedrate": None,
  2655. "feedrate_z": None,
  2656. "feedrate_rapid": None,
  2657. "dwell": None,
  2658. "dwelltime": None,
  2659. "multidepth": None,
  2660. "ppname_g": None,
  2661. "depthperpass": None,
  2662. "extracut": None,
  2663. "toolchange": None,
  2664. "toolchangez": None,
  2665. "endz": None,
  2666. "spindlespeed": None,
  2667. "toolchangexy": None,
  2668. "startz": None
  2669. })
  2670. # fill in self.default_data values from self.options
  2671. for def_key in self.default_data:
  2672. for opt_key, opt_val in self.options.items():
  2673. if def_key == opt_key:
  2674. self.default_data[def_key] = deepcopy(opt_val)
  2675. try:
  2676. tools_list = [
  2677. float(eval(dia)) for dia in self.options["cnctooldia"].split(",")
  2678. ]
  2679. except Exception as e:
  2680. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> Geometry General -> "
  2681. "Tool dia. %s" % str(e))
  2682. return
  2683. self.tooluid += 1
  2684. if not self.tools:
  2685. for toold in tools_list:
  2686. self.tools.update({
  2687. self.tooluid: {
  2688. 'tooldia': float(toold),
  2689. 'offset': ('Path'),
  2690. 'offset_value': 0.0,
  2691. 'type': _('Rough'),
  2692. 'tool_type': 'C1',
  2693. 'data': self.default_data,
  2694. 'solid_geometry': self.solid_geometry
  2695. }
  2696. })
  2697. self.tooluid += 1
  2698. else:
  2699. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2700. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2701. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2702. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2703. # following convoluted way of changing the keys from string to float type
  2704. temp_tools = {}
  2705. new_key = 0.0
  2706. for tooluid_key in self.tools:
  2707. val = deepcopy(self.tools[tooluid_key])
  2708. new_key = deepcopy(int(tooluid_key))
  2709. temp_tools[new_key] = val
  2710. self.tools.clear()
  2711. self.tools = deepcopy(temp_tools)
  2712. self.ui.tool_offset_entry.hide()
  2713. self.ui.tool_offset_lbl.hide()
  2714. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2715. self.old_pp_state = self.default_data['multidepth']
  2716. self.old_toolchangeg_state = self.default_data['toolchange']
  2717. if not isinstance(self.ui, GeometryObjectUI):
  2718. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2719. return
  2720. self.ui.geo_tools_table.setupContextMenu()
  2721. self.ui.geo_tools_table.addContextMenu(
  2722. _("Copy"), self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2723. self.ui.geo_tools_table.addContextMenu(
  2724. _("Delete"), lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2725. # Show/Hide Advanced Options
  2726. if self.app.defaults["global_app_level"] == 'b':
  2727. self.ui.level.setText(_(
  2728. '<span style="color:green;"><b>Basic</b></span>'
  2729. ))
  2730. self.ui.geo_tools_table.setColumnHidden(2, True)
  2731. self.ui.geo_tools_table.setColumnHidden(3, True)
  2732. self.ui.geo_tools_table.setColumnHidden(4, True)
  2733. self.ui.addtool_entry_lbl.hide()
  2734. self.ui.addtool_entry.hide()
  2735. self.ui.addtool_btn.hide()
  2736. self.ui.copytool_btn.hide()
  2737. self.ui.deltool_btn.hide()
  2738. self.ui.endzlabel.hide()
  2739. self.ui.gendz_entry.hide()
  2740. self.ui.fr_rapidlabel.hide()
  2741. self.ui.cncfeedrate_rapid_entry.hide()
  2742. self.ui.extracut_cb.hide()
  2743. self.ui.pdepth_label.hide()
  2744. self.ui.pdepth_entry.hide()
  2745. self.ui.feedrate_probe_label.hide()
  2746. self.ui.feedrate_probe_entry.hide()
  2747. else:
  2748. self.ui.level.setText(_(
  2749. '<span style="color:red;"><b>Advanced</b></span>'
  2750. ))
  2751. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2752. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2753. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  2754. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2755. self.ui.addtool_entry.returnPressed.connect(lambda: self.on_tool_add())
  2756. def set_tool_offset_visibility(self, current_row):
  2757. if current_row is None:
  2758. return
  2759. try:
  2760. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2761. if tool_offset is not None:
  2762. tool_offset_txt = tool_offset.currentText()
  2763. if tool_offset_txt == ('Custom'):
  2764. self.ui.tool_offset_entry.show()
  2765. self.ui.tool_offset_lbl.show()
  2766. else:
  2767. self.ui.tool_offset_entry.hide()
  2768. self.ui.tool_offset_lbl.hide()
  2769. except Exception as e:
  2770. log.debug("set_tool_offset_visibility() --> " + str(e))
  2771. return
  2772. def on_offset_value_edited(self):
  2773. """
  2774. This will save the offset_value into self.tools storage whenever the offset value is edited
  2775. :return:
  2776. """
  2777. for current_row in self.ui.geo_tools_table.selectedItems():
  2778. # sometime the header get selected and it has row number -1
  2779. # we don't want to do anything with the header :)
  2780. if current_row.row() < 0:
  2781. continue
  2782. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2783. self.set_tool_offset_visibility(current_row.row())
  2784. for tooluid_key, tooluid_value in self.tools.items():
  2785. if int(tooluid_key) == tool_uid:
  2786. try:
  2787. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2788. except ValueError:
  2789. # try to convert comma to decimal point. if it's still not working error message and return
  2790. try:
  2791. tooluid_value['offset_value'] = float(
  2792. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2793. )
  2794. except ValueError:
  2795. self.app.inform.emit(_(
  2796. "[ERROR_NOTCL] Wrong value format entered, "
  2797. "use a number."
  2798. )
  2799. )
  2800. return
  2801. def ui_connect(self):
  2802. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2803. # changes in geometry UI
  2804. for i in range(self.ui.grid3.count()):
  2805. try:
  2806. # works for CheckBoxes
  2807. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2808. except Exception as e:
  2809. # works for ComboBoxes
  2810. try:
  2811. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2812. except Exception as e2:
  2813. # works for Entry
  2814. try:
  2815. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2816. except Exception as e3:
  2817. pass
  2818. for row in range(self.ui.geo_tools_table.rowCount()):
  2819. for col in [2, 3, 4]:
  2820. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2821. self.on_tooltable_cellwidget_change)
  2822. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2823. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2824. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2825. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2826. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2827. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2828. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2829. for row in range(self.ui.geo_tools_table.rowCount()):
  2830. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2831. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2832. def ui_disconnect(self):
  2833. try:
  2834. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2835. # changes in geometry UI
  2836. for i in range(self.ui.grid3.count()):
  2837. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2838. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2839. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2840. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2841. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2842. isinstance(self.ui.grid3.itemAt(i).widget(), IntEntry) or \
  2843. isinstance(self.ui.grid3.itemAt(i).widget(), FCEntry):
  2844. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2845. except Exception as e:
  2846. pass
  2847. try:
  2848. for row in range(self.ui.geo_tools_table.rowCount()):
  2849. for col in [2, 3, 4]:
  2850. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2851. except Exception as e:
  2852. pass
  2853. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2854. try:
  2855. self.ui.addtool_btn.clicked.disconnect()
  2856. except Exception as e:
  2857. pass
  2858. try:
  2859. self.ui.copytool_btn.clicked.disconnect()
  2860. except Exception as e:
  2861. pass
  2862. try:
  2863. self.ui.deltool_btn.clicked.disconnect()
  2864. except Exception as e:
  2865. pass
  2866. try:
  2867. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2868. except Exception as e:
  2869. pass
  2870. try:
  2871. self.ui.geo_tools_table.itemChanged.disconnect()
  2872. except Exception as e:
  2873. pass
  2874. try:
  2875. self.ui.tool_offset_entry.editingFinished.disconnect()
  2876. except Exception as e:
  2877. pass
  2878. for row in range(self.ui.geo_tools_table.rowCount()):
  2879. try:
  2880. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2881. except Exception as e:
  2882. pass
  2883. try:
  2884. self.ui.plot_cb.stateChanged.disconnect()
  2885. except Exception as e:
  2886. pass
  2887. def on_tool_add(self, dia=None):
  2888. self.ui_disconnect()
  2889. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2890. # because the Default value for Tool is used.
  2891. change_message = False
  2892. if dia is not None:
  2893. tooldia = dia
  2894. else:
  2895. try:
  2896. tooldia = float(self.ui.addtool_entry.get_value())
  2897. except ValueError:
  2898. # try to convert comma to decimal point. if it's still not working error message and return
  2899. try:
  2900. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2901. except ValueError:
  2902. change_message = True
  2903. tooldia = self.options["cnctooldia"][0]
  2904. if tooldia is None:
  2905. self.build_ui()
  2906. self.app.inform.emit(_(
  2907. "[ERROR_NOTCL] Please enter the desired tool diameter in Float format."
  2908. ))
  2909. return
  2910. # construct a list of all 'tooluid' in the self.tools
  2911. tool_uid_list = []
  2912. for tooluid_key in self.tools:
  2913. tool_uid_item = int(tooluid_key)
  2914. tool_uid_list.append(tool_uid_item)
  2915. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2916. if not tool_uid_list:
  2917. max_uid = 0
  2918. else:
  2919. max_uid = max(tool_uid_list)
  2920. self.tooluid = max_uid + 1
  2921. if self.units == 'IN':
  2922. tooldia = float('%.4f' % tooldia)
  2923. else:
  2924. tooldia = float('%.2f' % tooldia)
  2925. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2926. # otherwise we add a tool with data copied from last tool
  2927. if not self.tools:
  2928. self.tools.update({
  2929. self.tooluid: {
  2930. 'tooldia': tooldia,
  2931. 'offset': 'Path',
  2932. 'offset_value': 0.0,
  2933. 'type': _('Rough'),
  2934. 'tool_type': 'C1',
  2935. 'data': deepcopy(self.default_data),
  2936. 'solid_geometry': self.solid_geometry
  2937. }
  2938. })
  2939. else:
  2940. last_data = self.tools[max_uid]['data']
  2941. last_offset = self.tools[max_uid]['offset']
  2942. last_offset_value = self.tools[max_uid]['offset_value']
  2943. last_type = self.tools[max_uid]['type']
  2944. last_tool_type = self.tools[max_uid]['tool_type']
  2945. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2946. # if previous geometry was empty (it may happen for the first tool added)
  2947. # then copy the object.solid_geometry
  2948. if not last_solid_geometry:
  2949. last_solid_geometry = self.solid_geometry
  2950. self.tools.update({
  2951. self.tooluid: {
  2952. 'tooldia': tooldia,
  2953. 'offset': last_offset,
  2954. 'offset_value': last_offset_value,
  2955. 'type': last_type,
  2956. 'tool_type': last_tool_type,
  2957. 'data': deepcopy(last_data),
  2958. 'solid_geometry': deepcopy(last_solid_geometry)
  2959. }
  2960. })
  2961. self.tools[self.tooluid]['data']['name'] = self.options['name']
  2962. self.ui.tool_offset_entry.hide()
  2963. self.ui.tool_offset_lbl.hide()
  2964. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2965. try:
  2966. self.ser_attrs.remove('tools')
  2967. except:
  2968. pass
  2969. self.ser_attrs.append('tools')
  2970. if change_message is False:
  2971. self.app.inform.emit(_(
  2972. "[success] Tool added in Tool Table."
  2973. ))
  2974. else:
  2975. change_message = False
  2976. self.app.inform.emit(_(
  2977. "[ERROR_NOTCL] Default Tool added. Wrong value format entered."
  2978. ))
  2979. self.build_ui()
  2980. def on_tool_copy(self, all=None):
  2981. self.ui_disconnect()
  2982. # find the tool_uid maximum value in the self.tools
  2983. uid_list = []
  2984. for key in self.tools:
  2985. uid_list.append(int(key))
  2986. try:
  2987. max_uid = max(uid_list, key=int)
  2988. except ValueError:
  2989. max_uid = 0
  2990. if all is None:
  2991. if self.ui.geo_tools_table.selectedItems():
  2992. for current_row in self.ui.geo_tools_table.selectedItems():
  2993. # sometime the header get selected and it has row number -1
  2994. # we don't want to do anything with the header :)
  2995. if current_row.row() < 0:
  2996. continue
  2997. try:
  2998. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2999. self.set_tool_offset_visibility(current_row.row())
  3000. max_uid += 1
  3001. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3002. except AttributeError:
  3003. self.app.inform.emit(_(
  3004. "[WARNING_NOTCL] Failed. Select a tool to copy."
  3005. ))
  3006. self.build_ui()
  3007. return
  3008. except Exception as e:
  3009. log.debug("on_tool_copy() --> " + str(e))
  3010. # deselect the table
  3011. # self.ui.geo_tools_table.clearSelection()
  3012. else:
  3013. self.app.inform.emit(_(
  3014. "[WARNING_NOTCL] Failed. Select a tool to copy."
  3015. ))
  3016. self.build_ui()
  3017. return
  3018. else:
  3019. # we copy all tools in geo_tools_table
  3020. try:
  3021. temp_tools = deepcopy(self.tools)
  3022. max_uid += 1
  3023. for tooluid in temp_tools:
  3024. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3025. temp_tools.clear()
  3026. except Exception as e:
  3027. log.debug("on_tool_copy() --> " + str(e))
  3028. # if there are no more tools in geo tools table then hide the tool offset
  3029. if not self.tools:
  3030. self.ui.tool_offset_entry.hide()
  3031. self.ui.tool_offset_lbl.hide()
  3032. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3033. try:
  3034. self.ser_attrs.remove('tools')
  3035. except:
  3036. pass
  3037. self.ser_attrs.append('tools')
  3038. self.build_ui()
  3039. self.app.inform.emit(_(
  3040. "[success] Tool was copied in Tool Table."
  3041. ))
  3042. def on_tool_edit(self, current_item):
  3043. self.ui_disconnect()
  3044. current_row = current_item.row()
  3045. try:
  3046. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3047. except ValueError:
  3048. # try to convert comma to decimal point. if it's still not working error message and return
  3049. try:
  3050. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3051. except ValueError:
  3052. self.app.inform.emit(_(
  3053. "[ERROR_NOTCL] Wrong value format entered, "
  3054. "use a number."
  3055. ))
  3056. return
  3057. tool_dia = float('%.4f' % d)
  3058. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3059. self.tools[tooluid]['tooldia'] = tool_dia
  3060. try:
  3061. self.ser_attrs.remove('tools')
  3062. self.ser_attrs.append('tools')
  3063. except:
  3064. pass
  3065. self.app.inform.emit(_(
  3066. "[success] Tool was edited in Tool Table."
  3067. ))
  3068. self.build_ui()
  3069. def on_tool_delete(self, all=None):
  3070. self.ui_disconnect()
  3071. if all is None:
  3072. if self.ui.geo_tools_table.selectedItems():
  3073. for current_row in self.ui.geo_tools_table.selectedItems():
  3074. # sometime the header get selected and it has row number -1
  3075. # we don't want to do anything with the header :)
  3076. if current_row.row() < 0:
  3077. continue
  3078. try:
  3079. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3080. self.set_tool_offset_visibility(current_row.row())
  3081. temp_tools = deepcopy(self.tools)
  3082. for tooluid_key in self.tools:
  3083. if int(tooluid_key) == tooluid_del:
  3084. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3085. # as a property of the object otherwise there will be nothing to hold it
  3086. if len(self.tools) == 1:
  3087. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3088. temp_tools.pop(tooluid_del, None)
  3089. self.tools = deepcopy(temp_tools)
  3090. temp_tools.clear()
  3091. except AttributeError:
  3092. self.app.inform.emit(_(
  3093. "[WARNING_NOTCL] Failed. Select a tool to delete."
  3094. ))
  3095. self.build_ui()
  3096. return
  3097. except Exception as e:
  3098. log.debug("on_tool_delete() --> " + str(e))
  3099. # deselect the table
  3100. # self.ui.geo_tools_table.clearSelection()
  3101. else:
  3102. self.app.inform.emit(_(
  3103. "[WARNING_NOTCL] Failed. Select a tool to delete."
  3104. ))
  3105. self.build_ui()
  3106. return
  3107. else:
  3108. # we delete all tools in geo_tools_table
  3109. self.tools.clear()
  3110. self.app.plot_all()
  3111. # if there are no more tools in geo tools table then hide the tool offset
  3112. if not self.tools:
  3113. self.ui.tool_offset_entry.hide()
  3114. self.ui.tool_offset_lbl.hide()
  3115. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3116. try:
  3117. self.ser_attrs.remove('tools')
  3118. except:
  3119. pass
  3120. self.ser_attrs.append('tools')
  3121. self.build_ui()
  3122. self.app.inform.emit(_(
  3123. "[success] Tool was deleted in Tool Table."
  3124. ))
  3125. obj_active = self.app.collection.get_active()
  3126. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  3127. # we make it back SingleGeo
  3128. if self.ui.geo_tools_table.rowCount() <= 0:
  3129. obj_active.multigeo = False
  3130. obj_active.options['xmin'] = 0
  3131. obj_active.options['ymin'] = 0
  3132. obj_active.options['xmax'] = 0
  3133. obj_active.options['ymax'] = 0
  3134. if obj_active.multigeo is True:
  3135. try:
  3136. xmin, ymin, xmax, ymax = obj_active.bounds()
  3137. obj_active.options['xmin'] = xmin
  3138. obj_active.options['ymin'] = ymin
  3139. obj_active.options['xmax'] = xmax
  3140. obj_active.options['ymax'] = ymax
  3141. except:
  3142. obj_active.options['xmin'] = 0
  3143. obj_active.options['ymin'] = 0
  3144. obj_active.options['xmax'] = 0
  3145. obj_active.options['ymax'] = 0
  3146. def on_row_selection_change(self):
  3147. self.update_ui()
  3148. def update_ui(self, row=None):
  3149. self.ui_disconnect()
  3150. if row is None:
  3151. try:
  3152. current_row = self.ui.geo_tools_table.currentRow()
  3153. except:
  3154. current_row = 0
  3155. else:
  3156. current_row = row
  3157. if current_row < 0:
  3158. current_row = 0
  3159. self.set_tool_offset_visibility(current_row)
  3160. # populate the form with the data from the tool associated with the row parameter
  3161. try:
  3162. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3163. except Exception as e:
  3164. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3165. return
  3166. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3167. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3168. try:
  3169. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  3170. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3171. except Exception as e:
  3172. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3173. return
  3174. try:
  3175. # set the form with data from the newly selected tool
  3176. for tooluid_key, tooluid_value in self.tools.items():
  3177. if int(tooluid_key) == tooluid:
  3178. for key, value in tooluid_value.items():
  3179. if key == 'data':
  3180. form_value_storage = tooluid_value[key]
  3181. self.update_form(form_value_storage)
  3182. if key == 'offset_value':
  3183. # update the offset value in the entry even if the entry is hidden
  3184. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  3185. if key == 'tool_type' and value == 'V':
  3186. self.update_cutz()
  3187. except Exception as e:
  3188. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  3189. self.ui_connect()
  3190. def ui_update_v_shape(self, tool_type_txt):
  3191. if tool_type_txt == 'V':
  3192. self.ui.tipdialabel.show()
  3193. self.ui.tipdia_entry.show()
  3194. self.ui.tipanglelabel.show()
  3195. self.ui.tipangle_entry.show()
  3196. self.ui.cutz_entry.setDisabled(True)
  3197. self.update_cutz()
  3198. else:
  3199. self.ui.tipdialabel.hide()
  3200. self.ui.tipdia_entry.hide()
  3201. self.ui.tipanglelabel.hide()
  3202. self.ui.tipangle_entry.hide()
  3203. self.ui.cutz_entry.setDisabled(False)
  3204. def update_cutz(self):
  3205. try:
  3206. vdia = float(self.ui.tipdia_entry.get_value())
  3207. except ValueError:
  3208. # try to convert comma to decimal point. if it's still not working error message and return
  3209. try:
  3210. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  3211. except ValueError:
  3212. self.app.inform.emit(_(
  3213. "[ERROR_NOTCL] Wrong value format entered, "
  3214. "use a number."
  3215. ))
  3216. return
  3217. try:
  3218. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  3219. except ValueError:
  3220. # try to convert comma to decimal point. if it's still not working error message and return
  3221. try:
  3222. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  3223. except ValueError:
  3224. self.app.inform.emit(_(
  3225. "[ERROR_NOTCL] Wrong value format entered, "
  3226. "use a number."
  3227. ))
  3228. return
  3229. row = self.ui.geo_tools_table.currentRow()
  3230. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  3231. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  3232. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3233. new_cutz = float('%.4f' % -new_cutz)
  3234. self.ui.cutz_entry.set_value(new_cutz)
  3235. # store the new CutZ value into storage (self.tools)
  3236. for tooluid_key, tooluid_value in self.tools.items():
  3237. if int(tooluid_key) == tool_uid:
  3238. tooluid_value['data']['cutz'] = new_cutz
  3239. def on_tooltable_cellwidget_change(self):
  3240. cw = self.sender()
  3241. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3242. cw_row = cw_index.row()
  3243. cw_col = cw_index.column()
  3244. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3245. # store the text of the cellWidget that changed it's index in the self.tools
  3246. for tooluid_key, tooluid_value in self.tools.items():
  3247. if int(tooluid_key) == current_uid:
  3248. cb_txt = cw.currentText()
  3249. if cw_col == 2:
  3250. tooluid_value['offset'] = cb_txt
  3251. if cb_txt == ('Custom'):
  3252. self.ui.tool_offset_entry.show()
  3253. self.ui.tool_offset_lbl.show()
  3254. else:
  3255. self.ui.tool_offset_entry.hide()
  3256. self.ui.tool_offset_lbl.hide()
  3257. # reset the offset_value in storage self.tools
  3258. tooluid_value['offset_value'] = 0.0
  3259. elif cw_col == 3:
  3260. # force toolpath type as 'Iso' if the tool type is V-Shape
  3261. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3262. tooluid_value['type'] = _('Iso')
  3263. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3264. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3265. else:
  3266. tooluid_value['type'] = cb_txt
  3267. elif cw_col == 4:
  3268. tooluid_value['tool_type'] = cb_txt
  3269. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3270. if cb_txt == 'V':
  3271. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3272. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3273. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3274. def update_form(self, dict_storage):
  3275. for form_key in self.form_fields:
  3276. for storage_key in dict_storage:
  3277. if form_key == storage_key:
  3278. try:
  3279. self.form_fields[form_key].set_value(dict_storage[form_key])
  3280. except Exception as e:
  3281. log.debug(str(e))
  3282. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3283. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3284. self.ui.ois_dwell_geo.on_cb_change()
  3285. self.ui.ois_mpass_geo.on_cb_change()
  3286. self.ui.ois_tcz_geo.on_cb_change()
  3287. def gui_form_to_storage(self):
  3288. self.ui_disconnect()
  3289. widget_changed = self.sender()
  3290. try:
  3291. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3292. except:
  3293. return
  3294. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3295. if widget_idx == 1 or widget_idx == 3:
  3296. self.update_cutz()
  3297. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  3298. # ui_diconnect() so I use this 'hack'
  3299. if isinstance(widget_changed, FCCheckBox):
  3300. if widget_changed.text() == 'Multi-Depth:':
  3301. self.ui.ois_mpass_geo.on_cb_change()
  3302. if widget_changed.text() == 'Tool change':
  3303. self.ui.ois_tcz_geo.on_cb_change()
  3304. if widget_changed.text() == 'Dwell:':
  3305. self.ui.ois_dwell_geo.on_cb_change()
  3306. row = self.ui.geo_tools_table.currentRow()
  3307. if row < 0:
  3308. row = 0
  3309. # store all the data associated with the row parameter to the self.tools storage
  3310. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3311. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3312. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3313. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3314. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3315. try:
  3316. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3317. except ValueError:
  3318. # try to convert comma to decimal point. if it's still not working error message and return
  3319. try:
  3320. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3321. )
  3322. except ValueError:
  3323. self.app.inform.emit(_(
  3324. "[ERROR_NOTCL] Wrong value format entered, "
  3325. "use a number."
  3326. ))
  3327. return
  3328. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3329. temp_tools = {}
  3330. temp_dia = {}
  3331. temp_data = {}
  3332. for tooluid_key, tooluid_value in self.tools.items():
  3333. if int(tooluid_key) == tooluid_item:
  3334. for key, value in tooluid_value.items():
  3335. if key == 'tooldia':
  3336. temp_dia[key] = tooldia_item
  3337. # update the 'offset', 'type' and 'tool_type' sections
  3338. if key == 'offset':
  3339. temp_dia[key] = offset_item
  3340. if key == 'type':
  3341. temp_dia[key] = type_item
  3342. if key == 'tool_type':
  3343. temp_dia[key] = tool_type_item
  3344. if key == 'offset_value':
  3345. temp_dia[key] = offset_value_item
  3346. if key == 'data':
  3347. # update the 'data' section
  3348. for data_key in tooluid_value[key].keys():
  3349. for form_key, form_value in self.form_fields.items():
  3350. if form_key == data_key:
  3351. temp_data[data_key] = form_value.get_value()
  3352. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3353. # updated from self.app.defaults
  3354. if data_key not in self.form_fields:
  3355. temp_data[data_key] = value[data_key]
  3356. temp_dia[key] = deepcopy(temp_data)
  3357. temp_data.clear()
  3358. if key == 'solid_geometry':
  3359. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3360. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3361. else:
  3362. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3363. self.tools.clear()
  3364. self.tools = deepcopy(temp_tools)
  3365. temp_tools.clear()
  3366. self.ui_connect()
  3367. def select_tools_table_row(self, row, clearsel=None):
  3368. if clearsel:
  3369. self.ui.geo_tools_table.clearSelection()
  3370. if self.ui.geo_tools_table.rowCount() > 0:
  3371. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3372. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3373. def export_dxf(self):
  3374. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3375. dwg = None
  3376. try:
  3377. dwg = ezdxf.new('R2010')
  3378. msp = dwg.modelspace()
  3379. def g2dxf(dxf_space, geo):
  3380. if isinstance(geo, MultiPolygon):
  3381. for poly in geo:
  3382. ext_points = list(poly.exterior.coords)
  3383. dxf_space.add_lwpolyline(ext_points)
  3384. for interior in poly.interiors:
  3385. dxf_space.add_lwpolyline(list(interior.coords))
  3386. if isinstance(geo, Polygon):
  3387. ext_points = list(geo.exterior.coords)
  3388. dxf_space.add_lwpolyline(ext_points)
  3389. for interior in geo.interiors:
  3390. dxf_space.add_lwpolyline(list(interior.coords))
  3391. if isinstance(geo, MultiLineString):
  3392. for line in geo:
  3393. dxf_space.add_lwpolyline(list(line.coords))
  3394. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  3395. dxf_space.add_lwpolyline(list(geo.coords))
  3396. multigeo_solid_geometry = []
  3397. if self.multigeo:
  3398. for tool in self.tools:
  3399. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  3400. else:
  3401. multigeo_solid_geometry = self.solid_geometry
  3402. for geo in multigeo_solid_geometry:
  3403. if type(geo) == list:
  3404. for g in geo:
  3405. g2dxf(msp, g)
  3406. else:
  3407. g2dxf(msp, geo)
  3408. # points = FlatCAMGeometry.get_pts(geo)
  3409. # msp.add_lwpolyline(points)
  3410. except Exception as e:
  3411. log.debug(str(e))
  3412. return dwg
  3413. def get_selected_tools_table_items(self):
  3414. """
  3415. Returns a list of lists, each list in the list is made out of row elements
  3416. :return: List of table_tools items.
  3417. :rtype: list
  3418. """
  3419. table_tools_items = []
  3420. if self.multigeo:
  3421. for x in self.ui.geo_tools_table.selectedItems():
  3422. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  3423. for column in range(0, self.ui.geo_tools_table.columnCount())])
  3424. else:
  3425. for x in self.ui.geo_tools_table.selectedItems():
  3426. r = []
  3427. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  3428. # so we don't read them
  3429. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  3430. # the columns have items that have text but also have items that are widgets
  3431. # for which the text they hold has to be read differently
  3432. try:
  3433. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  3434. except AttributeError:
  3435. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  3436. except:
  3437. pass
  3438. r.append(txt)
  3439. table_tools_items.append(r)
  3440. for item in table_tools_items:
  3441. item[0] = str(item[0])
  3442. return table_tools_items
  3443. def on_pp_changed(self):
  3444. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3445. if current_pp == 'hpgl':
  3446. self.old_pp_state = self.ui.mpass_cb.get_value()
  3447. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3448. self.ui.mpass_cb.set_value(False)
  3449. self.ui.mpass_cb.setDisabled(True)
  3450. self.ui.toolchangeg_cb.set_value(True)
  3451. self.ui.toolchangeg_cb.setDisabled(True)
  3452. else:
  3453. self.ui.mpass_cb.set_value(self.old_pp_state)
  3454. self.ui.mpass_cb.setDisabled(False)
  3455. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3456. self.ui.toolchangeg_cb.setDisabled(False)
  3457. if "toolchange_probe" in current_pp.lower():
  3458. self.ui.pdepth_entry.setVisible(True)
  3459. self.ui.pdepth_label.show()
  3460. self.ui.feedrate_probe_entry.setVisible(True)
  3461. self.ui.feedrate_probe_label.show()
  3462. else:
  3463. self.ui.pdepth_entry.setVisible(False)
  3464. self.ui.pdepth_label.hide()
  3465. self.ui.feedrate_probe_entry.setVisible(False)
  3466. self.ui.feedrate_probe_label.hide()
  3467. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  3468. self.ui.fr_rapidlabel.show()
  3469. self.ui.cncfeedrate_rapid_entry.show()
  3470. else:
  3471. self.ui.fr_rapidlabel.hide()
  3472. self.ui.cncfeedrate_rapid_entry.hide()
  3473. def on_generatecnc_button_click(self, *args):
  3474. self.app.report_usage("geometry_on_generatecnc_button")
  3475. self.read_form()
  3476. self.sel_tools = {}
  3477. try:
  3478. if self.special_group:
  3479. self.app.inform.emit(_(
  3480. "[WARNING_NOTCL] This Geometry can't be processed because it is %s geometry."
  3481. ) % str(self.special_group))
  3482. return
  3483. except AttributeError:
  3484. pass
  3485. # test to see if we have tools available in the tool table
  3486. if self.ui.geo_tools_table.selectedItems():
  3487. for x in self.ui.geo_tools_table.selectedItems():
  3488. try:
  3489. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3490. except ValueError:
  3491. # try to convert comma to decimal point. if it's still not working error message and return
  3492. try:
  3493. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3494. except ValueError:
  3495. self.app.inform.emit(_(
  3496. "[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  3497. "use a number."
  3498. ))
  3499. return
  3500. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3501. for tooluid_key, tooluid_value in self.tools.items():
  3502. if int(tooluid_key) == tooluid:
  3503. self.sel_tools.update({
  3504. tooluid: deepcopy(tooluid_value)
  3505. })
  3506. self.mtool_gen_cncjob()
  3507. self.ui.geo_tools_table.clearSelection()
  3508. elif self.ui.geo_tools_table.rowCount() == 1:
  3509. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3510. for tooluid_key, tooluid_value in self.tools.items():
  3511. if int(tooluid_key) == tooluid:
  3512. self.sel_tools.update({
  3513. tooluid: deepcopy(tooluid_value)
  3514. })
  3515. self.mtool_gen_cncjob()
  3516. self.ui.geo_tools_table.clearSelection()
  3517. else:
  3518. self.app.inform.emit(_(
  3519. "[ERROR_NOTCL] Failed. No tool selected in the tool table ..."
  3520. ))
  3521. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3522. """
  3523. Creates a multi-tool CNCJob out of this Geometry object.
  3524. The actual work is done by the target FlatCAMCNCjob object's
  3525. `generate_from_geometry_2()` method.
  3526. :param z_cut: Cut depth (negative)
  3527. :param z_move: Hight of the tool when travelling (not cutting)
  3528. :param feedrate: Feed rate while cutting on X - Y plane
  3529. :param feedrate_z: Feed rate while cutting on Z plane
  3530. :param feedrate_rapid: Feed rate while moving with rapids
  3531. :param tooldia: Tool diameter
  3532. :param outname: Name of the new object
  3533. :param spindlespeed: Spindle speed (RPM)
  3534. :param ppname_g Name of the postprocessor
  3535. :return: None
  3536. """
  3537. offset_str = ''
  3538. multitool_gcode = ''
  3539. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3540. outname = "%s_%s" % (self.options["name"], 'cnc')
  3541. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3542. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3543. try:
  3544. xmin = self.options['xmin']
  3545. ymin = self.options['ymin']
  3546. xmax = self.options['xmax']
  3547. ymax = self.options['ymax']
  3548. except Exception as e:
  3549. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3550. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  3551. msg += _('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s') % str(e)
  3552. msg += traceback.format_exc()
  3553. self.app.inform.emit(msg)
  3554. return
  3555. # Object initialization function for app.new_object()
  3556. # RUNNING ON SEPARATE THREAD!
  3557. def job_init_single_geometry(job_obj, app_obj):
  3558. log.debug("Creating a CNCJob out of a single-geometry")
  3559. assert isinstance(job_obj, FlatCAMCNCjob), \
  3560. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3561. # count the tools
  3562. tool_cnt = 0
  3563. dia_cnc_dict = {}
  3564. # this turn on the FlatCAMCNCJob plot for multiple tools
  3565. job_obj.multitool = True
  3566. job_obj.multigeo = False
  3567. job_obj.cnc_tools.clear()
  3568. # job_obj.create_geometry()
  3569. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3570. job_obj.segx = segx
  3571. job_obj.segy = segy
  3572. try:
  3573. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3574. except ValueError:
  3575. # try to convert comma to decimal point. if it's still not working error message and return
  3576. try:
  3577. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3578. except ValueError:
  3579. self.app.inform.emit(
  3580. _(
  3581. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3582. ))
  3583. try:
  3584. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3585. except ValueError:
  3586. # try to convert comma to decimal point. if it's still not working error message and return
  3587. try:
  3588. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3589. except ValueError:
  3590. self.app.inform.emit(
  3591. _(
  3592. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3593. 'or self.options["feedrate_probe"]'
  3594. ))
  3595. for tooluid_key in self.sel_tools:
  3596. tool_cnt += 1
  3597. app_obj.progress.emit(20)
  3598. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3599. if diadict_key == 'tooldia':
  3600. tooldia_val = float('%.4f' % float(diadict_value))
  3601. dia_cnc_dict.update({
  3602. diadict_key: tooldia_val
  3603. })
  3604. if diadict_key == 'offset':
  3605. o_val = diadict_value.lower()
  3606. dia_cnc_dict.update({
  3607. diadict_key: o_val
  3608. })
  3609. if diadict_key == 'type':
  3610. t_val = diadict_value
  3611. dia_cnc_dict.update({
  3612. diadict_key: t_val
  3613. })
  3614. if diadict_key == 'tool_type':
  3615. tt_val = diadict_value
  3616. dia_cnc_dict.update({
  3617. diadict_key: tt_val
  3618. })
  3619. if diadict_key == 'data':
  3620. for data_key, data_value in diadict_value.items():
  3621. if data_key == "multidepth":
  3622. multidepth = data_value
  3623. if data_key == "depthperpass":
  3624. depthpercut = data_value
  3625. if data_key == "extracut":
  3626. extracut = data_value
  3627. if data_key == "startz":
  3628. startz = data_value
  3629. if data_key == "endz":
  3630. endz = data_value
  3631. if data_key == "toolchangez":
  3632. toolchangez =data_value
  3633. if data_key == "toolchangexy":
  3634. toolchangexy = data_value
  3635. if data_key == "toolchange":
  3636. toolchange = data_value
  3637. if data_key == "cutz":
  3638. z_cut = data_value
  3639. if data_key == "travelz":
  3640. z_move = data_value
  3641. if data_key == "feedrate":
  3642. feedrate = data_value
  3643. if data_key == "feedrate_z":
  3644. feedrate_z = data_value
  3645. if data_key == "feedrate_rapid":
  3646. feedrate_rapid = data_value
  3647. if data_key == "ppname_g":
  3648. pp_geometry_name = data_value
  3649. if data_key == "spindlespeed":
  3650. spindlespeed = data_value
  3651. if data_key == "dwell":
  3652. dwell = data_value
  3653. if data_key == "dwelltime":
  3654. dwelltime = data_value
  3655. datadict = deepcopy(diadict_value)
  3656. dia_cnc_dict.update({
  3657. diadict_key: datadict
  3658. })
  3659. if dia_cnc_dict['offset'] == ('in'):
  3660. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3661. offset_str = 'inside'
  3662. elif dia_cnc_dict['offset'].lower() == ('out'):
  3663. tool_offset = dia_cnc_dict['tooldia'] / 2
  3664. offset_str = 'outside'
  3665. elif dia_cnc_dict['offset'].lower() == ('path'):
  3666. offset_str = 'onpath'
  3667. tool_offset = 0.0
  3668. else:
  3669. offset_str = 'custom'
  3670. try:
  3671. offset_value = float(self.ui.tool_offset_entry.get_value())
  3672. except ValueError:
  3673. # try to convert comma to decimal point. if it's still not working error message and return
  3674. try:
  3675. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3676. )
  3677. except ValueError:
  3678. self.app.inform.emit(_(
  3679. "[ERROR_NOTCL] Wrong value format entered, "
  3680. "use a number."
  3681. ))
  3682. return
  3683. if offset_value:
  3684. tool_offset = float(offset_value)
  3685. else:
  3686. self.app.inform.emit(
  3687. _(
  3688. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3689. "Add a Tool Offset or change the Offset Type."
  3690. )
  3691. )
  3692. return
  3693. dia_cnc_dict.update({
  3694. 'offset_value': tool_offset
  3695. })
  3696. spindledir = self.app.defaults['geometry_spindledir']
  3697. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3698. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3699. # Propagate options
  3700. job_obj.options["tooldia"] = tooldia_val
  3701. job_obj.options['type'] = 'Geometry'
  3702. job_obj.options['tool_dia'] = tooldia_val
  3703. job_obj.options['xmin'] = xmin
  3704. job_obj.options['ymin'] = ymin
  3705. job_obj.options['xmax'] = xmax
  3706. job_obj.options['ymax'] = ymax
  3707. app_obj.progress.emit(40)
  3708. tol = float(self.app.defaults['global_tolerance'])
  3709. res = job_obj.generate_from_geometry_2(
  3710. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  3711. z_cut=z_cut, z_move=z_move,
  3712. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3713. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3714. multidepth=multidepth, depthpercut=depthpercut,
  3715. extracut=extracut, startz=startz, endz=endz,
  3716. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3717. pp_geometry_name=pp_geometry_name,
  3718. tool_no=tool_cnt)
  3719. if res == 'fail':
  3720. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3721. return 'fail'
  3722. else:
  3723. dia_cnc_dict['gcode'] = res
  3724. app_obj.progress.emit(50)
  3725. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3726. # object is the source of gcode
  3727. job_obj.toolchange_xy_type = "geometry"
  3728. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3729. # TODO this serve for bounding box creation only; should be optimized
  3730. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3731. app_obj.progress.emit(80)
  3732. job_obj.cnc_tools.update({
  3733. tooluid_key: deepcopy(dia_cnc_dict)
  3734. })
  3735. dia_cnc_dict.clear()
  3736. # Object initialization function for app.new_object()
  3737. # RUNNING ON SEPARATE THREAD!
  3738. def job_init_multi_geometry(job_obj, app_obj):
  3739. log.debug("Creating a CNCJob out of a multi-geometry")
  3740. assert isinstance(job_obj, FlatCAMCNCjob), \
  3741. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3742. # count the tools
  3743. tool_cnt = 0
  3744. dia_cnc_dict = {}
  3745. current_uid = int(1)
  3746. # this turn on the FlatCAMCNCJob plot for multiple tools
  3747. job_obj.multitool = True
  3748. job_obj.multigeo = True
  3749. job_obj.cnc_tools.clear()
  3750. job_obj.options['xmin'] = xmin
  3751. job_obj.options['ymin'] = ymin
  3752. job_obj.options['xmax'] = xmax
  3753. job_obj.options['ymax'] = ymax
  3754. try:
  3755. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3756. except ValueError:
  3757. # try to convert comma to decimal point. if it's still not working error message and return
  3758. try:
  3759. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3760. except ValueError:
  3761. self.app.inform.emit(
  3762. _(
  3763. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3764. ))
  3765. try:
  3766. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3767. except ValueError:
  3768. # try to convert comma to decimal point. if it's still not working error message and return
  3769. try:
  3770. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3771. except ValueError:
  3772. self.app.inform.emit(
  3773. _(
  3774. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3775. 'or self.options["feedrate_probe"]'
  3776. ))
  3777. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3778. if not self.solid_geometry:
  3779. a = 0
  3780. for tooluid_key in self.tools:
  3781. if self.tools[tooluid_key]['solid_geometry'] is None:
  3782. a += 1
  3783. if a == len(self.tools):
  3784. self.app.inform.emit(_(
  3785. '[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'
  3786. ))
  3787. return 'fail'
  3788. for tooluid_key in self.sel_tools:
  3789. tool_cnt += 1
  3790. app_obj.progress.emit(20)
  3791. # find the tool_dia associated with the tooluid_key
  3792. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3793. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3794. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3795. for k, v in self.tools.items():
  3796. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3797. current_uid = int(k)
  3798. break
  3799. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3800. if diadict_key == 'tooldia':
  3801. tooldia_val = float('%.4f' % float(diadict_value))
  3802. dia_cnc_dict.update({
  3803. diadict_key: tooldia_val
  3804. })
  3805. if diadict_key == 'offset':
  3806. o_val = diadict_value.lower()
  3807. dia_cnc_dict.update({
  3808. diadict_key: o_val
  3809. })
  3810. if diadict_key == 'type':
  3811. t_val = diadict_value
  3812. dia_cnc_dict.update({
  3813. diadict_key: t_val
  3814. })
  3815. if diadict_key == 'tool_type':
  3816. tt_val = diadict_value
  3817. dia_cnc_dict.update({
  3818. diadict_key: tt_val
  3819. })
  3820. if diadict_key == 'data':
  3821. for data_key, data_value in diadict_value.items():
  3822. if data_key == "multidepth":
  3823. multidepth = data_value
  3824. if data_key == "depthperpass":
  3825. depthpercut = data_value
  3826. if data_key == "extracut":
  3827. extracut = data_value
  3828. if data_key == "startz":
  3829. startz = data_value
  3830. if data_key == "endz":
  3831. endz = data_value
  3832. if data_key == "toolchangez":
  3833. toolchangez =data_value
  3834. if data_key == "toolchangexy":
  3835. toolchangexy = data_value
  3836. if data_key == "toolchange":
  3837. toolchange = data_value
  3838. if data_key == "cutz":
  3839. z_cut = data_value
  3840. if data_key == "travelz":
  3841. z_move = data_value
  3842. if data_key == "feedrate":
  3843. feedrate = data_value
  3844. if data_key == "feedrate_z":
  3845. feedrate_z = data_value
  3846. if data_key == "feedrate_rapid":
  3847. feedrate_rapid = data_value
  3848. if data_key == "ppname_g":
  3849. pp_geometry_name = data_value
  3850. if data_key == "spindlespeed":
  3851. spindlespeed = data_value
  3852. if data_key == "dwell":
  3853. dwell = data_value
  3854. if data_key == "dwelltime":
  3855. dwelltime = data_value
  3856. datadict = deepcopy(diadict_value)
  3857. dia_cnc_dict.update({
  3858. diadict_key: datadict
  3859. })
  3860. if dia_cnc_dict['offset'] == ('in'):
  3861. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3862. offset_str = 'inside'
  3863. elif dia_cnc_dict['offset'].lower() == ('out'):
  3864. tool_offset = dia_cnc_dict['tooldia'] / 2
  3865. offset_str = 'outside'
  3866. elif dia_cnc_dict['offset'].lower() == ('path'):
  3867. offset_str = 'onpath'
  3868. tool_offset = 0.0
  3869. else:
  3870. offset_str = 'custom'
  3871. try:
  3872. offset_value = float(self.ui.tool_offset_entry.get_value())
  3873. except ValueError:
  3874. # try to convert comma to decimal point. if it's still not working error message and return
  3875. try:
  3876. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3877. )
  3878. except ValueError:
  3879. self.app.inform.emit(_(
  3880. "[ERROR_NOTCL] Wrong value format entered, "
  3881. "use a number."
  3882. ))
  3883. return
  3884. if offset_value:
  3885. tool_offset = float(offset_value)
  3886. else:
  3887. self.app.inform.emit(
  3888. _(
  3889. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3890. "Add a Tool Offset or change the Offset Type."
  3891. )
  3892. )
  3893. return
  3894. dia_cnc_dict.update({
  3895. 'offset_value': tool_offset
  3896. })
  3897. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3898. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3899. # Propagate options
  3900. job_obj.options["tooldia"] = tooldia_val
  3901. job_obj.options['type'] = 'Geometry'
  3902. job_obj.options['tool_dia'] = tooldia_val
  3903. app_obj.progress.emit(40)
  3904. spindledir = self.app.defaults['geometry_spindledir']
  3905. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3906. tol = float(self.app.defaults['global_tolerance'])
  3907. res = job_obj.generate_from_multitool_geometry(
  3908. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3909. tolerance=tol, z_cut=z_cut, z_move=z_move,
  3910. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3911. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3912. multidepth=multidepth, depthpercut=depthpercut,
  3913. extracut=extracut, startz=startz, endz=endz,
  3914. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3915. pp_geometry_name=pp_geometry_name,
  3916. tool_no=tool_cnt)
  3917. if res == 'fail':
  3918. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3919. return 'fail'
  3920. else:
  3921. dia_cnc_dict['gcode'] = res
  3922. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3923. # TODO this serve for bounding box creation only; should be optimized
  3924. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3925. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3926. # object is the source of gcode
  3927. job_obj.toolchange_xy_type = "geometry"
  3928. app_obj.progress.emit(80)
  3929. job_obj.cnc_tools.update({
  3930. tooluid_key: deepcopy(dia_cnc_dict)
  3931. })
  3932. dia_cnc_dict.clear()
  3933. if use_thread:
  3934. # To be run in separate thread
  3935. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3936. # separate solid_geometry in the self.tools dictionary
  3937. def job_thread(app_obj):
  3938. if self.solid_geometry:
  3939. with self.app.proc_container.new(_("Generating CNC Code")):
  3940. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3941. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3942. app_obj.progress.emit(100)
  3943. else:
  3944. with self.app.proc_container.new(_("Generating CNC Code")):
  3945. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3946. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3947. app_obj.progress.emit(100)
  3948. # Create a promise with the name
  3949. self.app.collection.promise(outname)
  3950. # Send to worker
  3951. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3952. else:
  3953. if self.solid_geometry:
  3954. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3955. else:
  3956. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3957. def generatecncjob(self, outname=None,
  3958. tooldia=None, offset=None,
  3959. z_cut=None, z_move=None,
  3960. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3961. spindlespeed=None, dwell=None, dwelltime=None,
  3962. multidepth=None, depthperpass=None,
  3963. toolchange=None, toolchangez=None, toolchangexy=None,
  3964. extracut=None, startz=None, endz=None,
  3965. ppname_g=None,
  3966. segx=None,
  3967. segy=None,
  3968. use_thread=True):
  3969. """
  3970. Only used for TCL Command.
  3971. Creates a CNCJob out of this Geometry object. The actual
  3972. work is done by the target FlatCAMCNCjob object's
  3973. `generate_from_geometry_2()` method.
  3974. :param z_cut: Cut depth (negative)
  3975. :param z_move: Hight of the tool when travelling (not cutting)
  3976. :param feedrate: Feed rate while cutting on X - Y plane
  3977. :param feedrate_z: Feed rate while cutting on Z plane
  3978. :param feedrate_rapid: Feed rate while moving with rapids
  3979. :param tooldia: Tool diameter
  3980. :param outname: Name of the new object
  3981. :param spindlespeed: Spindle speed (RPM)
  3982. :param ppname_g Name of the postprocessor
  3983. :return: None
  3984. """
  3985. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3986. outname = outname if outname is not None else self.options["name"]
  3987. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3988. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3989. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3990. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3991. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3992. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3993. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3994. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3995. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3996. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3997. startz = startz if startz is not None else self.options["startz"]
  3998. endz = endz if endz is not None else float(self.options["endz"])
  3999. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4000. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4001. toolchange = toolchange if toolchange else self.options["toolchange"]
  4002. offset = offset if offset else 0.0
  4003. # int or None.
  4004. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4005. dwell = dwell if dwell else self.options["dwell"]
  4006. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4007. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  4008. # Object initialization function for app.new_object()
  4009. # RUNNING ON SEPARATE THREAD!
  4010. def job_init(job_obj, app_obj):
  4011. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4012. # Propagate options
  4013. job_obj.options["tooldia"] = tooldia
  4014. app_obj.progress.emit(20)
  4015. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4016. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4017. app_obj.progress.emit(40)
  4018. job_obj.options['type'] = 'Geometry'
  4019. job_obj.options['tool_dia'] = tooldia
  4020. job_obj.segx = segx
  4021. job_obj.segy = segy
  4022. try:
  4023. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4024. except ValueError:
  4025. # try to convert comma to decimal point. if it's still not working error message and return
  4026. try:
  4027. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  4028. except ValueError:
  4029. self.app.inform.emit(
  4030. _(
  4031. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  4032. ))
  4033. try:
  4034. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4035. except ValueError:
  4036. # try to convert comma to decimal point. if it's still not working error message and return
  4037. try:
  4038. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  4039. except ValueError:
  4040. self.app.inform.emit(
  4041. _(
  4042. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  4043. 'or self.options["feedrate_probe"]'
  4044. ))
  4045. job_obj.options['xmin'] = self.options['xmin']
  4046. job_obj.options['ymin'] = self.options['ymin']
  4047. job_obj.options['xmax'] = self.options['xmax']
  4048. job_obj.options['ymax'] = self.options['ymax']
  4049. tol = float(self.app.defaults['global_tolerance'])
  4050. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=tol,
  4051. z_cut=z_cut, z_move=z_move,
  4052. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4053. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4054. multidepth=multidepth, depthpercut=depthperpass,
  4055. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4056. extracut=extracut, startz=startz, endz=endz,
  4057. pp_geometry_name=ppname_g
  4058. )
  4059. app_obj.progress.emit(50)
  4060. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4061. # source of gcode
  4062. job_obj.toolchange_xy_type = "geometry"
  4063. job_obj.gcode_parse()
  4064. app_obj.progress.emit(80)
  4065. if use_thread:
  4066. # To be run in separate thread
  4067. def job_thread(app_obj):
  4068. with self.app.proc_container.new(_("Generating CNC Code")):
  4069. app_obj.new_object("cncjob", outname, job_init)
  4070. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  4071. app_obj.progress.emit(100)
  4072. # Create a promise with the name
  4073. self.app.collection.promise(outname)
  4074. # Send to worker
  4075. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4076. else:
  4077. self.app.new_object("cncjob", outname, job_init)
  4078. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4079. # if self.muted_ui:
  4080. # return
  4081. # self.read_form_item('plot')
  4082. def scale(self, xfactor, yfactor=None, point=None):
  4083. """
  4084. Scales all geometry by a given factor.
  4085. :param xfactor: Factor by which to scale the object's geometry/
  4086. :type xfactor: float
  4087. :param yfactor: Factor by which to scale the object's geometry/
  4088. :type yfactor: float
  4089. :return: None
  4090. :rtype: None
  4091. """
  4092. try:
  4093. xfactor = float(xfactor)
  4094. except:
  4095. self.app.inform.emit(_(
  4096. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  4097. return
  4098. if yfactor is None:
  4099. yfactor = xfactor
  4100. else:
  4101. try:
  4102. yfactor = float(yfactor)
  4103. except:
  4104. self.app.inform.emit(_(
  4105. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."
  4106. ))
  4107. return
  4108. if point is None:
  4109. px = 0
  4110. py = 0
  4111. else:
  4112. px, py = point
  4113. # if type(self.solid_geometry) == list:
  4114. # geo_list = self.flatten(self.solid_geometry)
  4115. # self.solid_geometry = []
  4116. # # for g in geo_list:
  4117. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  4118. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  4119. # for g in geo_list]
  4120. # else:
  4121. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  4122. # origin=(px, py))
  4123. # self.app.inform.emit("[success] Geometry Scale done.")
  4124. def scale_recursion(geom):
  4125. if type(geom) == list:
  4126. geoms=list()
  4127. for local_geom in geom:
  4128. geoms.append(scale_recursion(local_geom))
  4129. return geoms
  4130. else:
  4131. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4132. if self.multigeo is True:
  4133. for tool in self.tools:
  4134. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4135. else:
  4136. self.solid_geometry=scale_recursion(self.solid_geometry)
  4137. self.app.inform.emit(_(
  4138. "[success] Geometry Scale done."
  4139. ))
  4140. def offset(self, vect):
  4141. """
  4142. Offsets all geometry by a given vector/
  4143. :param vect: (x, y) vector by which to offset the object's geometry.
  4144. :type vect: tuple
  4145. :return: None
  4146. :rtype: None
  4147. """
  4148. try:
  4149. dx, dy = vect
  4150. except TypeError:
  4151. self.app.inform.emit(_(
  4152. "[ERROR_NOTCL] An (x,y) pair of values are needed. "
  4153. "Probable you entered only one value in the Offset field."
  4154. ))
  4155. return
  4156. def translate_recursion(geom):
  4157. if type(geom) == list:
  4158. geoms=list()
  4159. for local_geom in geom:
  4160. geoms.append(translate_recursion(local_geom))
  4161. return geoms
  4162. else:
  4163. return affinity.translate(geom, xoff=dx, yoff=dy)
  4164. if self.multigeo is True:
  4165. for tool in self.tools:
  4166. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  4167. else:
  4168. self.solid_geometry=translate_recursion(self.solid_geometry)
  4169. self.app.inform.emit(_(
  4170. "[success] Geometry Offset done."
  4171. ))
  4172. def convert_units(self, units):
  4173. self.ui_disconnect()
  4174. factor = Geometry.convert_units(self, units)
  4175. self.options['cutz'] = float(self.options['cutz']) * factor
  4176. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  4177. self.options['travelz'] = float(self.options['travelz']) * factor
  4178. self.options['feedrate'] = float(self.options['feedrate']) * factor
  4179. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  4180. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  4181. self.options['endz'] = float(self.options['endz']) * factor
  4182. # self.options['cnctooldia'] *= factor
  4183. # self.options['painttooldia'] *= factor
  4184. # self.options['paintmargin'] *= factor
  4185. # self.options['paintoverlap'] *= factor
  4186. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  4187. if self.app.defaults["geometry_toolchangexy"] == '':
  4188. self.options['toolchangexy'] = "0.0, 0.0"
  4189. else:
  4190. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  4191. if len(coords_xy) < 2:
  4192. self.app.inform.emit(_(
  4193. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4194. "in the format (x, y) \nbut now there is only one value, not two. "
  4195. ))
  4196. return 'fail'
  4197. coords_xy[0] *= factor
  4198. coords_xy[1] *= factor
  4199. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4200. if self.options['startz'] is not None:
  4201. self.options['startz'] = float(self.options['startz']) * factor
  4202. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4203. 'endz', 'toolchangez']
  4204. if isinstance(self, FlatCAMGeometry):
  4205. temp_tools_dict = {}
  4206. tool_dia_copy = {}
  4207. data_copy = {}
  4208. for tooluid_key, tooluid_value in self.tools.items():
  4209. for dia_key, dia_value in tooluid_value.items():
  4210. if dia_key == 'tooldia':
  4211. dia_value *= factor
  4212. dia_value = float('%.4f' % dia_value)
  4213. tool_dia_copy[dia_key] = dia_value
  4214. if dia_key == 'offset':
  4215. tool_dia_copy[dia_key] = dia_value
  4216. if dia_key == 'offset_value':
  4217. dia_value *= factor
  4218. tool_dia_copy[dia_key] = dia_value
  4219. # convert the value in the Custom Tool Offset entry in UI
  4220. custom_offset = None
  4221. try:
  4222. custom_offset = float(self.ui.tool_offset_entry.get_value())
  4223. except ValueError:
  4224. # try to convert comma to decimal point. if it's still not working error message and return
  4225. try:
  4226. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  4227. )
  4228. except ValueError:
  4229. self.app.inform.emit(_(
  4230. "[ERROR_NOTCL] Wrong value format entered, "
  4231. "use a number."
  4232. ))
  4233. return
  4234. except TypeError:
  4235. pass
  4236. if custom_offset:
  4237. custom_offset *= factor
  4238. self.ui.tool_offset_entry.set_value(custom_offset)
  4239. if dia_key == 'type':
  4240. tool_dia_copy[dia_key] = dia_value
  4241. if dia_key == 'tool_type':
  4242. tool_dia_copy[dia_key] = dia_value
  4243. if dia_key == 'data':
  4244. for data_key, data_value in dia_value.items():
  4245. # convert the form fields that are convertible
  4246. for param in param_list:
  4247. if data_key == param and data_value is not None:
  4248. data_copy[data_key] = data_value * factor
  4249. # copy the other dict entries that are not convertible
  4250. if data_key not in param_list:
  4251. data_copy[data_key] = data_value
  4252. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4253. data_copy.clear()
  4254. temp_tools_dict.update({
  4255. tooluid_key: deepcopy(tool_dia_copy)
  4256. })
  4257. tool_dia_copy.clear()
  4258. self.tools.clear()
  4259. self.tools = deepcopy(temp_tools_dict)
  4260. # if there is a value in the new tool field then convert that one too
  4261. tooldia = self.ui.addtool_entry.get_value()
  4262. if tooldia:
  4263. tooldia *= factor
  4264. # limit the decimals to 2 for METRIC and 3 for INCH
  4265. if units.lower() == 'in':
  4266. tooldia = float('%.4f' % tooldia)
  4267. else:
  4268. tooldia = float('%.2f' % tooldia)
  4269. self.ui.addtool_entry.set_value(tooldia)
  4270. return factor
  4271. def plot_element(self, element, color='red', visible=None):
  4272. visible = visible if visible else self.options['plot']
  4273. try:
  4274. for sub_el in element:
  4275. self.plot_element(sub_el)
  4276. except TypeError: # Element is not iterable...
  4277. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4278. def plot(self, visible=None, kind=None):
  4279. """
  4280. Plot the object.
  4281. :param visible: Controls if the added shape is visible of not
  4282. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4283. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4284. :return:
  4285. """
  4286. # Does all the required setup and returns False
  4287. # if the 'ptint' option is set to False.
  4288. if not FlatCAMObj.plot(self):
  4289. return
  4290. try:
  4291. # plot solid geometries found as members of self.tools attribute dict
  4292. # for MultiGeo
  4293. if self.multigeo == True: # geo multi tool usage
  4294. for tooluid_key in self.tools:
  4295. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4296. self.plot_element(solid_geometry, visible=visible)
  4297. # plot solid geometry that may be an direct attribute of the geometry object
  4298. # for SingleGeo
  4299. if self.solid_geometry:
  4300. self.plot_element(self.solid_geometry, visible=visible)
  4301. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4302. self.shapes.redraw()
  4303. except (ObjectDeleted, AttributeError):
  4304. self.shapes.clear(update=True)
  4305. def on_plot_cb_click(self, *args):
  4306. if self.muted_ui:
  4307. return
  4308. self.plot()
  4309. self.read_form_item('plot')
  4310. self.ui_disconnect()
  4311. cb_flag = self.ui.plot_cb.isChecked()
  4312. for row in range(self.ui.geo_tools_table.rowCount()):
  4313. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4314. if cb_flag:
  4315. table_cb.setChecked(True)
  4316. else:
  4317. table_cb.setChecked(False)
  4318. self.ui_connect()
  4319. def on_plot_cb_click_table(self):
  4320. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4321. self.ui_disconnect()
  4322. cw = self.sender()
  4323. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4324. cw_row = cw_index.row()
  4325. check_row = 0
  4326. self.shapes.clear(update=True)
  4327. for tooluid_key in self.tools:
  4328. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4329. # find the geo_tool_table row associated with the tooluid_key
  4330. for row in range(self.ui.geo_tools_table.rowCount()):
  4331. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4332. if tooluid_item == int(tooluid_key):
  4333. check_row = row
  4334. break
  4335. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4336. self.plot_element(element=solid_geometry, visible=True)
  4337. self.shapes.redraw()
  4338. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4339. # if all the row plot's are enabled also enable the general plot checkbox
  4340. cb_cnt = 0
  4341. total_row = self.ui.geo_tools_table.rowCount()
  4342. for row in range(total_row):
  4343. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4344. cb_cnt += 1
  4345. else:
  4346. cb_cnt -= 1
  4347. if cb_cnt < total_row:
  4348. self.ui.plot_cb.setChecked(False)
  4349. else:
  4350. self.ui.plot_cb.setChecked(True)
  4351. self.ui_connect()
  4352. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4353. """
  4354. Represents G-Code.
  4355. """
  4356. optionChanged = QtCore.pyqtSignal(str)
  4357. ui_type = CNCObjectUI
  4358. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4359. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4360. spindlespeed=None):
  4361. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4362. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4363. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4364. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4365. FlatCAMObj.__init__(self, name)
  4366. self.kind = "cncjob"
  4367. self.options.update({
  4368. "plot": True,
  4369. "tooldia": 0.03937, # 0.4mm in inches
  4370. "append": "",
  4371. "prepend": "",
  4372. "dwell": False,
  4373. "dwelltime": 1,
  4374. "type": 'Geometry',
  4375. "toolchange_macro": '',
  4376. "toolchange_macro_enable": False
  4377. })
  4378. '''
  4379. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4380. diameter of the tools and the value is another dict that will hold the data under the following form:
  4381. {tooldia: {
  4382. 'tooluid': 1,
  4383. 'offset': 'Path',
  4384. 'type_item': 'Rough',
  4385. 'tool_type': 'C1',
  4386. 'data': {} # a dict to hold the parameters
  4387. 'gcode': "" # a string with the actual GCODE
  4388. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4389. 'solid_geometry': []
  4390. },
  4391. ...
  4392. }
  4393. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  4394. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4395. '''
  4396. self.cnc_tools = {}
  4397. '''
  4398. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4399. diameter of the tools and the value is another dict that will hold the data under the following form:
  4400. {tooldia: {
  4401. 'tool': int,
  4402. 'nr_drills': int,
  4403. 'nr_slots': int,
  4404. 'offset': float,
  4405. 'data': {} # a dict to hold the parameters
  4406. 'gcode': "" # a string with the actual GCODE
  4407. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4408. 'solid_geometry': []
  4409. },
  4410. ...
  4411. }
  4412. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  4413. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  4414. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4415. '''
  4416. self.exc_cnc_tools = {}
  4417. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  4418. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  4419. self.special_group = None
  4420. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  4421. # (like the one in the TCL Command), False
  4422. self.multitool = False
  4423. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  4424. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  4425. self.g_x_re = re.compile(gcodex_re_string)
  4426. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  4427. self.g_y_re = re.compile(gcodey_re_string)
  4428. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  4429. self.g_z_re = re.compile(gcodez_re_string)
  4430. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  4431. self.g_f_re = re.compile(gcodef_re_string)
  4432. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  4433. self.g_t_re = re.compile(gcodet_re_string)
  4434. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  4435. self.g_nr_re = re.compile(gcodenr_re_string)
  4436. # Attributes to be included in serialization
  4437. # Always append to it because it carries contents
  4438. # from predecessors.
  4439. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  4440. self.annotation = self.app.plotcanvas.new_text_group()
  4441. def build_ui(self):
  4442. self.ui_disconnect()
  4443. FlatCAMObj.build_ui(self)
  4444. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  4445. if self.cnc_tools:
  4446. self.ui.cnc_tools_table.show()
  4447. else:
  4448. self.ui.cnc_tools_table.hide()
  4449. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4450. offset = 0
  4451. tool_idx = 0
  4452. n = len(self.cnc_tools)
  4453. self.ui.cnc_tools_table.setRowCount(n)
  4454. for dia_key, dia_value in self.cnc_tools.items():
  4455. tool_idx += 1
  4456. row_no = tool_idx - 1
  4457. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  4458. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4459. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  4460. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  4461. # There are no tool bits in MM with more than 2 decimals diameter.
  4462. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  4463. if self.units == 'MM':
  4464. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  4465. else:
  4466. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  4467. offset_txt = list(str(dia_value['offset']))
  4468. offset_txt[0] = offset_txt[0].upper()
  4469. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  4470. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  4471. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  4472. id.setFlags(QtCore.Qt.ItemIsEnabled)
  4473. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4474. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4475. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4476. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4477. # hack so the checkbox stay centered in the table cell
  4478. # used this:
  4479. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  4480. # plot_item = QtWidgets.QWidget()
  4481. # checkbox = FCCheckBox()
  4482. # checkbox.setCheckState(QtCore.Qt.Checked)
  4483. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  4484. # qhboxlayout.addWidget(checkbox)
  4485. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  4486. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  4487. plot_item = FCCheckBox()
  4488. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  4489. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  4490. if self.ui.plot_cb.isChecked():
  4491. plot_item.setChecked(True)
  4492. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  4493. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  4494. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  4495. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  4496. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  4497. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  4498. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  4499. # make the diameter column editable
  4500. # for row in range(tool_idx):
  4501. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4502. # QtCore.Qt.ItemIsEnabled)
  4503. for row in range(tool_idx):
  4504. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4505. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4506. self.ui.cnc_tools_table.resizeColumnsToContents()
  4507. self.ui.cnc_tools_table.resizeRowsToContents()
  4508. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4509. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4510. vertical_header.hide()
  4511. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4512. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4513. horizontal_header.setMinimumSectionSize(10)
  4514. horizontal_header.setDefaultSectionSize(70)
  4515. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4516. horizontal_header.resizeSection(0, 20)
  4517. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4518. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4519. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4520. horizontal_header.resizeSection(4, 40)
  4521. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4522. horizontal_header.resizeSection(4, 17)
  4523. # horizontal_header.setStretchLastSection(True)
  4524. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4525. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4526. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4527. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4528. # self.ui.geo_tools_table.setSortingEnabled(True)
  4529. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4530. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4531. self.ui_connect()
  4532. def set_ui(self, ui):
  4533. FlatCAMObj.set_ui(self, ui)
  4534. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4535. assert isinstance(self.ui, CNCObjectUI), \
  4536. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4537. # this signal has to be connected to it's slot before the defaults are populated
  4538. # the decision done in the slot has to override the default value set bellow
  4539. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  4540. self.form_fields.update({
  4541. "plot": self.ui.plot_cb,
  4542. # "tooldia": self.ui.tooldia_entry,
  4543. "append": self.ui.append_text,
  4544. "prepend": self.ui.prepend_text,
  4545. "toolchange_macro": self.ui.toolchange_text,
  4546. "toolchange_macro_enable": self.ui.toolchange_cb
  4547. })
  4548. # Fill form fields only on object create
  4549. self.to_form()
  4550. # this means that the object that created this CNCJob was an Excellon
  4551. try:
  4552. if self.travel_distance:
  4553. self.ui.t_distance_label.show()
  4554. self.ui.t_distance_entry.setVisible(True)
  4555. self.ui.t_distance_entry.setDisabled(True)
  4556. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4557. self.ui.units_label.setText(str(self.units).lower())
  4558. self.ui.units_label.setDisabled(True)
  4559. except AttributeError:
  4560. pass
  4561. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4562. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4563. try:
  4564. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  4565. except:
  4566. pass
  4567. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  4568. # set if to display text annotations
  4569. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  4570. # Show/Hide Advanced Options
  4571. if self.app.defaults["global_app_level"] == 'b':
  4572. self.ui.level.setText(_(
  4573. '<span style="color:green;"><b>Basic</b></span>'
  4574. ))
  4575. self.ui.cnc_frame.hide()
  4576. else:
  4577. self.ui.level.setText(_(
  4578. '<span style="color:red;"><b>Advanced</b></span>'
  4579. ))
  4580. self.ui.cnc_frame.show()
  4581. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4582. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4583. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  4584. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  4585. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4586. def on_cnc_custom_parameters(self, signal_text):
  4587. if signal_text == 'Parameters':
  4588. return
  4589. else:
  4590. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4591. def ui_connect(self):
  4592. for row in range(self.ui.cnc_tools_table.rowCount()):
  4593. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4594. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4595. def ui_disconnect(self):
  4596. for row in range(self.ui.cnc_tools_table.rowCount()):
  4597. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4598. try:
  4599. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4600. except:
  4601. pass
  4602. def on_updateplot_button_click(self, *args):
  4603. """
  4604. Callback for the "Updata Plot" button. Reads the form for updates
  4605. and plots the object.
  4606. """
  4607. self.read_form()
  4608. self.plot()
  4609. def on_plot_kind_change(self):
  4610. kind = self.ui.cncplot_method_combo.get_value()
  4611. self.plot(kind=kind)
  4612. def on_exportgcode_button_click(self, *args):
  4613. self.app.report_usage("cncjob_on_exportgcode_button")
  4614. self.read_form()
  4615. name = self.app.collection.get_active().options['name']
  4616. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4617. _filter_ = "RML1 Files (*.rol);;" \
  4618. "All Files (*.*)"
  4619. elif 'hpgl' in self.pp_geometry_name:
  4620. _filter_ = "HPGL Files (*.plt);;" \
  4621. "All Files (*.*)"
  4622. else:
  4623. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4624. "G-Code Files (*.g-code);;All Files (*.*)"
  4625. try:
  4626. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4627. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4628. caption=_("Export Machine Code ..."),
  4629. directory=dir_file_to_save,
  4630. filter=_filter_
  4631. )
  4632. except TypeError:
  4633. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  4634. filename = str(filename)
  4635. if filename == '':
  4636. self.app.inform.emit(_(
  4637. "[WARNING_NOTCL] Export Machine Code cancelled ..."))
  4638. return
  4639. preamble = str(self.ui.prepend_text.get_value())
  4640. postamble = str(self.ui.append_text.get_value())
  4641. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4642. if gc == 'fail':
  4643. return
  4644. if self.app.defaults["global_open_style"] is False:
  4645. self.app.file_opened.emit("gcode", filename)
  4646. self.app.file_saved.emit("gcode", filename)
  4647. self.app.inform.emit(_("[success] Machine Code file saved to: %s") % filename)
  4648. def on_edit_code_click(self, *args):
  4649. preamble = str(self.ui.prepend_text.get_value())
  4650. postamble = str(self.ui.append_text.get_value())
  4651. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4652. if gc == 'fail':
  4653. return
  4654. else:
  4655. self.app.gcode_edited = gc
  4656. self.app.init_code_editor(name=_("Code Editor"))
  4657. self.app.ui.buttonOpen.clicked.connect(self.app.handleOpen)
  4658. self.app.ui.buttonSave.clicked.connect(self.app.handleSaveGCode)
  4659. # then append the text from GCode to the text editor
  4660. try:
  4661. for line in self.app.gcode_edited:
  4662. proc_line = str(line).strip('\n')
  4663. self.app.ui.code_editor.append(proc_line)
  4664. except Exception as e:
  4665. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  4666. self.app.inform.emit(_('[ERROR]FlatCAMCNNJob.on_edit_code_click() -->%s') % str(e))
  4667. return
  4668. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4669. self.app.handleTextChanged()
  4670. self.app.ui.show()
  4671. def gcode_header(self):
  4672. log.debug("FlatCAMCNCJob.gcode_header()")
  4673. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4674. marlin = False
  4675. hpgl = False
  4676. probe_pp = False
  4677. try:
  4678. for key in self.cnc_tools:
  4679. ppg = self.cnc_tools[key]['data']['ppname_g']
  4680. if ppg == 'marlin' or ppg == 'Repetier':
  4681. marlin = True
  4682. break
  4683. if ppg == 'hpgl':
  4684. hpgl = True
  4685. break
  4686. if "toolchange_probe" in ppg.lower():
  4687. probe_pp = True
  4688. break
  4689. except Exception as e:
  4690. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4691. try:
  4692. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4693. marlin = True
  4694. except Exception as e:
  4695. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4696. try:
  4697. if "toolchange_probe" in self.options['ppname_e'].lower():
  4698. probe_pp = True
  4699. except Exception as e:
  4700. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4701. if marlin is True:
  4702. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4703. (str(self.app.version), str(self.app.version_date)) + '\n'
  4704. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4705. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4706. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4707. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4708. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4709. gcode += ';Created on ' + time_str + '\n' + '\n'
  4710. elif hpgl is True:
  4711. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4712. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4713. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4714. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4715. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4716. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4717. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4718. gcode += 'CO "Created on ' + time_str + '";\n'
  4719. elif probe_pp is True:
  4720. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4721. (str(self.app.version), str(self.app.version_date)) + '\n'
  4722. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4723. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4724. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4725. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4726. 'Then zero the Z axis.)\n' + '\n'
  4727. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4728. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4729. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4730. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4731. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4732. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4733. else:
  4734. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4735. (str(self.app.version), str(self.app.version_date)) + '\n'
  4736. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4737. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4738. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4739. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4740. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4741. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4742. return gcode
  4743. def gcode_footer(self, end_command=None):
  4744. """
  4745. :param end_command: 'M02' or 'M30' - String
  4746. :return:
  4747. """
  4748. if end_command:
  4749. return end_command
  4750. else:
  4751. return 'M02'
  4752. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4753. gcode = ''
  4754. roland = False
  4755. hpgl = False
  4756. try:
  4757. if self.special_group:
  4758. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed because "
  4759. "it is a %s CNCJob object.") % str(self.special_group))
  4760. return 'fail'
  4761. except AttributeError:
  4762. pass
  4763. # detect if using Roland postprocessor
  4764. try:
  4765. for key in self.cnc_tools:
  4766. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4767. roland = True
  4768. break
  4769. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4770. hpgl = True
  4771. break
  4772. except:
  4773. try:
  4774. for key in self.cnc_tools:
  4775. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4776. roland = True
  4777. break
  4778. except:
  4779. pass
  4780. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4781. if roland is False and hpgl is False:
  4782. gcode = self.gcode_header()
  4783. # detect if using multi-tool and make the Gcode summation correctly for each case
  4784. if self.multitool is True:
  4785. for tooluid_key in self.cnc_tools:
  4786. for key, value in self.cnc_tools[tooluid_key].items():
  4787. if key == 'gcode':
  4788. gcode += value
  4789. break
  4790. else:
  4791. gcode += self.gcode
  4792. if roland is True:
  4793. g = preamble + gcode + postamble
  4794. elif hpgl is True:
  4795. g = self.gcode_header() + preamble + gcode + postamble
  4796. else:
  4797. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4798. g_idx = gcode.rfind('G20')
  4799. # if it did not find 'G20' then search for 'G21'
  4800. if g_idx == -1:
  4801. g_idx = gcode.rfind('G21')
  4802. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4803. if g_idx == -1:
  4804. self.app.inform.emit(_(
  4805. "[ERROR_NOTCL] G-code does not have a units code: either G20 or G21"
  4806. ))
  4807. return
  4808. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + self.gcode_footer()
  4809. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  4810. if self.ui.toolchange_cb.get_value() is True:
  4811. # match = self.re_toolchange.search(g)
  4812. if 'M6' in g:
  4813. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  4814. if m6_code is None or m6_code == '':
  4815. self.app.inform.emit(_(
  4816. "[ERROR_NOTCL] Cancelled. The Toolchange Custom code is enabled "
  4817. "but it's empty."
  4818. ))
  4819. return 'fail'
  4820. g = g.replace('M6', m6_code)
  4821. self.app.inform.emit(_(
  4822. "[success] Toolchange G-code was replaced by a custom code."
  4823. ))
  4824. # lines = StringIO(self.gcode)
  4825. lines = StringIO(g)
  4826. # Write
  4827. if filename is not None:
  4828. try:
  4829. with open(filename, 'w') as f:
  4830. for line in lines:
  4831. f.write(line)
  4832. except FileNotFoundError:
  4833. self.app.inform.emit(_(
  4834. "[WARNING_NOTCL] No such file or directory"
  4835. ))
  4836. return
  4837. elif to_file is False:
  4838. # Just for adding it to the recent files list.
  4839. if self.app.defaults["global_open_style"] is False:
  4840. self.app.file_opened.emit("cncjob", filename)
  4841. self.app.file_saved.emit("cncjob", filename)
  4842. self.app.inform.emit("[success] Saved to: " + filename)
  4843. else:
  4844. return lines
  4845. def on_toolchange_custom_clicked(self, signal):
  4846. try:
  4847. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  4848. if self.ui.toolchange_cb.get_value():
  4849. self.ui.toolchange_cb.set_value(False)
  4850. self.app.inform.emit(
  4851. _(
  4852. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: 'toolchange_custom'"
  4853. ))
  4854. except KeyError:
  4855. try:
  4856. for key in self.cnc_tools:
  4857. ppg = self.cnc_tools[key]['data']['ppname_g']
  4858. if 'toolchange_custom' not in str(ppg).lower():
  4859. print(ppg)
  4860. if self.ui.toolchange_cb.get_value():
  4861. self.ui.toolchange_cb.set_value(False)
  4862. self.app.inform.emit(
  4863. _(
  4864. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: "
  4865. "'toolchange_custom'"
  4866. ))
  4867. except KeyError:
  4868. self.app.inform.emit(
  4869. _(
  4870. "[ERROR] There is no postprocessor file."
  4871. ))
  4872. def get_gcode(self, preamble='', postamble=''):
  4873. #we need this to be able get_gcode separatelly for shell command export_gcode
  4874. return preamble + '\n' + self.gcode + "\n" + postamble
  4875. def get_svg(self):
  4876. # we need this to be able get_svg separately for shell command export_svg
  4877. pass
  4878. def on_plot_cb_click(self, *args):
  4879. if self.muted_ui:
  4880. return
  4881. kind = self.ui.cncplot_method_combo.get_value()
  4882. self.plot(kind=kind)
  4883. self.read_form_item('plot')
  4884. self.ui_disconnect()
  4885. cb_flag = self.ui.plot_cb.isChecked()
  4886. for row in range(self.ui.cnc_tools_table.rowCount()):
  4887. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4888. if cb_flag:
  4889. table_cb.setChecked(True)
  4890. else:
  4891. table_cb.setChecked(False)
  4892. self.ui_connect()
  4893. def on_plot_cb_click_table(self):
  4894. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4895. self.ui_disconnect()
  4896. cw = self.sender()
  4897. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4898. cw_row = cw_index.row()
  4899. kind = self.ui.cncplot_method_combo.get_value()
  4900. self.shapes.clear(update=True)
  4901. for tooluid_key in self.cnc_tools:
  4902. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4903. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4904. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4905. for r in range(self.ui.cnc_tools_table.rowCount()):
  4906. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4907. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4908. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4909. self.shapes.redraw()
  4910. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4911. # if all the row plot's are enabled also enable the general plot checkbox
  4912. cb_cnt = 0
  4913. total_row = self.ui.cnc_tools_table.rowCount()
  4914. for row in range(total_row):
  4915. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4916. cb_cnt += 1
  4917. else:
  4918. cb_cnt -= 1
  4919. if cb_cnt < total_row:
  4920. self.ui.plot_cb.setChecked(False)
  4921. else:
  4922. self.ui.plot_cb.setChecked(True)
  4923. self.ui_connect()
  4924. def plot(self, visible=None, kind='all'):
  4925. # Does all the required setup and returns False
  4926. # if the 'ptint' option is set to False.
  4927. if not FlatCAMObj.plot(self):
  4928. return
  4929. visible = visible if visible else self.options['plot']
  4930. try:
  4931. if self.multitool is False: # single tool usage
  4932. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4933. else:
  4934. # multiple tools usage
  4935. for tooluid_key in self.cnc_tools:
  4936. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4937. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4938. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4939. self.shapes.redraw()
  4940. except (ObjectDeleted, AttributeError):
  4941. self.shapes.clear(update=True)
  4942. self.annotation.clear(update=True)
  4943. def on_annotation_change(self):
  4944. if self.ui.annotation_cb.get_value():
  4945. self.app.plotcanvas.text_collection.enabled = True
  4946. else:
  4947. self.app.plotcanvas.text_collection.enabled = False
  4948. kind = self.ui.cncplot_method_combo.get_value()
  4949. self.plot(kind=kind)
  4950. def convert_units(self, units):
  4951. factor = CNCjob.convert_units(self, units)
  4952. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4953. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4954. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4955. 'endz', 'toolchangez']
  4956. temp_tools_dict = {}
  4957. tool_dia_copy = {}
  4958. data_copy = {}
  4959. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4960. for dia_key, dia_value in tooluid_value.items():
  4961. if dia_key == 'tooldia':
  4962. dia_value *= factor
  4963. dia_value = float('%.4f' % dia_value)
  4964. tool_dia_copy[dia_key] = dia_value
  4965. if dia_key == 'offset':
  4966. tool_dia_copy[dia_key] = dia_value
  4967. if dia_key == 'offset_value':
  4968. dia_value *= factor
  4969. tool_dia_copy[dia_key] = dia_value
  4970. if dia_key == 'type':
  4971. tool_dia_copy[dia_key] = dia_value
  4972. if dia_key == 'tool_type':
  4973. tool_dia_copy[dia_key] = dia_value
  4974. if dia_key == 'data':
  4975. for data_key, data_value in dia_value.items():
  4976. # convert the form fields that are convertible
  4977. for param in param_list:
  4978. if data_key == param and data_value is not None:
  4979. data_copy[data_key] = data_value * factor
  4980. # copy the other dict entries that are not convertible
  4981. if data_key not in param_list:
  4982. data_copy[data_key] = data_value
  4983. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4984. data_copy.clear()
  4985. if dia_key == 'gcode':
  4986. tool_dia_copy[dia_key] = dia_value
  4987. if dia_key == 'gcode_parsed':
  4988. tool_dia_copy[dia_key] = dia_value
  4989. if dia_key == 'solid_geometry':
  4990. tool_dia_copy[dia_key] = dia_value
  4991. # if dia_key == 'solid_geometry':
  4992. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4993. # if dia_key == 'gcode_parsed':
  4994. # for g in dia_value:
  4995. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4996. #
  4997. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  4998. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4999. temp_tools_dict.update({
  5000. tooluid_key: deepcopy(tool_dia_copy)
  5001. })
  5002. tool_dia_copy.clear()
  5003. self.cnc_tools.clear()
  5004. self.cnc_tools = deepcopy(temp_tools_dict)
  5005. # end of file