FlatCAMObj.py 307 KB

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