FlatCAMObj.py 275 KB

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