FlatCAMObj.py 299 KB

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