FlatCAMObj.py 264 KB

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