FlatCAMObj.py 309 KB

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