FlatCAMObj.py 354 KB

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