FlatCAMObj.py 334 KB

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