FlatCAMObj.py 345 KB

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