FlatCAMObj.py 338 KB

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