FlatCAMObj.py 278 KB

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