FlatCAMObj.py 278 KB

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