FlatCAMObj.py 350 KB

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