FlatCAMObj.py 319 KB

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