FlatCAMObj.py 274 KB

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