FlatCAMObj.py 274 KB

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