FlatCAMObj.py 309 KB

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