FlatCAMObj.py 253 KB

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