FlatCAMObj.py 277 KB

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