FlatCAMObj.py 276 KB

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