FlatCAMObj.py 275 KB

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