FlatCAMObj.py 278 KB

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