FlatCAMObj.py 277 KB

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