FlatCAMObj.py 267 KB

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