FlatCAMObj.py 346 KB

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