FlatCAMObj.py 306 KB

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