FlatCAMObj.py 327 KB

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