FlatCAMObj.py 275 KB

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