FlatCAMObj.py 278 KB

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