FlatCAMObj.py 263 KB

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