FlatCAMObj.py 320 KB

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