FlatCAMObj.py 327 KB

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