FlatCAMObj.py 326 KB

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