FlatCAMObj.py 354 KB

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