FlatCAMObj.py 265 KB

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