FlatCAMObj.py 352 KB

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