FlatCAMObj.py 331 KB

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