FlatCAMObj.py 273 KB

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