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.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  3267. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  3268. self.ui.addtool_entry.returnPressed.connect(lambda: self.on_tool_add())
  3269. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  3270. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  3271. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  3272. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  3273. def set_tool_offset_visibility(self, current_row):
  3274. if current_row is None:
  3275. return
  3276. try:
  3277. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  3278. if tool_offset is not None:
  3279. tool_offset_txt = tool_offset.currentText()
  3280. if tool_offset_txt == 'Custom':
  3281. self.ui.tool_offset_entry.show()
  3282. self.ui.tool_offset_lbl.show()
  3283. else:
  3284. self.ui.tool_offset_entry.hide()
  3285. self.ui.tool_offset_lbl.hide()
  3286. except Exception as e:
  3287. log.debug("set_tool_offset_visibility() --> " + str(e))
  3288. return
  3289. def on_offset_value_edited(self):
  3290. """
  3291. This will save the offset_value into self.tools storage whenever the offset value is edited
  3292. :return:
  3293. """
  3294. for current_row in self.ui.geo_tools_table.selectedItems():
  3295. # sometime the header get selected and it has row number -1
  3296. # we don't want to do anything with the header :)
  3297. if current_row.row() < 0:
  3298. continue
  3299. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3300. self.set_tool_offset_visibility(current_row.row())
  3301. for tooluid_key, tooluid_value in self.tools.items():
  3302. if int(tooluid_key) == tool_uid:
  3303. try:
  3304. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  3305. except ValueError:
  3306. # try to convert comma to decimal point. if it's still not working error message and return
  3307. try:
  3308. tooluid_value['offset_value'] = float(
  3309. self.ui.tool_offset_entry.get_value().replace(',', '.')
  3310. )
  3311. except ValueError:
  3312. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3313. _("Wrong value format entered, use a number."))
  3314. return
  3315. def ui_connect(self):
  3316. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3317. # changes in geometry UI
  3318. for i in range(self.ui.grid3.count()):
  3319. current_widget = self.ui.grid3.itemAt(i).widget()
  3320. if isinstance(current_widget, FCCheckBox):
  3321. current_widget.stateChanged.connect(self.gui_form_to_storage)
  3322. elif isinstance(current_widget, FCComboBox):
  3323. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  3324. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  3325. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  3326. current_widget.editingFinished.connect(self.gui_form_to_storage)
  3327. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3328. current_widget.returnPressed.connect(self.gui_form_to_storage)
  3329. for row in range(self.ui.geo_tools_table.rowCount()):
  3330. for col in [2, 3, 4]:
  3331. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  3332. self.on_tooltable_cellwidget_change)
  3333. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  3334. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  3335. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  3336. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  3337. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  3338. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  3339. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  3340. for row in range(self.ui.geo_tools_table.rowCount()):
  3341. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3342. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3343. def ui_disconnect(self):
  3344. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3345. # changes in geometry UI
  3346. for i in range(self.ui.grid3.count()):
  3347. current_widget = self.ui.grid3.itemAt(i).widget()
  3348. if isinstance(current_widget, FCCheckBox):
  3349. try:
  3350. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  3351. except (TypeError, AttributeError):
  3352. pass
  3353. elif isinstance(current_widget, FCComboBox):
  3354. try:
  3355. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  3356. except (TypeError, AttributeError):
  3357. pass
  3358. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  3359. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  3360. try:
  3361. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  3362. except (TypeError, AttributeError):
  3363. pass
  3364. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3365. try:
  3366. self.ui.grid3.itemAt(i).widget().returnPressed.disconnect(self.gui_form_to_storage)
  3367. except TypeError:
  3368. pass
  3369. for row in range(self.ui.geo_tools_table.rowCount()):
  3370. for col in [2, 3, 4]:
  3371. try:
  3372. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3373. except (TypeError, AttributeError):
  3374. pass
  3375. try:
  3376. self.ui.addtool_btn.clicked.disconnect()
  3377. except (TypeError, AttributeError):
  3378. pass
  3379. try:
  3380. self.ui.copytool_btn.clicked.disconnect()
  3381. except (TypeError, AttributeError):
  3382. pass
  3383. try:
  3384. self.ui.deltool_btn.clicked.disconnect()
  3385. except (TypeError, AttributeError):
  3386. pass
  3387. try:
  3388. self.ui.geo_tools_table.currentItemChanged.disconnect()
  3389. except (TypeError, AttributeError):
  3390. pass
  3391. try:
  3392. self.ui.geo_tools_table.itemChanged.disconnect()
  3393. except (TypeError, AttributeError):
  3394. pass
  3395. try:
  3396. self.ui.tool_offset_entry.returnPressed.disconnect()
  3397. except (TypeError, AttributeError):
  3398. pass
  3399. for row in range(self.ui.geo_tools_table.rowCount()):
  3400. try:
  3401. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  3402. except (TypeError, AttributeError):
  3403. pass
  3404. try:
  3405. self.ui.plot_cb.stateChanged.disconnect()
  3406. except (TypeError, AttributeError):
  3407. pass
  3408. def on_tool_add(self, dia=None):
  3409. self.ui_disconnect()
  3410. self.units = self.app.defaults['units'].upper()
  3411. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  3412. # because the Default value for Tool is used.
  3413. change_message = False
  3414. if dia is not None:
  3415. tooldia = dia
  3416. else:
  3417. try:
  3418. tooldia = float(self.ui.addtool_entry.get_value())
  3419. except ValueError:
  3420. # try to convert comma to decimal point. if it's still not working error message and return
  3421. try:
  3422. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  3423. except ValueError:
  3424. change_message = True
  3425. tooldia = float(self.options["cnctooldia"][0])
  3426. if tooldia is None:
  3427. self.build_ui()
  3428. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3429. _("Please enter the desired tool diameter in Float format."))
  3430. return
  3431. # construct a list of all 'tooluid' in the self.tools
  3432. tool_uid_list = []
  3433. for tooluid_key in self.tools:
  3434. tool_uid_item = int(tooluid_key)
  3435. tool_uid_list.append(tool_uid_item)
  3436. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3437. if not tool_uid_list:
  3438. max_uid = 0
  3439. else:
  3440. max_uid = max(tool_uid_list)
  3441. self.tooluid = max_uid + 1
  3442. tooldia = float('%.*f' % (self.decimals, tooldia))
  3443. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  3444. # otherwise we add a tool with data copied from last tool
  3445. if not self.tools:
  3446. self.tools.update({
  3447. self.tooluid: {
  3448. 'tooldia': tooldia,
  3449. 'offset': 'Path',
  3450. 'offset_value': 0.0,
  3451. 'type': _('Rough'),
  3452. 'tool_type': 'C1',
  3453. 'data': deepcopy(self.default_data),
  3454. 'solid_geometry': self.solid_geometry
  3455. }
  3456. })
  3457. else:
  3458. last_data = self.tools[max_uid]['data']
  3459. last_offset = self.tools[max_uid]['offset']
  3460. last_offset_value = self.tools[max_uid]['offset_value']
  3461. last_type = self.tools[max_uid]['type']
  3462. last_tool_type = self.tools[max_uid]['tool_type']
  3463. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  3464. # if previous geometry was empty (it may happen for the first tool added)
  3465. # then copy the object.solid_geometry
  3466. if not last_solid_geometry:
  3467. last_solid_geometry = self.solid_geometry
  3468. self.tools.update({
  3469. self.tooluid: {
  3470. 'tooldia': tooldia,
  3471. 'offset': last_offset,
  3472. 'offset_value': last_offset_value,
  3473. 'type': last_type,
  3474. 'tool_type': last_tool_type,
  3475. 'data': deepcopy(last_data),
  3476. 'solid_geometry': deepcopy(last_solid_geometry)
  3477. }
  3478. })
  3479. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3480. self.ui.tool_offset_entry.hide()
  3481. self.ui.tool_offset_lbl.hide()
  3482. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3483. try:
  3484. self.ser_attrs.remove('tools')
  3485. except TypeError:
  3486. pass
  3487. self.ser_attrs.append('tools')
  3488. if change_message is False:
  3489. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  3490. else:
  3491. change_message = False
  3492. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3493. _("Default Tool added. Wrong value format entered."))
  3494. self.build_ui()
  3495. # if there is no tool left in the Tools Table, enable the parameters GUI
  3496. if self.ui.geo_tools_table.rowCount() != 0:
  3497. self.ui.geo_param_frame.setDisabled(False)
  3498. def on_tool_add_from_db_clicked(self):
  3499. """
  3500. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3501. and display the Tools Database tab in the form needed for the Tool adding
  3502. :return: None
  3503. """
  3504. # if the Tools Database is already opened focus on it
  3505. for idx in range(self.app.ui.plot_tab_area.count()):
  3506. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3507. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3508. break
  3509. self.app.on_tools_database()
  3510. self.app.tools_db_tab.buttons_frame.hide()
  3511. self.app.tools_db_tab.add_tool_from_db.show()
  3512. self.app.tools_db_tab.cancel_tool_from_db.show()
  3513. def on_tool_from_db_inserted(self, tool):
  3514. """
  3515. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3516. :param tool: a dict with the tool data
  3517. :return: None
  3518. """
  3519. self.ui_disconnect()
  3520. self.units = self.app.defaults['units'].upper()
  3521. tooldia = float(tool['tooldia'])
  3522. # construct a list of all 'tooluid' in the self.tools
  3523. tool_uid_list = []
  3524. for tooluid_key in self.tools:
  3525. tool_uid_item = int(tooluid_key)
  3526. tool_uid_list.append(tool_uid_item)
  3527. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3528. if not tool_uid_list:
  3529. max_uid = 0
  3530. else:
  3531. max_uid = max(tool_uid_list)
  3532. self.tooluid = max_uid + 1
  3533. tooldia = float('%.*f' % (self.decimals, tooldia))
  3534. self.tools.update({
  3535. self.tooluid: {
  3536. 'tooldia': tooldia,
  3537. 'offset': tool['offset'],
  3538. 'offset_value': float(tool['offset_value']),
  3539. 'type': tool['type'],
  3540. 'tool_type': tool['tool_type'],
  3541. 'data': deepcopy(tool['data']),
  3542. 'solid_geometry': self.solid_geometry
  3543. }
  3544. })
  3545. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3546. self.ui.tool_offset_entry.hide()
  3547. self.ui.tool_offset_lbl.hide()
  3548. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3549. try:
  3550. self.ser_attrs.remove('tools')
  3551. except TypeError:
  3552. pass
  3553. self.ser_attrs.append('tools')
  3554. self.build_ui()
  3555. # if there is no tool left in the Tools Table, enable the parameters GUI
  3556. if self.ui.geo_tools_table.rowCount() != 0:
  3557. self.ui.geo_param_frame.setDisabled(False)
  3558. def on_tool_copy(self, all=None):
  3559. self.ui_disconnect()
  3560. # find the tool_uid maximum value in the self.tools
  3561. uid_list = []
  3562. for key in self.tools:
  3563. uid_list.append(int(key))
  3564. try:
  3565. max_uid = max(uid_list, key=int)
  3566. except ValueError:
  3567. max_uid = 0
  3568. if all is None:
  3569. if self.ui.geo_tools_table.selectedItems():
  3570. for current_row in self.ui.geo_tools_table.selectedItems():
  3571. # sometime the header get selected and it has row number -1
  3572. # we don't want to do anything with the header :)
  3573. if current_row.row() < 0:
  3574. continue
  3575. try:
  3576. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3577. self.set_tool_offset_visibility(current_row.row())
  3578. max_uid += 1
  3579. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3580. except AttributeError:
  3581. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3582. _("Failed. Select a tool to copy."))
  3583. self.build_ui()
  3584. return
  3585. except Exception as e:
  3586. log.debug("on_tool_copy() --> " + str(e))
  3587. # deselect the table
  3588. # self.ui.geo_tools_table.clearSelection()
  3589. else:
  3590. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3591. _("Failed. Select a tool to copy."))
  3592. self.build_ui()
  3593. return
  3594. else:
  3595. # we copy all tools in geo_tools_table
  3596. try:
  3597. temp_tools = deepcopy(self.tools)
  3598. max_uid += 1
  3599. for tooluid in temp_tools:
  3600. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3601. temp_tools.clear()
  3602. except Exception as e:
  3603. log.debug("on_tool_copy() --> " + str(e))
  3604. # if there are no more tools in geo tools table then hide the tool offset
  3605. if not self.tools:
  3606. self.ui.tool_offset_entry.hide()
  3607. self.ui.tool_offset_lbl.hide()
  3608. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3609. try:
  3610. self.ser_attrs.remove('tools')
  3611. except ValueError:
  3612. pass
  3613. self.ser_attrs.append('tools')
  3614. self.build_ui()
  3615. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  3616. def on_tool_edit(self, current_item):
  3617. self.ui_disconnect()
  3618. current_row = current_item.row()
  3619. try:
  3620. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3621. except ValueError:
  3622. # try to convert comma to decimal point. if it's still not working error message and return
  3623. try:
  3624. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3625. except ValueError:
  3626. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  3627. return
  3628. tool_dia = float('%.*f' % (self.decimals, d))
  3629. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3630. self.tools[tooluid]['tooldia'] = tool_dia
  3631. try:
  3632. self.ser_attrs.remove('tools')
  3633. self.ser_attrs.append('tools')
  3634. except (TypeError, ValueError):
  3635. pass
  3636. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  3637. self.build_ui()
  3638. def on_tool_delete(self, all=None):
  3639. self.ui_disconnect()
  3640. if all is None:
  3641. if self.ui.geo_tools_table.selectedItems():
  3642. for current_row in self.ui.geo_tools_table.selectedItems():
  3643. # sometime the header get selected and it has row number -1
  3644. # we don't want to do anything with the header :)
  3645. if current_row.row() < 0:
  3646. continue
  3647. try:
  3648. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3649. self.set_tool_offset_visibility(current_row.row())
  3650. temp_tools = deepcopy(self.tools)
  3651. for tooluid_key in self.tools:
  3652. if int(tooluid_key) == tooluid_del:
  3653. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3654. # as a property of the object otherwise there will be nothing to hold it
  3655. if len(self.tools) == 1:
  3656. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3657. temp_tools.pop(tooluid_del, None)
  3658. self.tools = deepcopy(temp_tools)
  3659. temp_tools.clear()
  3660. except AttributeError:
  3661. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3662. _("Failed. Select a tool to delete."))
  3663. self.build_ui()
  3664. return
  3665. except Exception as e:
  3666. log.debug("on_tool_delete() --> " + str(e))
  3667. # deselect the table
  3668. # self.ui.geo_tools_table.clearSelection()
  3669. else:
  3670. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3671. _("Failed. Select a tool to delete."))
  3672. self.build_ui()
  3673. return
  3674. else:
  3675. # we delete all tools in geo_tools_table
  3676. self.tools.clear()
  3677. self.app.plot_all()
  3678. # if there are no more tools in geo tools table then hide the tool offset
  3679. if not self.tools:
  3680. self.ui.tool_offset_entry.hide()
  3681. self.ui.tool_offset_lbl.hide()
  3682. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3683. try:
  3684. self.ser_attrs.remove('tools')
  3685. except TypeError:
  3686. pass
  3687. self.ser_attrs.append('tools')
  3688. self.build_ui()
  3689. self.app.inform.emit('[success] %s' %
  3690. _("Tool was deleted in Tool Table."))
  3691. obj_active = self.app.collection.get_active()
  3692. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  3693. # we make it back SingleGeo
  3694. if self.ui.geo_tools_table.rowCount() <= 0:
  3695. obj_active.multigeo = False
  3696. obj_active.options['xmin'] = 0
  3697. obj_active.options['ymin'] = 0
  3698. obj_active.options['xmax'] = 0
  3699. obj_active.options['ymax'] = 0
  3700. if obj_active.multigeo is True:
  3701. try:
  3702. xmin, ymin, xmax, ymax = obj_active.bounds()
  3703. obj_active.options['xmin'] = xmin
  3704. obj_active.options['ymin'] = ymin
  3705. obj_active.options['xmax'] = xmax
  3706. obj_active.options['ymax'] = ymax
  3707. except Exception as e:
  3708. obj_active.options['xmin'] = 0
  3709. obj_active.options['ymin'] = 0
  3710. obj_active.options['xmax'] = 0
  3711. obj_active.options['ymax'] = 0
  3712. # if there is no tool left in the Tools Table, disable the parameters GUI
  3713. if self.ui.geo_tools_table.rowCount() == 0:
  3714. self.ui.geo_param_frame.setDisabled(True)
  3715. def on_row_selection_change(self):
  3716. self.update_ui()
  3717. def update_ui(self, row=None):
  3718. self.ui_disconnect()
  3719. if row is None:
  3720. try:
  3721. current_row = self.ui.geo_tools_table.currentRow()
  3722. except Exception:
  3723. current_row = 0
  3724. else:
  3725. current_row = row
  3726. if current_row < 0:
  3727. current_row = 0
  3728. self.set_tool_offset_visibility(current_row)
  3729. # populate the form with the data from the tool associated with the row parameter
  3730. try:
  3731. item = self.ui.geo_tools_table.item(current_row, 5)
  3732. if type(item) is not None:
  3733. tooluid = int(item.text())
  3734. else:
  3735. return
  3736. except Exception as e:
  3737. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3738. return
  3739. # update the QLabel that shows for which Tool we have the parameters in the UI form
  3740. self.ui.tool_data_label.setText(
  3741. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  3742. )
  3743. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3744. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3745. try:
  3746. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3747. if item is not None:
  3748. tool_type_txt = item.currentText()
  3749. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3750. else:
  3751. return
  3752. except Exception as e:
  3753. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  3754. return
  3755. try:
  3756. # set the form with data from the newly selected tool
  3757. for tooluid_key, tooluid_value in list(self.tools.items()):
  3758. if int(tooluid_key) == tooluid:
  3759. for key, value in tooluid_value.items():
  3760. if key == 'data':
  3761. form_value_storage = tooluid_value[key]
  3762. self.update_form(form_value_storage)
  3763. if key == 'offset_value':
  3764. # update the offset value in the entry even if the entry is hidden
  3765. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  3766. if key == 'tool_type' and value == 'V':
  3767. self.update_cutz()
  3768. except Exception as e:
  3769. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  3770. self.ui_connect()
  3771. def ui_update_v_shape(self, tool_type_txt):
  3772. if tool_type_txt == 'V':
  3773. self.ui.tipdialabel.show()
  3774. self.ui.tipdia_entry.show()
  3775. self.ui.tipanglelabel.show()
  3776. self.ui.tipangle_entry.show()
  3777. self.ui.cutz_entry.setDisabled(True)
  3778. self.update_cutz()
  3779. else:
  3780. self.ui.tipdialabel.hide()
  3781. self.ui.tipdia_entry.hide()
  3782. self.ui.tipanglelabel.hide()
  3783. self.ui.tipangle_entry.hide()
  3784. self.ui.cutz_entry.setDisabled(False)
  3785. def update_cutz(self):
  3786. vdia = float(self.ui.tipdia_entry.get_value())
  3787. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  3788. row = self.ui.geo_tools_table.currentRow()
  3789. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  3790. if tool_uid_item is None:
  3791. return
  3792. tool_uid = int(tool_uid_item.text())
  3793. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  3794. if tool_dia_item is None:
  3795. return
  3796. tooldia = float(tool_dia_item.text())
  3797. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3798. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  3799. self.ui.cutz_entry.set_value(new_cutz)
  3800. # store the new CutZ value into storage (self.tools)
  3801. for tooluid_key, tooluid_value in self.tools.items():
  3802. if int(tooluid_key) == tool_uid:
  3803. tooluid_value['data']['cutz'] = new_cutz
  3804. def on_tooltable_cellwidget_change(self):
  3805. cw = self.sender()
  3806. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3807. cw_row = cw_index.row()
  3808. cw_col = cw_index.column()
  3809. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3810. # store the text of the cellWidget that changed it's index in the self.tools
  3811. for tooluid_key, tooluid_value in self.tools.items():
  3812. if int(tooluid_key) == current_uid:
  3813. cb_txt = cw.currentText()
  3814. if cw_col == 2:
  3815. tooluid_value['offset'] = cb_txt
  3816. if cb_txt == 'Custom':
  3817. self.ui.tool_offset_entry.show()
  3818. self.ui.tool_offset_lbl.show()
  3819. else:
  3820. self.ui.tool_offset_entry.hide()
  3821. self.ui.tool_offset_lbl.hide()
  3822. # reset the offset_value in storage self.tools
  3823. tooluid_value['offset_value'] = 0.0
  3824. elif cw_col == 3:
  3825. # force toolpath type as 'Iso' if the tool type is V-Shape
  3826. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3827. tooluid_value['type'] = _('Iso')
  3828. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3829. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3830. else:
  3831. tooluid_value['type'] = cb_txt
  3832. elif cw_col == 4:
  3833. tooluid_value['tool_type'] = cb_txt
  3834. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3835. if cb_txt == 'V':
  3836. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3837. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3838. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3839. def update_form(self, dict_storage):
  3840. for form_key in self.form_fields:
  3841. for storage_key in dict_storage:
  3842. if form_key == storage_key:
  3843. try:
  3844. self.form_fields[form_key].set_value(dict_storage[form_key])
  3845. except Exception as e:
  3846. log.debug(str(e))
  3847. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3848. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3849. self.ui.ois_dwell_geo.on_cb_change()
  3850. self.ui.ois_mpass_geo.on_cb_change()
  3851. self.ui.ois_tcz_geo.on_cb_change()
  3852. def on_apply_param_to_all_clicked(self):
  3853. if self.ui.geo_tools_table.rowCount() == 0:
  3854. # there is no tool in tool table so we can't save the GUI elements values to storage
  3855. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  3856. return
  3857. self.ui_disconnect()
  3858. row = self.ui.geo_tools_table.currentRow()
  3859. if row < 0:
  3860. row = 0
  3861. # store all the data associated with the row parameter to the self.tools storage
  3862. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3863. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3864. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3865. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3866. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3867. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3868. temp_tools = {}
  3869. temp_dia = {}
  3870. temp_data = {}
  3871. for tooluid_key, tooluid_value in self.tools.items():
  3872. for key, value in tooluid_value.items():
  3873. if key == 'tooldia':
  3874. temp_dia[key] = tooldia_item
  3875. # update the 'offset', 'type' and 'tool_type' sections
  3876. if key == 'offset':
  3877. temp_dia[key] = offset_item
  3878. if key == 'type':
  3879. temp_dia[key] = type_item
  3880. if key == 'tool_type':
  3881. temp_dia[key] = tool_type_item
  3882. if key == 'offset_value':
  3883. temp_dia[key] = offset_value_item
  3884. if key == 'data':
  3885. # update the 'data' section
  3886. for data_key in tooluid_value[key].keys():
  3887. for form_key, form_value in self.form_fields.items():
  3888. if form_key == data_key:
  3889. temp_data[data_key] = form_value.get_value()
  3890. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3891. # updated from self.app.defaults
  3892. if data_key not in self.form_fields:
  3893. temp_data[data_key] = value[data_key]
  3894. temp_dia[key] = deepcopy(temp_data)
  3895. temp_data.clear()
  3896. if key == 'solid_geometry':
  3897. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3898. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3899. self.tools.clear()
  3900. self.tools = deepcopy(temp_tools)
  3901. temp_tools.clear()
  3902. self.ui_connect()
  3903. def gui_form_to_storage(self):
  3904. if self.ui.geo_tools_table.rowCount() == 0:
  3905. # there is no tool in tool table so we can't save the GUI elements values to storage
  3906. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  3907. return
  3908. self.ui_disconnect()
  3909. widget_changed = self.sender()
  3910. try:
  3911. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3912. except Exception as e:
  3913. return
  3914. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3915. if widget_idx == 1 or widget_idx == 3:
  3916. self.update_cutz()
  3917. # the original connect() function of the OptionalInputSelection is no longer working because of the
  3918. # ui_diconnect() so I use this 'hack'
  3919. if isinstance(widget_changed, FCCheckBox):
  3920. if widget_changed.text() == 'Multi-Depth:':
  3921. self.ui.ois_mpass_geo.on_cb_change()
  3922. if widget_changed.text() == 'Tool change':
  3923. self.ui.ois_tcz_geo.on_cb_change()
  3924. if widget_changed.text() == 'Dwell:':
  3925. self.ui.ois_dwell_geo.on_cb_change()
  3926. row = self.ui.geo_tools_table.currentRow()
  3927. if row < 0:
  3928. row = 0
  3929. # store all the data associated with the row parameter to the self.tools storage
  3930. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3931. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3932. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3933. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3934. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3935. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3936. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3937. temp_tools = {}
  3938. temp_dia = {}
  3939. temp_data = {}
  3940. for tooluid_key, tooluid_value in self.tools.items():
  3941. if int(tooluid_key) == tooluid_item:
  3942. for key, value in tooluid_value.items():
  3943. if key == 'tooldia':
  3944. temp_dia[key] = tooldia_item
  3945. # update the 'offset', 'type' and 'tool_type' sections
  3946. if key == 'offset':
  3947. temp_dia[key] = offset_item
  3948. if key == 'type':
  3949. temp_dia[key] = type_item
  3950. if key == 'tool_type':
  3951. temp_dia[key] = tool_type_item
  3952. if key == 'offset_value':
  3953. temp_dia[key] = offset_value_item
  3954. if key == 'data':
  3955. # update the 'data' section
  3956. for data_key in tooluid_value[key].keys():
  3957. for form_key, form_value in self.form_fields.items():
  3958. if form_key == data_key:
  3959. temp_data[data_key] = form_value.get_value()
  3960. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3961. # updated from self.app.defaults
  3962. if data_key not in self.form_fields:
  3963. temp_data[data_key] = value[data_key]
  3964. temp_dia[key] = deepcopy(temp_data)
  3965. temp_data.clear()
  3966. if key == 'solid_geometry':
  3967. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3968. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3969. else:
  3970. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3971. self.tools.clear()
  3972. self.tools = deepcopy(temp_tools)
  3973. temp_tools.clear()
  3974. self.ui_connect()
  3975. def select_tools_table_row(self, row, clearsel=None):
  3976. if clearsel:
  3977. self.ui.geo_tools_table.clearSelection()
  3978. if self.ui.geo_tools_table.rowCount() > 0:
  3979. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3980. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3981. def export_dxf(self):
  3982. units = self.app.defaults['units'].upper()
  3983. dwg = None
  3984. try:
  3985. dwg = ezdxf.new('R2010')
  3986. msp = dwg.modelspace()
  3987. def g2dxf(dxf_space, geo):
  3988. if isinstance(geo, MultiPolygon):
  3989. for poly in geo:
  3990. ext_points = list(poly.exterior.coords)
  3991. dxf_space.add_lwpolyline(ext_points)
  3992. for interior in poly.interiors:
  3993. dxf_space.add_lwpolyline(list(interior.coords))
  3994. if isinstance(geo, Polygon):
  3995. ext_points = list(geo.exterior.coords)
  3996. dxf_space.add_lwpolyline(ext_points)
  3997. for interior in geo.interiors:
  3998. dxf_space.add_lwpolyline(list(interior.coords))
  3999. if isinstance(geo, MultiLineString):
  4000. for line in geo:
  4001. dxf_space.add_lwpolyline(list(line.coords))
  4002. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  4003. dxf_space.add_lwpolyline(list(geo.coords))
  4004. multigeo_solid_geometry = []
  4005. if self.multigeo:
  4006. for tool in self.tools:
  4007. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  4008. else:
  4009. multigeo_solid_geometry = self.solid_geometry
  4010. for geo in multigeo_solid_geometry:
  4011. if type(geo) == list:
  4012. for g in geo:
  4013. g2dxf(msp, g)
  4014. else:
  4015. g2dxf(msp, geo)
  4016. # points = FlatCAMGeometry.get_pts(geo)
  4017. # msp.add_lwpolyline(points)
  4018. except Exception as e:
  4019. log.debug(str(e))
  4020. return dwg
  4021. def get_selected_tools_table_items(self):
  4022. """
  4023. Returns a list of lists, each list in the list is made out of row elements
  4024. :return: List of table_tools items.
  4025. :rtype: list
  4026. """
  4027. table_tools_items = []
  4028. if self.multigeo:
  4029. for x in self.ui.geo_tools_table.selectedItems():
  4030. elem = list()
  4031. txt = ''
  4032. for column in range(0, self.ui.geo_tools_table.columnCount()):
  4033. try:
  4034. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4035. except AttributeError:
  4036. try:
  4037. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4038. except AttributeError:
  4039. pass
  4040. elem.append(txt)
  4041. table_tools_items.append(deepcopy(elem))
  4042. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  4043. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  4044. else:
  4045. for x in self.ui.geo_tools_table.selectedItems():
  4046. r = []
  4047. txt = ''
  4048. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  4049. # so we don't read them
  4050. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  4051. # the columns have items that have text but also have items that are widgets
  4052. # for which the text they hold has to be read differently
  4053. try:
  4054. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4055. except AttributeError:
  4056. try:
  4057. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4058. except AttributeError:
  4059. pass
  4060. r.append(txt)
  4061. table_tools_items.append(r)
  4062. for item in table_tools_items:
  4063. item[0] = str(item[0])
  4064. return table_tools_items
  4065. def on_pp_changed(self):
  4066. current_pp = self.ui.pp_geometry_name_cb.get_value()
  4067. if current_pp == 'hpgl':
  4068. self.old_pp_state = self.ui.mpass_cb.get_value()
  4069. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  4070. self.ui.mpass_cb.set_value(False)
  4071. self.ui.mpass_cb.setDisabled(True)
  4072. self.ui.toolchangeg_cb.set_value(True)
  4073. self.ui.toolchangeg_cb.setDisabled(True)
  4074. else:
  4075. self.ui.mpass_cb.set_value(self.old_pp_state)
  4076. self.ui.mpass_cb.setDisabled(False)
  4077. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  4078. self.ui.toolchangeg_cb.setDisabled(False)
  4079. if "toolchange_probe" in current_pp.lower():
  4080. self.ui.pdepth_entry.setVisible(True)
  4081. self.ui.pdepth_label.show()
  4082. self.ui.feedrate_probe_entry.setVisible(True)
  4083. self.ui.feedrate_probe_label.show()
  4084. else:
  4085. self.ui.pdepth_entry.setVisible(False)
  4086. self.ui.pdepth_label.hide()
  4087. self.ui.feedrate_probe_entry.setVisible(False)
  4088. self.ui.feedrate_probe_label.hide()
  4089. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  4090. self.ui.fr_rapidlabel.show()
  4091. self.ui.cncfeedrate_rapid_entry.show()
  4092. else:
  4093. self.ui.fr_rapidlabel.hide()
  4094. self.ui.cncfeedrate_rapid_entry.hide()
  4095. def on_generatecnc_button_click(self, *args):
  4096. log.debug("Generating CNCJob from Geometry ...")
  4097. self.app.report_usage("geometry_on_generatecnc_button")
  4098. # this reads the values in the UI form to the self.options dictionary
  4099. self.read_form()
  4100. self.sel_tools = {}
  4101. try:
  4102. if self.special_group:
  4103. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  4104. (_("This Geometry can't be processed because it is"),
  4105. str(self.special_group),
  4106. _("geometry")
  4107. )
  4108. )
  4109. return
  4110. except AttributeError:
  4111. pass
  4112. # test to see if we have tools available in the tool table
  4113. if self.ui.geo_tools_table.selectedItems():
  4114. for x in self.ui.geo_tools_table.selectedItems():
  4115. # try:
  4116. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  4117. # except ValueError:
  4118. # # try to convert comma to decimal point. if it's still not working error message and return
  4119. # try:
  4120. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  4121. # except ValueError:
  4122. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  4123. # _("Wrong value format entered, use a number."))
  4124. # return
  4125. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  4126. for tooluid_key, tooluid_value in self.tools.items():
  4127. if int(tooluid_key) == tooluid:
  4128. self.sel_tools.update({
  4129. tooluid: deepcopy(tooluid_value)
  4130. })
  4131. self.mtool_gen_cncjob()
  4132. self.ui.geo_tools_table.clearSelection()
  4133. elif self.ui.geo_tools_table.rowCount() == 1:
  4134. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  4135. for tooluid_key, tooluid_value in self.tools.items():
  4136. if int(tooluid_key) == tooluid:
  4137. self.sel_tools.update({
  4138. tooluid: deepcopy(tooluid_value)
  4139. })
  4140. self.mtool_gen_cncjob()
  4141. self.ui.geo_tools_table.clearSelection()
  4142. else:
  4143. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4144. _("Failed. No tool selected in the tool table ..."))
  4145. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  4146. plot=True, use_thread=True):
  4147. """
  4148. Creates a multi-tool CNCJob out of this Geometry object.
  4149. The actual work is done by the target FlatCAMCNCjob object's
  4150. `generate_from_geometry_2()` method.
  4151. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  4152. (including the solid_geometry)
  4153. :param tools_in_use: the tools that are used, needed by some preprocessors
  4154. :type list of lists, each list in the list is made out of row elements of tools table from GUI
  4155. :param segx: number of segments on the X axis, for auto-levelling
  4156. :param segy: number of segments on the Y axis, for auto-levelling
  4157. :param plot: if True the generated object will be plotted; if False will not be plotted
  4158. :param use_thread: if True use threading
  4159. :return: None
  4160. """
  4161. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  4162. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  4163. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  4164. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  4165. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4166. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4167. try:
  4168. xmin = self.options['xmin']
  4169. ymin = self.options['ymin']
  4170. xmax = self.options['xmax']
  4171. ymax = self.options['ymax']
  4172. except Exception as e:
  4173. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  4174. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  4175. msg += '%s %s' % ('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() -->', str(e))
  4176. msg += traceback.format_exc()
  4177. self.app.inform.emit(msg)
  4178. return
  4179. # Object initialization function for app.new_object()
  4180. # RUNNING ON SEPARATE THREAD!
  4181. def job_init_single_geometry(job_obj, app_obj):
  4182. log.debug("Creating a CNCJob out of a single-geometry")
  4183. assert isinstance(job_obj, FlatCAMCNCjob), \
  4184. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4185. job_obj.options['xmin'] = xmin
  4186. job_obj.options['ymin'] = ymin
  4187. job_obj.options['xmax'] = xmax
  4188. job_obj.options['ymax'] = ymax
  4189. # count the tools
  4190. tool_cnt = 0
  4191. dia_cnc_dict = dict()
  4192. # this turn on the FlatCAMCNCJob plot for multiple tools
  4193. job_obj.multitool = True
  4194. job_obj.multigeo = False
  4195. job_obj.cnc_tools.clear()
  4196. job_obj.options['Tools_in_use'] = tools_in_use
  4197. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4198. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4199. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4200. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4201. for tooluid_key in list(tools_dict.keys()):
  4202. tool_cnt += 1
  4203. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4204. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4205. dia_cnc_dict.update({
  4206. 'tooldia': tooldia_val
  4207. })
  4208. if dia_cnc_dict['offset'] == 'in':
  4209. tool_offset = -dia_cnc_dict['tooldia'] / 2
  4210. elif dia_cnc_dict['offset'].lower() == 'out':
  4211. tool_offset = dia_cnc_dict['tooldia'] / 2
  4212. elif dia_cnc_dict['offset'].lower() == 'custom':
  4213. try:
  4214. offset_value = float(self.ui.tool_offset_entry.get_value())
  4215. except ValueError:
  4216. # try to convert comma to decimal point. if it's still not working error message and return
  4217. try:
  4218. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4219. except ValueError:
  4220. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4221. _("Wrong value format entered, use a number."))
  4222. return
  4223. if offset_value:
  4224. tool_offset = float(offset_value)
  4225. else:
  4226. self.app.inform.emit('[WARNING] %s' % _("Tool Offset is selected in Tool Table but "
  4227. "no value is provided.\n"
  4228. "Add a Tool Offset or change the Offset Type."))
  4229. return
  4230. else:
  4231. tool_offset = 0.0
  4232. dia_cnc_dict.update({
  4233. 'offset_value': tool_offset
  4234. })
  4235. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4236. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4237. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4238. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4239. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4240. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4241. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4242. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4243. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4244. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4245. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4246. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4247. startz = tools_dict[tooluid_key]['data']["startz"]
  4248. endz = tools_dict[tooluid_key]['data']["endz"]
  4249. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4250. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4251. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4252. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4253. spindledir = self.app.defaults['geometry_spindledir']
  4254. tool_solid_geometry = self.solid_geometry
  4255. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4256. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4257. # Propagate options
  4258. job_obj.options["tooldia"] = tooldia_val
  4259. job_obj.options['type'] = 'Geometry'
  4260. job_obj.options['tool_dia'] = tooldia_val
  4261. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4262. # to a value of 0.0005 which is 20 times less than 0.01
  4263. tol = float(self.app.defaults['global_tolerance']) / 20
  4264. res = job_obj.generate_from_geometry_2(
  4265. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  4266. z_cut=z_cut, z_move=z_move,
  4267. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4268. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4269. multidepth=multidepth, depthpercut=depthpercut,
  4270. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4271. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4272. pp_geometry_name=pp_geometry_name,
  4273. tool_no=tool_cnt)
  4274. if res == 'fail':
  4275. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4276. return 'fail'
  4277. else:
  4278. dia_cnc_dict['gcode'] = res
  4279. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4280. # object is the source of gcode
  4281. job_obj.toolchange_xy_type = "geometry"
  4282. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4283. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4284. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4285. # TODO this serve for bounding box creation only; should be optimized
  4286. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4287. # for bounding box values
  4288. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  4289. try:
  4290. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  4291. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  4292. except Exception as e:
  4293. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4294. job_obj.cnc_tools.update({
  4295. tooluid_key: deepcopy(dia_cnc_dict)
  4296. })
  4297. dia_cnc_dict.clear()
  4298. # Object initialization function for app.new_object()
  4299. # RUNNING ON SEPARATE THREAD!
  4300. def job_init_multi_geometry(job_obj, app_obj):
  4301. log.debug("Creating a CNCJob out of a multi-geometry")
  4302. assert isinstance(job_obj, FlatCAMCNCjob), \
  4303. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4304. current_uid = int(1)
  4305. job_obj.options['xmin'] = xmin
  4306. job_obj.options['ymin'] = ymin
  4307. job_obj.options['xmax'] = xmax
  4308. job_obj.options['ymax'] = ymax
  4309. # count the tools
  4310. tool_cnt = 0
  4311. dia_cnc_dict = dict()
  4312. # this turn on the FlatCAMCNCJob plot for multiple tools
  4313. job_obj.multitool = True
  4314. job_obj.multigeo = True
  4315. job_obj.cnc_tools.clear()
  4316. job_obj.options['Tools_in_use'] = tools_in_use
  4317. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4318. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4319. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4320. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4321. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  4322. if not self.solid_geometry:
  4323. a = 0
  4324. for tooluid_key in self.tools:
  4325. if self.tools[tooluid_key]['solid_geometry'] is None:
  4326. a += 1
  4327. if a == len(self.tools):
  4328. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  4329. _('Cancelled. Empty file, it has no geometry'))
  4330. return 'fail'
  4331. for tooluid_key in list(tools_dict.keys()):
  4332. tool_cnt += 1
  4333. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4334. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4335. dia_cnc_dict.update({
  4336. 'tooldia': tooldia_val
  4337. })
  4338. # find the tool_dia associated with the tooluid_key
  4339. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  4340. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  4341. for k, v in self.tools.items():
  4342. if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  4343. current_uid = int(k)
  4344. break
  4345. if dia_cnc_dict['offset'] == 'in':
  4346. tool_offset = -tooldia_val / 2
  4347. elif dia_cnc_dict['offset'].lower() == 'out':
  4348. tool_offset = tooldia_val / 2
  4349. elif dia_cnc_dict['offset'].lower() == 'custom':
  4350. offset_value = float(self.ui.tool_offset_entry.get_value())
  4351. if offset_value:
  4352. tool_offset = float(offset_value)
  4353. else:
  4354. self.app.inform.emit('[WARNING] %s' %
  4355. _("Tool Offset is selected in Tool Table but "
  4356. "no value is provided.\n"
  4357. "Add a Tool Offset or change the Offset Type."))
  4358. return
  4359. else:
  4360. tool_offset = 0.0
  4361. dia_cnc_dict.update({
  4362. 'offset_value': tool_offset
  4363. })
  4364. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4365. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4366. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4367. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4368. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4369. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4370. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4371. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4372. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4373. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4374. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4375. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4376. startz = tools_dict[tooluid_key]['data']["startz"]
  4377. endz = tools_dict[tooluid_key]['data']["endz"]
  4378. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4379. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4380. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4381. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4382. spindledir = self.app.defaults['geometry_spindledir']
  4383. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  4384. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4385. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4386. # Propagate options
  4387. job_obj.options["tooldia"] = tooldia_val
  4388. job_obj.options['type'] = 'Geometry'
  4389. job_obj.options['tool_dia'] = tooldia_val
  4390. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4391. # to a value of 0.0005 which is 20 times less than 0.01
  4392. tol = float(self.app.defaults['global_tolerance']) / 20
  4393. res = job_obj.generate_from_multitool_geometry(
  4394. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  4395. tolerance=tol, z_cut=z_cut, z_move=z_move,
  4396. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4397. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4398. multidepth=multidepth, depthpercut=depthpercut,
  4399. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4400. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4401. pp_geometry_name=pp_geometry_name,
  4402. tool_no=tool_cnt)
  4403. if res == 'fail':
  4404. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4405. return 'fail'
  4406. else:
  4407. dia_cnc_dict['gcode'] = res
  4408. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4409. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4410. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4411. # TODO this serve for bounding box creation only; should be optimized
  4412. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4413. # for bounding box values
  4414. # geo_for_bound_values = cascaded_union([
  4415. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  4416. # ])
  4417. try:
  4418. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  4419. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4420. except Exception as e:
  4421. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4422. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4423. # object is the source of gcode
  4424. job_obj.toolchange_xy_type = "geometry"
  4425. job_obj.cnc_tools.update({
  4426. tooluid_key: deepcopy(dia_cnc_dict)
  4427. })
  4428. dia_cnc_dict.clear()
  4429. if use_thread:
  4430. # To be run in separate thread
  4431. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  4432. # separate solid_geometry in the self.tools dictionary
  4433. def job_thread(app_obj):
  4434. if self.solid_geometry:
  4435. with self.app.proc_container.new(_("Generating CNC Code")):
  4436. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  4437. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4438. else:
  4439. with self.app.proc_container.new(_("Generating CNC Code")):
  4440. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  4441. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4442. # Create a promise with the name
  4443. self.app.collection.promise(outname)
  4444. # Send to worker
  4445. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4446. else:
  4447. if self.solid_geometry:
  4448. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  4449. else:
  4450. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  4451. def generatecncjob(
  4452. self, outname=None,
  4453. dia=None, offset=None,
  4454. z_cut=None, z_move=None,
  4455. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  4456. spindlespeed=None, dwell=None, dwelltime=None,
  4457. multidepth=None, depthperpass=None,
  4458. toolchange=None, toolchangez=None, toolchangexy=None,
  4459. extracut=None, extracut_length=None, startz=None, endz=None,
  4460. pp=None,
  4461. segx=None, segy=None,
  4462. use_thread=True,
  4463. plot=True):
  4464. """
  4465. Only used for TCL Command.
  4466. Creates a CNCJob out of this Geometry object. The actual
  4467. work is done by the target camlib.CNCjob
  4468. `generate_from_geometry_2()` method.
  4469. :param z_cut: Cut depth (negative)
  4470. :param z_move: Hight of the tool when travelling (not cutting)
  4471. :param feedrate: Feed rate while cutting on X - Y plane
  4472. :param feedrate_z: Feed rate while cutting on Z plane
  4473. :param feedrate_rapid: Feed rate while moving with rapids
  4474. :param dia: Tool diameter
  4475. :param outname: Name of the new object
  4476. :param spindlespeed: Spindle speed (RPM)
  4477. :param pp Name of the preprocessor
  4478. :return: None
  4479. """
  4480. tooldia = dia if dia else float(self.options["cnctooldia"])
  4481. outname = outname if outname is not None else self.options["name"]
  4482. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4483. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4484. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4485. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4486. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4487. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4488. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4489. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4490. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4491. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4492. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  4493. startz = startz if startz is not None else self.options["startz"]
  4494. endz = endz if endz is not None else float(self.options["endz"])
  4495. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4496. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4497. toolchange = toolchange if toolchange else self.options["toolchange"]
  4498. offset = offset if offset else 0.0
  4499. # int or None.
  4500. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4501. dwell = dwell if dwell else self.options["dwell"]
  4502. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4503. ppname_g = pp if pp else self.options["ppname_g"]
  4504. # Object initialization function for app.new_object()
  4505. # RUNNING ON SEPARATE THREAD!
  4506. def job_init(job_obj, app_obj):
  4507. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4508. # Propagate options
  4509. job_obj.options["tooldia"] = tooldia
  4510. app_obj.progress.emit(20)
  4511. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4512. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4513. app_obj.progress.emit(40)
  4514. job_obj.options['type'] = 'Geometry'
  4515. job_obj.options['tool_dia'] = tooldia
  4516. job_obj.segx = segx
  4517. job_obj.segy = segy
  4518. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4519. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4520. job_obj.options['xmin'] = self.options['xmin']
  4521. job_obj.options['ymin'] = self.options['ymin']
  4522. job_obj.options['xmax'] = self.options['xmax']
  4523. job_obj.options['ymax'] = self.options['ymax']
  4524. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4525. # to a value of 0.0005 which is 20 times less than 0.01
  4526. tol = float(self.app.defaults['global_tolerance']) / 20
  4527. job_obj.generate_from_geometry_2(
  4528. self, tooldia=tooldia, offset=offset, tolerance=tol,
  4529. z_cut=z_cut, z_move=z_move,
  4530. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4531. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4532. multidepth=multidepth, depthpercut=depthperpass,
  4533. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4534. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4535. pp_geometry_name=ppname_g
  4536. )
  4537. app_obj.progress.emit(50)
  4538. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4539. # source of gcode
  4540. job_obj.toolchange_xy_type = "geometry"
  4541. job_obj.gcode_parse()
  4542. self.app.inform.emit('[success] %s' %
  4543. _("Finished G-Code processing..."))
  4544. app_obj.progress.emit(80)
  4545. if use_thread:
  4546. # To be run in separate thread
  4547. def job_thread(app_obj):
  4548. with self.app.proc_container.new(_("Generating CNC Code")):
  4549. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  4550. app_obj.inform.emit('[success] %s: %s' %
  4551. (_("CNCjob created")), outname)
  4552. app_obj.progress.emit(100)
  4553. # Create a promise with the name
  4554. self.app.collection.promise(outname)
  4555. # Send to worker
  4556. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4557. else:
  4558. self.app.new_object("cncjob", outname, job_init, plot=plot)
  4559. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4560. # if self.muted_ui:
  4561. # return
  4562. # self.read_form_item('plot')
  4563. def scale(self, xfactor, yfactor=None, point=None):
  4564. """
  4565. Scales all geometry by a given factor.
  4566. :param xfactor: Factor by which to scale the object's geometry/
  4567. :type xfactor: float
  4568. :param yfactor: Factor by which to scale the object's geometry/
  4569. :type yfactor: float
  4570. :return: None
  4571. :rtype: None
  4572. """
  4573. log.debug("FlatCAMObj.FlatCAMGeometry.scale()")
  4574. try:
  4575. xfactor = float(xfactor)
  4576. except Exception:
  4577. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4578. return
  4579. if yfactor is None:
  4580. yfactor = xfactor
  4581. else:
  4582. try:
  4583. yfactor = float(yfactor)
  4584. except Exception:
  4585. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4586. return
  4587. if xfactor == 1 and yfactor == 1:
  4588. return
  4589. if point is None:
  4590. px = 0
  4591. py = 0
  4592. else:
  4593. px, py = point
  4594. self.geo_len = 0
  4595. self.old_disp_number = 0
  4596. self.el_count = 0
  4597. def scale_recursion(geom):
  4598. if type(geom) is list:
  4599. geoms = list()
  4600. for local_geom in geom:
  4601. geoms.append(scale_recursion(local_geom))
  4602. return geoms
  4603. else:
  4604. try:
  4605. self.el_count += 1
  4606. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4607. if self.old_disp_number < disp_number <= 100:
  4608. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4609. self.old_disp_number = disp_number
  4610. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4611. except AttributeError:
  4612. return geom
  4613. if self.multigeo is True:
  4614. for tool in self.tools:
  4615. # variables to display the percentage of work done
  4616. self.geo_len = 0
  4617. try:
  4618. for g in self.tools[tool]['solid_geometry']:
  4619. self.geo_len += 1
  4620. except TypeError:
  4621. self.geo_len = 1
  4622. self.old_disp_number = 0
  4623. self.el_count = 0
  4624. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4625. try:
  4626. # variables to display the percentage of work done
  4627. self.geo_len = 0
  4628. try:
  4629. self.geo_len = len(self.solid_geometry)
  4630. except TypeError:
  4631. self.geo_len = 1
  4632. self.old_disp_number = 0
  4633. self.el_count = 0
  4634. self.solid_geometry = scale_recursion(self.solid_geometry)
  4635. except AttributeError:
  4636. self.solid_geometry = []
  4637. return
  4638. self.app.proc_container.new_text = ''
  4639. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  4640. def offset(self, vect):
  4641. """
  4642. Offsets all geometry by a given vector/
  4643. :param vect: (x, y) vector by which to offset the object's geometry.
  4644. :type vect: tuple
  4645. :return: None
  4646. :rtype: None
  4647. """
  4648. log.debug("FlatCAMObj.FlatCAMGeometry.offset()")
  4649. try:
  4650. dx, dy = vect
  4651. except TypeError:
  4652. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4653. _("An (x,y) pair of values are needed. "
  4654. "Probable you entered only one value in the Offset field.")
  4655. )
  4656. return
  4657. if dx == 0 and dy == 0:
  4658. return
  4659. self.geo_len = 0
  4660. self.old_disp_number = 0
  4661. self.el_count = 0
  4662. def translate_recursion(geom):
  4663. if type(geom) is list:
  4664. geoms = list()
  4665. for local_geom in geom:
  4666. geoms.append(translate_recursion(local_geom))
  4667. return geoms
  4668. else:
  4669. try:
  4670. self.el_count += 1
  4671. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4672. if self.old_disp_number < disp_number <= 100:
  4673. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4674. self.old_disp_number = disp_number
  4675. return affinity.translate(geom, xoff=dx, yoff=dy)
  4676. except AttributeError:
  4677. return geom
  4678. if self.multigeo is True:
  4679. for tool in self.tools:
  4680. # variables to display the percentage of work done
  4681. self.geo_len = 0
  4682. try:
  4683. for g in self.tools[tool]['solid_geometry']:
  4684. self.geo_len += 1
  4685. except TypeError:
  4686. self.geo_len = 1
  4687. self.old_disp_number = 0
  4688. self.el_count = 0
  4689. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  4690. # variables to display the percentage of work done
  4691. self.geo_len = 0
  4692. try:
  4693. for g in self.solid_geometry:
  4694. self.geo_len += 1
  4695. except TypeError:
  4696. self.geo_len = 1
  4697. self.old_disp_number = 0
  4698. self.el_count = 0
  4699. self.solid_geometry = translate_recursion(self.solid_geometry)
  4700. self.app.proc_container.new_text = ''
  4701. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  4702. def convert_units(self, units):
  4703. log.debug("FlatCAMObj.FlatCAMGeometry.convert_units()")
  4704. self.ui_disconnect()
  4705. factor = Geometry.convert_units(self, units)
  4706. self.options['cutz'] = float(self.options['cutz']) * factor
  4707. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  4708. self.options['travelz'] = float(self.options['travelz']) * factor
  4709. self.options['feedrate'] = float(self.options['feedrate']) * factor
  4710. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  4711. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  4712. self.options['endz'] = float(self.options['endz']) * factor
  4713. # self.options['cnctooldia'] *= factor
  4714. # self.options['painttooldia'] *= factor
  4715. # self.options['paintmargin'] *= factor
  4716. # self.options['paintoverlap'] *= factor
  4717. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  4718. if self.app.defaults["geometry_toolchangexy"] == '':
  4719. self.options['toolchangexy'] = "0.0, 0.0"
  4720. else:
  4721. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  4722. if len(coords_xy) < 2:
  4723. self.app.inform.emit('[ERROR] %s' %
  4724. _("The Toolchange X,Y field in Edit -> Preferences "
  4725. "has to be in the format (x, y)\n"
  4726. "but now there is only one value, not two.")
  4727. )
  4728. return 'fail'
  4729. coords_xy[0] *= factor
  4730. coords_xy[1] *= factor
  4731. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4732. if self.options['startz'] is not None:
  4733. self.options['startz'] = float(self.options['startz']) * factor
  4734. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4735. 'endz', 'toolchangez']
  4736. if isinstance(self, FlatCAMGeometry):
  4737. temp_tools_dict = {}
  4738. tool_dia_copy = {}
  4739. data_copy = {}
  4740. for tooluid_key, tooluid_value in self.tools.items():
  4741. for dia_key, dia_value in tooluid_value.items():
  4742. if dia_key == 'tooldia':
  4743. dia_value *= factor
  4744. dia_value = float('%.*f' % (self.decimals, dia_value))
  4745. tool_dia_copy[dia_key] = dia_value
  4746. if dia_key == 'offset':
  4747. tool_dia_copy[dia_key] = dia_value
  4748. if dia_key == 'offset_value':
  4749. dia_value *= factor
  4750. tool_dia_copy[dia_key] = dia_value
  4751. # convert the value in the Custom Tool Offset entry in UI
  4752. custom_offset = None
  4753. try:
  4754. custom_offset = float(self.ui.tool_offset_entry.get_value())
  4755. except ValueError:
  4756. # try to convert comma to decimal point. if it's still not working error message and return
  4757. try:
  4758. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4759. except ValueError:
  4760. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4761. _("Wrong value format entered, use a number."))
  4762. return
  4763. except TypeError:
  4764. pass
  4765. if custom_offset:
  4766. custom_offset *= factor
  4767. self.ui.tool_offset_entry.set_value(custom_offset)
  4768. if dia_key == 'type':
  4769. tool_dia_copy[dia_key] = dia_value
  4770. if dia_key == 'tool_type':
  4771. tool_dia_copy[dia_key] = dia_value
  4772. if dia_key == 'data':
  4773. for data_key, data_value in dia_value.items():
  4774. # convert the form fields that are convertible
  4775. for param in param_list:
  4776. if data_key == param and data_value is not None:
  4777. data_copy[data_key] = data_value * factor
  4778. # copy the other dict entries that are not convertible
  4779. if data_key not in param_list:
  4780. data_copy[data_key] = data_value
  4781. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4782. data_copy.clear()
  4783. temp_tools_dict.update({
  4784. tooluid_key: deepcopy(tool_dia_copy)
  4785. })
  4786. tool_dia_copy.clear()
  4787. self.tools.clear()
  4788. self.tools = deepcopy(temp_tools_dict)
  4789. # if there is a value in the new tool field then convert that one too
  4790. tooldia = self.ui.addtool_entry.get_value()
  4791. if tooldia:
  4792. tooldia *= factor
  4793. tooldia = float('%.*f' % (self.decimals, tooldia))
  4794. self.ui.addtool_entry.set_value(tooldia)
  4795. return factor
  4796. def plot_element(self, element, color='#FF0000FF', visible=None):
  4797. visible = visible if visible else self.options['plot']
  4798. try:
  4799. for sub_el in element:
  4800. self.plot_element(sub_el)
  4801. except TypeError: # Element is not iterable...
  4802. # if self.app.is_legacy is False:
  4803. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4804. def plot(self, visible=None, kind=None):
  4805. """
  4806. Plot the object.
  4807. :param visible: Controls if the added shape is visible of not
  4808. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4809. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4810. :return:
  4811. """
  4812. # Does all the required setup and returns False
  4813. # if the 'ptint' option is set to False.
  4814. if not FlatCAMObj.plot(self):
  4815. return
  4816. try:
  4817. # plot solid geometries found as members of self.tools attribute dict
  4818. # for MultiGeo
  4819. if self.multigeo is True: # geo multi tool usage
  4820. for tooluid_key in self.tools:
  4821. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4822. self.plot_element(solid_geometry, visible=visible)
  4823. else:
  4824. # plot solid geometry that may be an direct attribute of the geometry object
  4825. # for SingleGeo
  4826. if self.solid_geometry:
  4827. self.plot_element(self.solid_geometry, visible=visible)
  4828. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4829. self.shapes.redraw()
  4830. except (ObjectDeleted, AttributeError):
  4831. self.shapes.clear(update=True)
  4832. def on_plot_cb_click(self, *args):
  4833. if self.muted_ui:
  4834. return
  4835. self.read_form_item('plot')
  4836. self.plot()
  4837. self.ui_disconnect()
  4838. cb_flag = self.ui.plot_cb.isChecked()
  4839. for row in range(self.ui.geo_tools_table.rowCount()):
  4840. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4841. if cb_flag:
  4842. table_cb.setChecked(True)
  4843. else:
  4844. table_cb.setChecked(False)
  4845. self.ui_connect()
  4846. def on_plot_cb_click_table(self):
  4847. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4848. self.ui_disconnect()
  4849. # cw = self.sender()
  4850. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4851. # cw_row = cw_index.row()
  4852. check_row = 0
  4853. self.shapes.clear(update=True)
  4854. for tooluid_key in self.tools:
  4855. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4856. # find the geo_tool_table row associated with the tooluid_key
  4857. for row in range(self.ui.geo_tools_table.rowCount()):
  4858. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4859. if tooluid_item == int(tooluid_key):
  4860. check_row = row
  4861. break
  4862. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4863. self.plot_element(element=solid_geometry, visible=True)
  4864. self.shapes.redraw()
  4865. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4866. # if all the row plot's are enabled also enable the general plot checkbox
  4867. cb_cnt = 0
  4868. total_row = self.ui.geo_tools_table.rowCount()
  4869. for row in range(total_row):
  4870. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4871. cb_cnt += 1
  4872. else:
  4873. cb_cnt -= 1
  4874. if cb_cnt < total_row:
  4875. self.ui.plot_cb.setChecked(False)
  4876. else:
  4877. self.ui.plot_cb.setChecked(True)
  4878. self.ui_connect()
  4879. def merge(self, geo_list, geo_final, multigeo=None):
  4880. """
  4881. Merges the geometry of objects in grb_list into
  4882. the geometry of geo_final.
  4883. :param geo_list: List of FlatCAMGerber Objects to join.
  4884. :param geo_final: Destination FlatCAMGerber object.
  4885. :param multigeo: if the merged geometry objects are of type MultiGeo
  4886. :return: None
  4887. """
  4888. if geo_final.solid_geometry is None:
  4889. geo_final.solid_geometry = []
  4890. if type(geo_final.solid_geometry) is not list:
  4891. geo_final.solid_geometry = [geo_final.solid_geometry]
  4892. for geo in geo_list:
  4893. for option in geo.options:
  4894. if option is not 'name':
  4895. try:
  4896. geo_final.options[option] = deepcopy(geo.options[option])
  4897. except Exception as e:
  4898. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  4899. # Expand lists
  4900. if type(geo) is list:
  4901. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  4902. # If not list, just append
  4903. else:
  4904. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  4905. if multigeo is None or multigeo is False:
  4906. geo_final.multigeo = False
  4907. try:
  4908. geo_final.solid_geometry.append(deepcopy(geo.solid_geometry))
  4909. except Exception as e:
  4910. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  4911. else:
  4912. geo_final.multigeo = True
  4913. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  4914. # tools object attribute, as a key value
  4915. geo_final.solid_geometry = []
  4916. # find the tool_uid maximum value in the geo_final
  4917. geo_final_uid_list = []
  4918. for key in geo_final.tools:
  4919. geo_final_uid_list.append(int(key))
  4920. try:
  4921. max_uid = max(geo_final_uid_list, key=int)
  4922. except ValueError:
  4923. max_uid = 0
  4924. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  4925. # to merge the obj.tools as it is likely there is none to merge.
  4926. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  4927. for tool_uid in geo.tools:
  4928. max_uid += 1
  4929. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  4930. @staticmethod
  4931. def get_pts(o):
  4932. """
  4933. Returns a list of all points in the object, where
  4934. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  4935. of such. Search is done recursively.
  4936. :param: geometric object
  4937. :return: List of points
  4938. :rtype: list
  4939. """
  4940. pts = []
  4941. # Iterable: descend into each item.
  4942. try:
  4943. for subo in o:
  4944. pts += FlatCAMGeometry.get_pts(subo)
  4945. # Non-iterable
  4946. except TypeError:
  4947. if o is not None:
  4948. if type(o) == MultiPolygon:
  4949. for poly in o:
  4950. pts += FlatCAMGeometry.get_pts(poly)
  4951. # ## Descend into .exerior and .interiors
  4952. elif type(o) == Polygon:
  4953. pts += FlatCAMGeometry.get_pts(o.exterior)
  4954. for i in o.interiors:
  4955. pts += FlatCAMGeometry.get_pts(i)
  4956. elif type(o) == MultiLineString:
  4957. for line in o:
  4958. pts += FlatCAMGeometry.get_pts(line)
  4959. # ## Has .coords: list them.
  4960. else:
  4961. pts += list(o.coords)
  4962. else:
  4963. return
  4964. return pts
  4965. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4966. """
  4967. Represents G-Code.
  4968. """
  4969. optionChanged = QtCore.pyqtSignal(str)
  4970. ui_type = CNCObjectUI
  4971. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4972. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4973. spindlespeed=None):
  4974. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4975. self.decimals = self.app.decimals
  4976. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4977. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4978. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4979. FlatCAMObj.__init__(self, name)
  4980. self.kind = "cncjob"
  4981. self.options.update({
  4982. "plot": True,
  4983. "tooldia": 0.03937, # 0.4mm in inches
  4984. "append": "",
  4985. "prepend": "",
  4986. "dwell": False,
  4987. "dwelltime": 1,
  4988. "type": 'Geometry',
  4989. "toolchange_macro": '',
  4990. "toolchange_macro_enable": False
  4991. })
  4992. '''
  4993. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4994. diameter of the tools and the value is another dict that will hold the data under the following form:
  4995. {tooldia: {
  4996. 'tooluid': 1,
  4997. 'offset': 'Path',
  4998. 'type_item': 'Rough',
  4999. 'tool_type': 'C1',
  5000. 'data': {} # a dict to hold the parameters
  5001. 'gcode': "" # a string with the actual GCODE
  5002. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  5003. (cut or move)
  5004. 'solid_geometry': []
  5005. },
  5006. ...
  5007. }
  5008. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  5009. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5010. '''
  5011. self.cnc_tools = dict()
  5012. '''
  5013. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5014. diameter of the tools and the value is another dict that will hold the data under the following form:
  5015. {tooldia: {
  5016. 'tool': int,
  5017. 'nr_drills': int,
  5018. 'nr_slots': int,
  5019. 'offset': float,
  5020. 'data': {} # a dict to hold the parameters
  5021. 'gcode': "" # a string with the actual GCODE
  5022. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  5023. 'solid_geometry': []
  5024. },
  5025. ...
  5026. }
  5027. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  5028. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  5029. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5030. '''
  5031. self.exc_cnc_tools = dict()
  5032. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  5033. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  5034. self.special_group = None
  5035. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  5036. # (like the one in the TCL Command), False
  5037. self.multitool = False
  5038. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  5039. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  5040. self.g_x_re = re.compile(gcodex_re_string)
  5041. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  5042. self.g_y_re = re.compile(gcodey_re_string)
  5043. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  5044. self.g_z_re = re.compile(gcodez_re_string)
  5045. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  5046. self.g_f_re = re.compile(gcodef_re_string)
  5047. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  5048. self.g_t_re = re.compile(gcodet_re_string)
  5049. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  5050. self.g_nr_re = re.compile(gcodenr_re_string)
  5051. # Attributes to be included in serialization
  5052. # Always append to it because it carries contents
  5053. # from predecessors.
  5054. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  5055. if self.app.is_legacy is False:
  5056. self.text_col = self.app.plotcanvas.new_text_collection()
  5057. self.text_col.enabled = True
  5058. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  5059. self.gcode_editor_tab = None
  5060. self.units_found = self.app.defaults['units']
  5061. def build_ui(self):
  5062. self.ui_disconnect()
  5063. FlatCAMObj.build_ui(self)
  5064. self.units = self.app.defaults['units'].upper()
  5065. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  5066. self.ui.cnc_tools_table.hide()
  5067. if self.cnc_tools:
  5068. self.ui.cnc_tools_table.show()
  5069. self.build_cnc_tools_table()
  5070. self.ui.exc_cnc_tools_table.hide()
  5071. if self.exc_cnc_tools:
  5072. self.ui.exc_cnc_tools_table.show()
  5073. self.build_excellon_cnc_tools()
  5074. #
  5075. self.ui_connect()
  5076. def build_cnc_tools_table(self):
  5077. offset = 0
  5078. tool_idx = 0
  5079. n = len(self.cnc_tools)
  5080. self.ui.cnc_tools_table.setRowCount(n)
  5081. for dia_key, dia_value in self.cnc_tools.items():
  5082. tool_idx += 1
  5083. row_no = tool_idx - 1
  5084. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5085. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  5086. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5087. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  5088. # There are no tool bits in MM with more than 2 decimals diameter.
  5089. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  5090. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  5091. offset_txt = list(str(dia_value['offset']))
  5092. offset_txt[0] = offset_txt[0].upper()
  5093. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  5094. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  5095. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  5096. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5097. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5098. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5099. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5100. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5101. # hack so the checkbox stay centered in the table cell
  5102. # used this:
  5103. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5104. # plot_item = QtWidgets.QWidget()
  5105. # checkbox = FCCheckBox()
  5106. # checkbox.setCheckState(QtCore.Qt.Checked)
  5107. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5108. # qhboxlayout.addWidget(checkbox)
  5109. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5110. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5111. plot_item = FCCheckBox()
  5112. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5113. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  5114. if self.ui.plot_cb.isChecked():
  5115. plot_item.setChecked(True)
  5116. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5117. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  5118. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  5119. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  5120. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5121. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  5122. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5123. # make the diameter column editable
  5124. # for row in range(tool_idx):
  5125. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  5126. # QtCore.Qt.ItemIsEnabled)
  5127. for row in range(tool_idx):
  5128. self.ui.cnc_tools_table.item(row, 0).setFlags(
  5129. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5130. self.ui.cnc_tools_table.resizeColumnsToContents()
  5131. self.ui.cnc_tools_table.resizeRowsToContents()
  5132. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  5133. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  5134. vertical_header.hide()
  5135. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5136. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  5137. horizontal_header.setMinimumSectionSize(10)
  5138. horizontal_header.setDefaultSectionSize(70)
  5139. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5140. horizontal_header.resizeSection(0, 20)
  5141. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5142. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5143. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  5144. horizontal_header.resizeSection(4, 40)
  5145. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5146. horizontal_header.resizeSection(4, 17)
  5147. # horizontal_header.setStretchLastSection(True)
  5148. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5149. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  5150. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  5151. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  5152. # self.ui.geo_tools_table.setSortingEnabled(True)
  5153. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  5154. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  5155. def build_excellon_cnc_tools(self):
  5156. tool_idx = 0
  5157. n = len(self.exc_cnc_tools)
  5158. self.ui.exc_cnc_tools_table.setRowCount(n)
  5159. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  5160. tool_idx += 1
  5161. row_no = tool_idx - 1
  5162. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5163. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  5164. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  5165. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  5166. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset_z']) + self.z_cut))
  5167. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5168. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5169. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5170. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5171. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5172. # hack so the checkbox stay centered in the table cell
  5173. # used this:
  5174. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5175. # plot_item = QtWidgets.QWidget()
  5176. # checkbox = FCCheckBox()
  5177. # checkbox.setCheckState(QtCore.Qt.Checked)
  5178. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5179. # qhboxlayout.addWidget(checkbox)
  5180. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5181. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5182. plot_item = FCCheckBox()
  5183. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5184. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  5185. if self.ui.plot_cb.isChecked():
  5186. plot_item.setChecked(True)
  5187. # TODO until the feature of individual plot for an Excellon tool is implemented
  5188. plot_item.setDisabled(True)
  5189. self.ui.exc_cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5190. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5191. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  5192. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  5193. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5194. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  5195. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  5196. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5197. for row in range(tool_idx):
  5198. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  5199. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5200. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  5201. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  5202. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  5203. vertical_header.hide()
  5204. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5205. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  5206. horizontal_header.setMinimumSectionSize(10)
  5207. horizontal_header.setDefaultSectionSize(70)
  5208. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5209. horizontal_header.resizeSection(0, 20)
  5210. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5211. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  5212. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5213. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  5214. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5215. # horizontal_header.setStretchLastSection(True)
  5216. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5217. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  5218. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  5219. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5220. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5221. def set_ui(self, ui):
  5222. FlatCAMObj.set_ui(self, ui)
  5223. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  5224. assert isinstance(self.ui, CNCObjectUI), \
  5225. "Expected a CNCObjectUI, got %s" % type(self.ui)
  5226. self.units = self.app.defaults['units'].upper()
  5227. self.units_found = self.app.defaults['units']
  5228. # this signal has to be connected to it's slot before the defaults are populated
  5229. # the decision done in the slot has to override the default value set bellow
  5230. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  5231. self.form_fields.update({
  5232. "plot": self.ui.plot_cb,
  5233. "tooldia": self.ui.tooldia_entry,
  5234. "append": self.ui.append_text,
  5235. "prepend": self.ui.prepend_text,
  5236. "toolchange_macro": self.ui.toolchange_text,
  5237. "toolchange_macro_enable": self.ui.toolchange_cb
  5238. })
  5239. # Fill form fields only on object create
  5240. self.to_form()
  5241. # this means that the object that created this CNCJob was an Excellon or Geometry
  5242. try:
  5243. if self.travel_distance:
  5244. self.ui.t_distance_label.show()
  5245. self.ui.t_distance_entry.setVisible(True)
  5246. self.ui.t_distance_entry.setDisabled(True)
  5247. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  5248. self.ui.units_label.setText(str(self.units).lower())
  5249. self.ui.units_label.setDisabled(True)
  5250. self.ui.t_time_label.show()
  5251. self.ui.t_time_entry.setVisible(True)
  5252. self.ui.t_time_entry.setDisabled(True)
  5253. # if time is more than 1 then we have minutes, else we have seconds
  5254. if self.routing_time > 1:
  5255. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  5256. self.ui.units_time_label.setText('min')
  5257. else:
  5258. time_r = self.routing_time * 60
  5259. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  5260. self.ui.units_time_label.setText('sec')
  5261. self.ui.units_time_label.setDisabled(True)
  5262. except AttributeError:
  5263. pass
  5264. if self.multitool is False:
  5265. self.ui.tooldia_entry.show()
  5266. self.ui.updateplot_button.show()
  5267. else:
  5268. self.ui.tooldia_entry.hide()
  5269. self.ui.updateplot_button.hide()
  5270. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  5271. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  5272. try:
  5273. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  5274. except (TypeError, AttributeError):
  5275. pass
  5276. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  5277. # set if to display text annotations
  5278. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  5279. # Show/Hide Advanced Options
  5280. if self.app.defaults["global_app_level"] == 'b':
  5281. self.ui.level.setText(_(
  5282. '<span style="color:green;"><b>Basic</b></span>'
  5283. ))
  5284. self.ui.cnc_frame.hide()
  5285. else:
  5286. self.ui.level.setText(_(
  5287. '<span style="color:red;"><b>Advanced</b></span>'
  5288. ))
  5289. self.ui.cnc_frame.show()
  5290. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  5291. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  5292. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  5293. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  5294. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  5295. def on_cnc_custom_parameters(self, signal_text):
  5296. if signal_text == 'Parameters':
  5297. return
  5298. else:
  5299. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5300. def ui_connect(self):
  5301. for row in range(self.ui.cnc_tools_table.rowCount()):
  5302. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  5303. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  5304. def ui_disconnect(self):
  5305. for row in range(self.ui.cnc_tools_table.rowCount()):
  5306. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  5307. try:
  5308. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  5309. except (TypeError, AttributeError):
  5310. pass
  5311. def on_updateplot_button_click(self, *args):
  5312. """
  5313. Callback for the "Updata Plot" button. Reads the form for updates
  5314. and plots the object.
  5315. """
  5316. self.read_form()
  5317. self.on_plot_kind_change()
  5318. def on_plot_kind_change(self):
  5319. kind = self.ui.cncplot_method_combo.get_value()
  5320. def worker_task():
  5321. with self.app.proc_container.new(_("Plotting...")):
  5322. self.plot(kind=kind)
  5323. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  5324. def on_exportgcode_button_click(self, *args):
  5325. self.app.report_usage("cncjob_on_exportgcode_button")
  5326. self.read_form()
  5327. name = self.app.collection.get_active().options['name']
  5328. save_gcode = False
  5329. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5330. _filter_ = "RML1 Files (*.rol);;All Files (*.*)"
  5331. elif 'hpgl' in self.pp_geometry_name:
  5332. _filter_ = "HPGL Files (*.plt);;All Files (*.*)"
  5333. else:
  5334. save_gcode = True
  5335. _filter_ = self.app.defaults['cncjob_save_filters']
  5336. try:
  5337. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  5338. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5339. caption=_("Export Machine Code ..."),
  5340. directory=dir_file_to_save,
  5341. filter=_filter_
  5342. )
  5343. except TypeError:
  5344. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  5345. filename = str(filename)
  5346. if filename == '':
  5347. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  5348. return
  5349. else:
  5350. if save_gcode is True:
  5351. used_extension = filename.rpartition('.')[2]
  5352. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  5353. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  5354. self.ui.name_entry.set_value(new_name)
  5355. self.on_name_activate(silent=True)
  5356. preamble = str(self.ui.prepend_text.get_value())
  5357. postamble = str(self.ui.append_text.get_value())
  5358. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  5359. if gc == 'fail':
  5360. return
  5361. if self.app.defaults["global_open_style"] is False:
  5362. self.app.file_opened.emit("gcode", filename)
  5363. self.app.file_saved.emit("gcode", filename)
  5364. self.app.inform.emit('[success] %s: %s' %
  5365. (_("Machine Code file saved to"), filename))
  5366. def on_edit_code_click(self, *args):
  5367. self.app.proc_container.view.set_busy(_("Loading..."))
  5368. preamble = str(self.ui.prepend_text.get_value())
  5369. postamble = str(self.ui.append_text.get_value())
  5370. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  5371. if gco == 'fail':
  5372. return
  5373. else:
  5374. self.app.gcode_edited = gco
  5375. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  5376. # add the tab if it was closed
  5377. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  5378. self.gcode_editor_tab.setObjectName('code_editor_tab')
  5379. # delete the absolute and relative position and messages in the infobar
  5380. self.app.ui.position_label.setText("")
  5381. self.app.ui.rel_position_label.setText("")
  5382. # first clear previous text in text editor (if any)
  5383. self.gcode_editor_tab.code_editor.clear()
  5384. self.gcode_editor_tab.code_editor.setReadOnly(False)
  5385. self.gcode_editor_tab.code_editor.completer_enable = False
  5386. self.gcode_editor_tab.buttonRun.hide()
  5387. # Switch plot_area to CNCJob tab
  5388. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  5389. self.gcode_editor_tab.t_frame.hide()
  5390. # then append the text from GCode to the text editor
  5391. try:
  5392. self.gcode_editor_tab.code_editor.setPlainText(self.app.gcode_edited.getvalue())
  5393. # for line in self.app.gcode_edited:
  5394. # QtWidgets.QApplication.processEvents()
  5395. #
  5396. # proc_line = str(line).strip('\n')
  5397. # self.gcode_editor_tab.code_editor.append(proc_line)
  5398. except Exception as e:
  5399. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  5400. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  5401. return
  5402. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5403. self.gcode_editor_tab.handleTextChanged()
  5404. self.gcode_editor_tab.t_frame.show()
  5405. self.app.proc_container.view.set_idle()
  5406. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  5407. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  5408. """
  5409. Will create a header to be added to all GCode files generated by FlatCAM
  5410. :param comment_start_symbol: a symbol to be used as the first symbol in a comment
  5411. :param comment_stop_symbol: a symbol to be used as the last symbol in a comment
  5412. :return: a string with a GCode header
  5413. """
  5414. log.debug("FlatCAMCNCJob.gcode_header()")
  5415. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5416. marlin = False
  5417. hpgl = False
  5418. probe_pp = False
  5419. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  5420. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  5421. try:
  5422. for key in self.cnc_tools:
  5423. ppg = self.cnc_tools[key]['data']['ppname_g']
  5424. if ppg == 'marlin' or ppg == 'Repetier':
  5425. marlin = True
  5426. break
  5427. if ppg == 'hpgl':
  5428. hpgl = True
  5429. break
  5430. if "toolchange_probe" in ppg.lower():
  5431. probe_pp = True
  5432. break
  5433. except KeyError:
  5434. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  5435. pass
  5436. try:
  5437. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  5438. marlin = True
  5439. except KeyError:
  5440. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5441. pass
  5442. try:
  5443. if "toolchange_probe" in self.options['ppname_e'].lower():
  5444. probe_pp = True
  5445. except KeyError:
  5446. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5447. pass
  5448. if marlin is True:
  5449. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5450. (str(self.app.version), str(self.app.version_date)) + '\n'
  5451. gcode += ';Name: ' + str(self.options['name']) + '\n'
  5452. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  5453. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5454. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5455. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  5456. gcode += ';Created on ' + time_str + '\n' + '\n'
  5457. elif hpgl is True:
  5458. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  5459. (str(self.app.version), str(self.app.version_date)) + '";\n'
  5460. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  5461. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  5462. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5463. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5464. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  5465. gcode += 'CO "Created on ' + time_str + '";\n'
  5466. elif probe_pp is True:
  5467. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  5468. (str(self.app.version), str(self.app.version_date)) + '\n'
  5469. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  5470. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  5471. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  5472. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  5473. 'Then zero the Z axis.)\n' + '\n'
  5474. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  5475. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  5476. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5477. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5478. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  5479. gcode += '(Created on ' + time_str + ')\n' + '\n'
  5480. else:
  5481. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  5482. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  5483. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  5484. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  5485. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5486. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5487. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  5488. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  5489. return gcode
  5490. def gcode_footer(self, end_command=None):
  5491. """
  5492. :param end_command: 'M02' or 'M30' - String
  5493. :return:
  5494. """
  5495. if end_command:
  5496. return end_command
  5497. else:
  5498. return 'M02'
  5499. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  5500. """
  5501. This will save the GCode from the Gcode object to a file on the OS filesystem
  5502. :param filename: filename for the GCode file
  5503. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  5504. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  5505. :param to_file: if False then no actual file is saved but the app will know that a file was created
  5506. :return: None
  5507. """
  5508. gcode = ''
  5509. roland = False
  5510. hpgl = False
  5511. try:
  5512. if self.special_group:
  5513. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  5514. (_("This CNCJob object can't be processed because it is a"),
  5515. str(self.special_group),
  5516. _("CNCJob object")))
  5517. return 'fail'
  5518. except AttributeError:
  5519. pass
  5520. # detect if using Roland preprocessor
  5521. try:
  5522. for key in self.cnc_tools:
  5523. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  5524. roland = True
  5525. break
  5526. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  5527. hpgl = True
  5528. break
  5529. except Exception as e:
  5530. try:
  5531. for key in self.cnc_tools:
  5532. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  5533. roland = True
  5534. break
  5535. except Exception as e:
  5536. pass
  5537. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  5538. if roland is False and hpgl is False:
  5539. gcode = self.gcode_header()
  5540. # detect if using multi-tool and make the Gcode summation correctly for each case
  5541. if self.multitool is True:
  5542. for tooluid_key in self.cnc_tools:
  5543. for key, value in self.cnc_tools[tooluid_key].items():
  5544. if key == 'gcode':
  5545. gcode += value
  5546. break
  5547. else:
  5548. gcode += self.gcode
  5549. if roland is True:
  5550. g = preamble + gcode + postamble
  5551. elif hpgl is True:
  5552. g = self.gcode_header() + preamble + gcode + postamble
  5553. else:
  5554. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5555. g_idx = gcode.rfind('G20')
  5556. # if it did not find 'G20' then search for 'G21'
  5557. if g_idx == -1:
  5558. g_idx = gcode.rfind('G21')
  5559. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5560. if g_idx == -1:
  5561. self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5562. return
  5563. footer = self.app.defaults['cncjob_footer']
  5564. end_gcode = self.gcode_footer() if footer is True else ''
  5565. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  5566. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  5567. if self.ui.toolchange_cb.get_value() is True:
  5568. # match = self.re_toolchange.search(g)
  5569. if 'M6' in g:
  5570. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  5571. if m6_code is None or m6_code == '':
  5572. self.app.inform.emit(
  5573. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  5574. )
  5575. return 'fail'
  5576. g = g.replace('M6', m6_code)
  5577. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  5578. lines = StringIO(g)
  5579. # Write
  5580. if filename is not None:
  5581. try:
  5582. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  5583. if force_windows_line_endings and sys.platform != 'win32':
  5584. with open(filename, 'w', newline='\r\n') as f:
  5585. for line in lines:
  5586. f.write(line)
  5587. else:
  5588. with open(filename, 'w') as f:
  5589. for line in lines:
  5590. f.write(line)
  5591. except FileNotFoundError:
  5592. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  5593. return
  5594. except PermissionError:
  5595. self.app.inform.emit(
  5596. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  5597. "Most likely another app is holding the file open and not accessible.")
  5598. )
  5599. return 'fail'
  5600. elif to_file is False:
  5601. # Just for adding it to the recent files list.
  5602. if self.app.defaults["global_open_style"] is False:
  5603. self.app.file_opened.emit("cncjob", filename)
  5604. self.app.file_saved.emit("cncjob", filename)
  5605. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  5606. else:
  5607. return lines
  5608. def on_toolchange_custom_clicked(self, signal):
  5609. try:
  5610. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  5611. if self.ui.toolchange_cb.get_value():
  5612. self.ui.toolchange_cb.set_value(False)
  5613. self.app.inform.emit('[WARNING_NOTCL] %s' %
  5614. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  5615. except KeyError:
  5616. try:
  5617. for key in self.cnc_tools:
  5618. ppg = self.cnc_tools[key]['data']['ppname_g']
  5619. if 'toolchange_custom' not in str(ppg).lower():
  5620. print(ppg)
  5621. if self.ui.toolchange_cb.get_value():
  5622. self.ui.toolchange_cb.set_value(False)
  5623. self.app.inform.emit('[WARNING_NOTCL] %s' %
  5624. _("The used preprocessor file has to have in it's name: "
  5625. "'toolchange_custom'"))
  5626. except KeyError:
  5627. self.app.inform.emit('[ERROR] %s' %
  5628. _("There is no preprocessor file."))
  5629. def get_gcode(self, preamble='', postamble=''):
  5630. # we need this to be able get_gcode separatelly for shell command export_gcode
  5631. return preamble + '\n' + self.gcode + "\n" + postamble
  5632. def get_svg(self):
  5633. # we need this to be able get_svg separately for shell command export_svg
  5634. pass
  5635. def on_plot_cb_click(self, *args):
  5636. if self.muted_ui:
  5637. return
  5638. kind = self.ui.cncplot_method_combo.get_value()
  5639. self.plot(kind=kind)
  5640. self.read_form_item('plot')
  5641. self.ui_disconnect()
  5642. cb_flag = self.ui.plot_cb.isChecked()
  5643. for row in range(self.ui.cnc_tools_table.rowCount()):
  5644. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  5645. if cb_flag:
  5646. table_cb.setChecked(True)
  5647. else:
  5648. table_cb.setChecked(False)
  5649. self.ui_connect()
  5650. def on_plot_cb_click_table(self):
  5651. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  5652. self.ui_disconnect()
  5653. # cw = self.sender()
  5654. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  5655. # cw_row = cw_index.row()
  5656. kind = self.ui.cncplot_method_combo.get_value()
  5657. self.shapes.clear(update=True)
  5658. for tooluid_key in self.cnc_tools:
  5659. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  5660. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  5661. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  5662. for r in range(self.ui.cnc_tools_table.rowCount()):
  5663. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  5664. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  5665. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  5666. self.shapes.redraw()
  5667. # make sure that the general plot is disabled if one of the row plot's are disabled and
  5668. # if all the row plot's are enabled also enable the general plot checkbox
  5669. cb_cnt = 0
  5670. total_row = self.ui.cnc_tools_table.rowCount()
  5671. for row in range(total_row):
  5672. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  5673. cb_cnt += 1
  5674. else:
  5675. cb_cnt -= 1
  5676. if cb_cnt < total_row:
  5677. self.ui.plot_cb.setChecked(False)
  5678. else:
  5679. self.ui.plot_cb.setChecked(True)
  5680. self.ui_connect()
  5681. def plot(self, visible=None, kind='all'):
  5682. # Does all the required setup and returns False
  5683. # if the 'ptint' option is set to False.
  5684. if not FlatCAMObj.plot(self):
  5685. return
  5686. visible = visible if visible else self.options['plot']
  5687. if self.app.is_legacy is False:
  5688. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  5689. self.text_col.enabled = True
  5690. else:
  5691. self.text_col.enabled = False
  5692. self.annotation.redraw()
  5693. try:
  5694. if self.multitool is False: # single tool usage
  5695. try:
  5696. dia_plot = float(self.options["tooldia"])
  5697. except ValueError:
  5698. # we may have a tuple with only one element and a comma
  5699. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  5700. self.plot2(dia_plot, obj=self, visible=visible, kind=kind)
  5701. else:
  5702. # multiple tools usage
  5703. if self.cnc_tools:
  5704. for tooluid_key in self.cnc_tools:
  5705. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  5706. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  5707. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  5708. # TODO: until the gcode parsed will be stored on each Excellon tool this will not get executed
  5709. if self.exc_cnc_tools:
  5710. for tooldia_key in self.exc_cnc_tools:
  5711. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  5712. # gcode_parsed = self.cnc_tools[tooldia_key]['gcode_parsed']
  5713. gcode_parsed = self.gcode_parsed
  5714. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  5715. self.shapes.redraw()
  5716. except (ObjectDeleted, AttributeError):
  5717. self.shapes.clear(update=True)
  5718. if self.app.is_legacy is False:
  5719. self.annotation.clear(update=True)
  5720. def on_annotation_change(self):
  5721. if self.app.is_legacy is False:
  5722. if self.ui.annotation_cb.get_value():
  5723. self.text_col.enabled = True
  5724. else:
  5725. self.text_col.enabled = False
  5726. # kind = self.ui.cncplot_method_combo.get_value()
  5727. # self.plot(kind=kind)
  5728. self.annotation.redraw()
  5729. else:
  5730. kind = self.ui.cncplot_method_combo.get_value()
  5731. self.plot(kind=kind)
  5732. def convert_units(self, units):
  5733. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  5734. factor = CNCjob.convert_units(self, units)
  5735. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  5736. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  5737. 'endz', 'toolchangez']
  5738. temp_tools_dict = {}
  5739. tool_dia_copy = {}
  5740. data_copy = {}
  5741. for tooluid_key, tooluid_value in self.cnc_tools.items():
  5742. for dia_key, dia_value in tooluid_value.items():
  5743. if dia_key == 'tooldia':
  5744. dia_value *= factor
  5745. dia_value = float('%.*f' % (self.decimals, dia_value))
  5746. tool_dia_copy[dia_key] = dia_value
  5747. if dia_key == 'offset':
  5748. tool_dia_copy[dia_key] = dia_value
  5749. if dia_key == 'offset_value':
  5750. dia_value *= factor
  5751. tool_dia_copy[dia_key] = dia_value
  5752. if dia_key == 'type':
  5753. tool_dia_copy[dia_key] = dia_value
  5754. if dia_key == 'tool_type':
  5755. tool_dia_copy[dia_key] = dia_value
  5756. if dia_key == 'data':
  5757. for data_key, data_value in dia_value.items():
  5758. # convert the form fields that are convertible
  5759. for param in param_list:
  5760. if data_key == param and data_value is not None:
  5761. data_copy[data_key] = data_value * factor
  5762. # copy the other dict entries that are not convertible
  5763. if data_key not in param_list:
  5764. data_copy[data_key] = data_value
  5765. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5766. data_copy.clear()
  5767. if dia_key == 'gcode':
  5768. tool_dia_copy[dia_key] = dia_value
  5769. if dia_key == 'gcode_parsed':
  5770. tool_dia_copy[dia_key] = dia_value
  5771. if dia_key == 'solid_geometry':
  5772. tool_dia_copy[dia_key] = dia_value
  5773. # if dia_key == 'solid_geometry':
  5774. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  5775. # if dia_key == 'gcode_parsed':
  5776. # for g in dia_value:
  5777. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  5778. #
  5779. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  5780. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  5781. temp_tools_dict.update({
  5782. tooluid_key: deepcopy(tool_dia_copy)
  5783. })
  5784. tool_dia_copy.clear()
  5785. self.cnc_tools.clear()
  5786. self.cnc_tools = deepcopy(temp_tools_dict)
  5787. class FlatCAMScript(FlatCAMObj):
  5788. """
  5789. Represents a TCL script object.
  5790. """
  5791. optionChanged = QtCore.pyqtSignal(str)
  5792. ui_type = ScriptObjectUI
  5793. def __init__(self, name):
  5794. self.decimals = self.app.decimals
  5795. FlatCAMApp.App.log.debug("Creating a FlatCAMScript object...")
  5796. FlatCAMObj.__init__(self, name)
  5797. self.kind = "script"
  5798. self.options.update({
  5799. "plot": True,
  5800. "type": 'Script',
  5801. "source_file": '',
  5802. })
  5803. self.units = ''
  5804. self.ser_attrs = ['options', 'kind', 'source_file']
  5805. self.source_file = ''
  5806. self.script_code = ''
  5807. self.units_found = self.app.defaults['units']
  5808. # self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  5809. self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  5810. def set_ui(self, ui):
  5811. FlatCAMObj.set_ui(self, ui)
  5812. FlatCAMApp.App.log.debug("FlatCAMScript.set_ui()")
  5813. assert isinstance(self.ui, ScriptObjectUI), \
  5814. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  5815. self.units = self.app.defaults['units'].upper()
  5816. self.units_found = self.app.defaults['units']
  5817. # Fill form fields only on object create
  5818. self.to_form()
  5819. # Show/Hide Advanced Options
  5820. if self.app.defaults["global_app_level"] == 'b':
  5821. self.ui.level.setText(_(
  5822. '<span style="color:green;"><b>Basic</b></span>'
  5823. ))
  5824. else:
  5825. self.ui.level.setText(_(
  5826. '<span style="color:red;"><b>Advanced</b></span>'
  5827. ))
  5828. # tab_here = False
  5829. # # try to not add too many times a tab that it is already installed
  5830. # for idx in range(self.app.ui.plot_tab_area.count()):
  5831. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  5832. # tab_here = True
  5833. # break
  5834. #
  5835. # # add the tab if it is not already added
  5836. # if tab_here is False:
  5837. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  5838. # self.script_editor_tab.setObjectName(self.options['name'])
  5839. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  5840. self.script_editor_tab.setObjectName(self.options['name'])
  5841. # first clear previous text in text editor (if any)
  5842. # self.script_editor_tab.code_editor.clear()
  5843. # self.script_editor_tab.code_editor.setReadOnly(False)
  5844. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  5845. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  5846. self.script_editor_tab.buttonRun.show()
  5847. # Switch plot_area to CNCJob tab
  5848. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  5849. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5850. self.script_editor_tab.buttonOpen.clicked.disconnect()
  5851. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  5852. self.script_editor_tab.buttonSave.clicked.disconnect()
  5853. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  5854. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  5855. self.script_editor_tab.handleTextChanged()
  5856. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  5857. self.ser_attrs = ['options', 'kind', 'source_file']
  5858. # ---------------------------------------------------- #
  5859. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  5860. # ---------------------------------------------------- #
  5861. self.app.proc_container.view.set_busy(_("Loading..."))
  5862. self.script_editor_tab.t_frame.hide()
  5863. try:
  5864. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  5865. # for line in self.source_file.splitlines():
  5866. # QtWidgets.QApplication.processEvents()
  5867. # self.script_editor_tab.code_editor.append(line)
  5868. except Exception as e:
  5869. log.debug("FlatCAMScript.set_ui() --> %s" % str(e))
  5870. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  5871. self.script_editor_tab.t_frame.show()
  5872. self.app.proc_container.view.set_idle()
  5873. self.build_ui()
  5874. def build_ui(self):
  5875. FlatCAMObj.build_ui(self)
  5876. def handle_run_code(self):
  5877. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5878. # tries to print on a hidden widget, therefore show the dock if hidden
  5879. if self.app.ui.shell_dock.isHidden():
  5880. self.app.ui.shell_dock.show()
  5881. self.script_code = deepcopy(self.script_editor_tab.code_editor.toPlainText())
  5882. old_line = ''
  5883. for tcl_command_line in self.script_code.splitlines():
  5884. # do not process lines starting with '#' = comment and empty lines
  5885. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5886. # id FlatCAM is run in Windows then replace all the slashes with
  5887. # the UNIX style slash that TCL understands
  5888. if sys.platform == 'win32':
  5889. if "open" in tcl_command_line:
  5890. tcl_command_line = tcl_command_line.replace('\\', '/')
  5891. if old_line != '':
  5892. new_command = old_line + tcl_command_line + '\n'
  5893. else:
  5894. new_command = tcl_command_line
  5895. # execute the actual Tcl command
  5896. try:
  5897. self.app.shell.open_proccessing() # Disables input box.
  5898. result = self.app.tcl.eval(str(new_command))
  5899. if result != 'None':
  5900. self.app.shell.append_output(result + '\n')
  5901. old_line = ''
  5902. except tk.TclError:
  5903. old_line = old_line + tcl_command_line + '\n'
  5904. except Exception as e:
  5905. log.debug("FlatCAMScript.handleRunCode() --> %s" % str(e))
  5906. if old_line != '':
  5907. # it means that the script finished with an error
  5908. result = self.app.tcl.eval("set errorInfo")
  5909. log.error("Exec command Exception: %s" % (result + '\n'))
  5910. self.app.shell.append_error('ERROR: ' + result + '\n')
  5911. self.app.shell.close_proccessing()
  5912. def on_autocomplete_changed(self, state):
  5913. if state:
  5914. self.script_editor_tab.code_editor.completer_enable = True
  5915. else:
  5916. self.script_editor_tab.code_editor.completer_enable = False
  5917. def to_dict(self):
  5918. """
  5919. Returns a representation of the object as a dictionary.
  5920. Attributes to include are listed in ``self.ser_attrs``.
  5921. :return: A dictionary-encoded copy of the object.
  5922. :rtype: dict
  5923. """
  5924. d = {}
  5925. for attr in self.ser_attrs:
  5926. d[attr] = getattr(self, attr)
  5927. return d
  5928. def from_dict(self, d):
  5929. """
  5930. Sets object's attributes from a dictionary.
  5931. Attributes to include are listed in ``self.ser_attrs``.
  5932. This method will look only for only and all the
  5933. attributes in ``self.ser_attrs``. They must all
  5934. be present. Use only for deserializing saved
  5935. objects.
  5936. :param d: Dictionary of attributes to set in the object.
  5937. :type d: dict
  5938. :return: None
  5939. """
  5940. for attr in self.ser_attrs:
  5941. setattr(self, attr, d[attr])
  5942. class FlatCAMDocument(FlatCAMObj):
  5943. """
  5944. Represents a Document object.
  5945. """
  5946. optionChanged = QtCore.pyqtSignal(str)
  5947. ui_type = DocumentObjectUI
  5948. def __init__(self, name):
  5949. self.decimals = self.app.decimals
  5950. FlatCAMApp.App.log.debug("Creating a Document object...")
  5951. FlatCAMObj.__init__(self, name)
  5952. self.kind = "document"
  5953. self.units = ''
  5954. self.ser_attrs = ['options', 'kind', 'source_file']
  5955. self.source_file = ''
  5956. self.doc_code = ''
  5957. self.font_italic = None
  5958. self.font_bold = None
  5959. self.font_underline =None
  5960. self.document_editor_tab = None
  5961. self._read_only = False
  5962. self.units_found = self.app.defaults['units']
  5963. def set_ui(self, ui):
  5964. FlatCAMObj.set_ui(self, ui)
  5965. FlatCAMApp.App.log.debug("FlatCAMDocument.set_ui()")
  5966. assert isinstance(self.ui, DocumentObjectUI), \
  5967. "Expected a DocumentObjectUI, got %s" % type(self.ui)
  5968. self.units = self.app.defaults['units'].upper()
  5969. self.units_found = self.app.defaults['units']
  5970. # Fill form fields only on object create
  5971. self.to_form()
  5972. # Show/Hide Advanced Options
  5973. if self.app.defaults["global_app_level"] == 'b':
  5974. self.ui.level.setText(_(
  5975. '<span style="color:green;"><b>Basic</b></span>'
  5976. ))
  5977. else:
  5978. self.ui.level.setText(_(
  5979. '<span style="color:red;"><b>Advanced</b></span>'
  5980. ))
  5981. self.document_editor_tab = TextEditor(app=self.app)
  5982. stylesheet = """
  5983. QTextEdit {selection-background-color:%s;
  5984. selection-color:white;
  5985. }
  5986. """ % self.app.defaults["document_sel_color"]
  5987. self.document_editor_tab.code_editor.setStyleSheet(stylesheet)
  5988. # first clear previous text in text editor (if any)
  5989. self.document_editor_tab.code_editor.clear()
  5990. self.document_editor_tab.code_editor.setReadOnly(self._read_only)
  5991. self.document_editor_tab.buttonRun.hide()
  5992. self.ui.autocomplete_cb.set_value(self.app.defaults['document_autocompleter'])
  5993. self.on_autocomplete_changed(state=self.app.defaults['document_autocompleter'])
  5994. self.on_tab_size_change(val=self.app.defaults['document_tab_size'])
  5995. flt = "FlatCAM Docs (*.FlatDoc);;All Files (*.*)"
  5996. # ######################################################################
  5997. # ######################## SIGNALS #####################################
  5998. # ######################################################################
  5999. self.document_editor_tab.buttonOpen.clicked.disconnect()
  6000. self.document_editor_tab.buttonOpen.clicked.connect(lambda: self.document_editor_tab.handleOpen(filt=flt))
  6001. self.document_editor_tab.buttonSave.clicked.disconnect()
  6002. self.document_editor_tab.buttonSave.clicked.connect(lambda: self.document_editor_tab.handleSaveGCode(filt=flt))
  6003. self.document_editor_tab.code_editor.textChanged.connect(self.on_text_changed)
  6004. self.ui.font_type_cb.currentFontChanged.connect(self.font_family)
  6005. self.ui.font_size_cb.activated.connect(self.font_size)
  6006. self.ui.font_bold_tb.clicked.connect(self.on_bold_button)
  6007. self.ui.font_italic_tb.clicked.connect(self.on_italic_button)
  6008. self.ui.font_under_tb.clicked.connect(self.on_underline_button)
  6009. self.ui.font_color_entry.editingFinished.connect(self.on_font_color_entry)
  6010. self.ui.font_color_button.clicked.connect(self.on_font_color_button)
  6011. self.ui.sel_color_entry.editingFinished.connect(self.on_selection_color_entry)
  6012. self.ui.sel_color_button.clicked.connect(self.on_selection_color_button)
  6013. self.ui.al_left_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignLeft))
  6014. self.ui.al_center_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignCenter))
  6015. self.ui.al_right_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignRight))
  6016. self.ui.al_justify_tb.clicked.connect(
  6017. lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignJustify)
  6018. )
  6019. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6020. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6021. # #######################################################################
  6022. self.ui.font_color_entry.set_value(self.app.defaults['document_font_color'])
  6023. self.ui.font_color_button.setStyleSheet(
  6024. "background-color:%s" % str(self.app.defaults['document_font_color']))
  6025. self.ui.sel_color_entry.set_value(self.app.defaults['document_sel_color'])
  6026. self.ui.sel_color_button.setStyleSheet(
  6027. "background-color:%s" % self.app.defaults['document_sel_color'])
  6028. self.ui.font_size_cb.setCurrentIndex(int(self.app.defaults['document_font_size']))
  6029. self.document_editor_tab.handleTextChanged()
  6030. self.ser_attrs = ['options', 'kind', 'source_file']
  6031. if Qt.mightBeRichText(self.source_file):
  6032. self.document_editor_tab.code_editor.setHtml(self.source_file)
  6033. else:
  6034. for line in self.source_file.splitlines():
  6035. self.document_editor_tab.code_editor.append(line)
  6036. self.build_ui()
  6037. @property
  6038. def read_only(self):
  6039. return self._read_only
  6040. @read_only.setter
  6041. def read_only(self, val):
  6042. if val:
  6043. self._read_only = True
  6044. else:
  6045. self._read_only = False
  6046. def build_ui(self):
  6047. FlatCAMObj.build_ui(self)
  6048. tab_here = False
  6049. # try to not add too many times a tab that it is already installed
  6050. for idx in range(self.app.ui.plot_tab_area.count()):
  6051. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6052. tab_here = True
  6053. break
  6054. # add the tab if it is not already added
  6055. if tab_here is False:
  6056. self.app.ui.plot_tab_area.addTab(self.document_editor_tab, '%s' % _("Document Editor"))
  6057. self.document_editor_tab.setObjectName(self.options['name'])
  6058. # Switch plot_area to CNCJob tab
  6059. self.app.ui.plot_tab_area.setCurrentWidget(self.document_editor_tab)
  6060. def on_autocomplete_changed(self, state):
  6061. if state:
  6062. self.document_editor_tab.code_editor.completer_enable = True
  6063. else:
  6064. self.document_editor_tab.code_editor.completer_enable = False
  6065. def on_tab_size_change(self, val=None):
  6066. try:
  6067. self.ui.tab_size_spinner.returnPressed.disconnect(self.on_tab_size_change)
  6068. except TypeError:
  6069. pass
  6070. if val:
  6071. self.ui.tab_size_spinner.set_value(val)
  6072. tab_balue = int(self.ui.tab_size_spinner.get_value())
  6073. self.document_editor_tab.code_editor.setTabStopWidth(tab_balue)
  6074. self.app.defaults['document_tab_size'] = tab_balue
  6075. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6076. def on_text_changed(self):
  6077. self.source_file = self.document_editor_tab.code_editor.toHtml()
  6078. # print(self.source_file)
  6079. def font_family(self, font):
  6080. # self.document_editor_tab.code_editor.selectAll()
  6081. font.setPointSize(float(self.ui.font_size_cb.get_value()))
  6082. self.document_editor_tab.code_editor.setCurrentFont(font)
  6083. self.font_name = self.ui.font_type_cb.currentFont().family()
  6084. def font_size(self):
  6085. # self.document_editor_tab.code_editor.selectAll()
  6086. self.document_editor_tab.code_editor.setFontPointSize(float(self.ui.font_size_cb.get_value()))
  6087. def on_bold_button(self):
  6088. if self.ui.font_bold_tb.isChecked():
  6089. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Bold)
  6090. self.font_bold = True
  6091. else:
  6092. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Normal)
  6093. self.font_bold = False
  6094. def on_italic_button(self):
  6095. if self.ui.font_italic_tb.isChecked():
  6096. self.document_editor_tab.code_editor.setFontItalic(True)
  6097. self.font_italic = True
  6098. else:
  6099. self.document_editor_tab.code_editor.setFontItalic(False)
  6100. self.font_italic = False
  6101. def on_underline_button(self):
  6102. if self.ui.font_under_tb.isChecked():
  6103. self.document_editor_tab.code_editor.setFontUnderline(True)
  6104. self.font_underline = True
  6105. else:
  6106. self.document_editor_tab.code_editor.setFontUnderline(False)
  6107. self.font_underline = False
  6108. # Setting font colors handlers
  6109. def on_font_color_entry(self):
  6110. self.app.defaults['document_font_color'] = self.ui.font_color_entry.get_value()
  6111. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_font_color']))
  6112. def on_font_color_button(self):
  6113. current_color = QtGui.QColor(self.app.defaults['document_font_color'])
  6114. c_dialog = QtWidgets.QColorDialog()
  6115. font_color = c_dialog.getColor(initial=current_color)
  6116. if font_color.isValid() is False:
  6117. return
  6118. self.document_editor_tab.code_editor.setTextColor(font_color)
  6119. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(font_color.name()))
  6120. new_val = str(font_color.name())
  6121. self.ui.font_color_entry.set_value(new_val)
  6122. self.app.defaults['document_font_color'] = new_val
  6123. # Setting selection colors handlers
  6124. def on_selection_color_entry(self):
  6125. self.app.defaults['document_sel_color'] = self.ui.sel_color_entry.get_value()
  6126. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_sel_color']))
  6127. def on_selection_color_button(self):
  6128. current_color = QtGui.QColor(self.app.defaults['document_sel_color'])
  6129. c_dialog = QtWidgets.QColorDialog()
  6130. sel_color = c_dialog.getColor(initial=current_color)
  6131. if sel_color.isValid() is False:
  6132. return
  6133. p = QtGui.QPalette()
  6134. p.setColor(QtGui.QPalette.Highlight, sel_color)
  6135. p.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('white'))
  6136. self.document_editor_tab.code_editor.setPalette(p)
  6137. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(sel_color.name()))
  6138. new_val = str(sel_color.name())
  6139. self.ui.sel_color_entry.set_value(new_val)
  6140. self.app.defaults['document_sel_color'] = new_val
  6141. def to_dict(self):
  6142. """
  6143. Returns a representation of the object as a dictionary.
  6144. Attributes to include are listed in ``self.ser_attrs``.
  6145. :return: A dictionary-encoded copy of the object.
  6146. :rtype: dict
  6147. """
  6148. d = {}
  6149. for attr in self.ser_attrs:
  6150. d[attr] = getattr(self, attr)
  6151. return d
  6152. def from_dict(self, d):
  6153. """
  6154. Sets object's attributes from a dictionary.
  6155. Attributes to include are listed in ``self.ser_attrs``.
  6156. This method will look only for only and all the
  6157. attributes in ``self.ser_attrs``. They must all
  6158. be present. Use only for deserializing saved
  6159. objects.
  6160. :param d: Dictionary of attributes to set in the object.
  6161. :type d: dict
  6162. :return: None
  6163. """
  6164. for attr in self.ser_attrs:
  6165. setattr(self, attr, d[attr])
  6166. # end of file