FlatCAMObj.py 335 KB

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