FlatCAMObj.py 328 KB

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