FlatCAMObj.py 251 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970
  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.optionChanged.emit(key)
  104. def set_ui(self, ui):
  105. self.ui = ui
  106. self.form_fields = {"name": self.ui.name_entry}
  107. assert isinstance(self.ui, ObjectUI)
  108. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  109. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  110. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  111. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  112. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  113. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  114. def build_ui(self):
  115. """
  116. Sets up the UI/form for this object. Show the UI
  117. in the App.
  118. :return: None
  119. :rtype: None
  120. """
  121. self.muted_ui = True
  122. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  123. # Remove anything else in the box
  124. # box_children = self.app.ui.notebook.selected_contents.get_children()
  125. # for child in box_children:
  126. # self.app.ui.notebook.selected_contents.remove(child)
  127. # while self.app.ui.selected_layout.count():
  128. # self.app.ui.selected_layout.takeAt(0)
  129. # Put in the UI
  130. # box_selected.pack_start(sw, True, True, 0)
  131. # self.app.ui.notebook.selected_contents.add(self.ui)
  132. # self.app.ui.selected_layout.addWidget(self.ui)
  133. try:
  134. self.app.ui.selected_scroll_area.takeWidget()
  135. except:
  136. self.app.log.debug("Nothing to remove")
  137. self.app.ui.selected_scroll_area.setWidget(self.ui)
  138. self.muted_ui = False
  139. def on_name_activate(self):
  140. old_name = copy(self.options["name"])
  141. new_name = self.ui.name_entry.get_value()
  142. if new_name != old_name:
  143. # update the SHELL auto-completer model data
  144. try:
  145. self.app.myKeywords.remove(old_name)
  146. self.app.myKeywords.append(new_name)
  147. self.app.shell._edit.set_model_data(self.app.myKeywords)
  148. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  149. except:
  150. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  151. self.options["name"] = self.ui.name_entry.get_value()
  152. self.app.collection.update_view()
  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, threaded=False):
  267. log.debug("FlatCAMObj.visible()")
  268. def worker_task(app_obj):
  269. app_obj.shapes.visible = value
  270. # Not all object types has annotations
  271. try:
  272. app_obj.annotation.visible = value
  273. except Exception as e:
  274. pass
  275. if threaded is False:
  276. worker_task(self)
  277. else:
  278. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  279. @property
  280. def drawing_tolerance(self):
  281. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  282. @drawing_tolerance.setter
  283. def drawing_tolerance(self, value):
  284. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  285. def clear(self, update=False):
  286. self.shapes.clear(update)
  287. # Not all object types has annotations
  288. try:
  289. self.annotation.clear(update)
  290. except AttributeError:
  291. pass
  292. def delete(self):
  293. # Free resources
  294. del self.ui
  295. del self.options
  296. # Set flag
  297. self.deleted = True
  298. class FlatCAMGerber(FlatCAMObj, Gerber):
  299. """
  300. Represents Gerber code.
  301. """
  302. optionChanged = QtCore.pyqtSignal(str)
  303. replotApertures = QtCore.pyqtSignal()
  304. ui_type = GerberObjectUI
  305. def merge(self, 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 = False
  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. def merge(self, exc_list, exc_final):
  1324. """
  1325. Merge Excellon objects found in exc_list parameter into exc_final object.
  1326. Options are always copied from source .
  1327. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1328. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1329. tool_name to be used in the final Excellon object, exc_final.
  1330. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1331. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1332. :param exc_final: Destination FlatCAMExcellon object.
  1333. :return: None
  1334. """
  1335. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1336. flag_order = False
  1337. try:
  1338. flattened_list = list(itertools.chain(*exc_list))
  1339. except TypeError:
  1340. flattened_list = exc_list
  1341. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1342. # values will be list of Shapely Points; for drills
  1343. custom_dict_drills = {}
  1344. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1345. # values will be list of Shapely Points; for slots
  1346. custom_dict_slots = {}
  1347. for exc in flattened_list:
  1348. # copy options of the current excellon obj to the final excellon obj
  1349. for option in exc.options:
  1350. if option is not 'name':
  1351. try:
  1352. exc_final.options[option] = exc.options[option]
  1353. except:
  1354. exc.app.log.warning("Failed to copy option.", option)
  1355. for drill in exc.drills:
  1356. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  1357. if exc_tool_dia not in custom_dict_drills:
  1358. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1359. else:
  1360. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1361. for slot in exc.slots:
  1362. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  1363. if exc_tool_dia not in custom_dict_slots:
  1364. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1365. else:
  1366. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1367. # add the zeros and units to the exc_final object
  1368. exc_final.zeros = exc.zeros
  1369. exc_final.units = exc.units
  1370. # ##########################################
  1371. # Here we add data to the exc_final object #
  1372. # ##########################################
  1373. # variable to make tool_name for the tools
  1374. current_tool = 0
  1375. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1376. # drills
  1377. for tool_dia in custom_dict_drills:
  1378. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1379. current_tool += 1
  1380. tool_name = str(current_tool)
  1381. spec = {"C": float(tool_dia)}
  1382. exc_final.tools[tool_name] = spec
  1383. # rebuild the drills list of dict's that belong to the exc_final object
  1384. for point in custom_dict_drills[tool_dia]:
  1385. exc_final.drills.append(
  1386. {
  1387. "point": point,
  1388. "tool": str(current_tool)
  1389. }
  1390. )
  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='orange', visible=self.options['plot'])
  2294. #
  2295. # self.shapes.redraw()
  2296. # return
  2297. # except (ObjectDeleted, AttributeError, KeyError):
  2298. # self.shapes.clear(update=True)
  2299. # this stays for compatibility reasons, in case we try to open old projects
  2300. try:
  2301. __ = iter(self.solid_geometry)
  2302. except TypeError:
  2303. self.solid_geometry = [self.solid_geometry]
  2304. try:
  2305. # Plot Excellon (All polygons?)
  2306. if self.options["solid"]:
  2307. for geo in self.solid_geometry:
  2308. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2309. visible=self.options['plot'],
  2310. layer=2)
  2311. else:
  2312. for geo in self.solid_geometry:
  2313. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2314. for ints in geo.interiors:
  2315. self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2316. self.shapes.redraw()
  2317. except (ObjectDeleted, AttributeError):
  2318. self.shapes.clear(update=True)
  2319. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2320. """
  2321. Geometric object not associated with a specific
  2322. format.
  2323. """
  2324. optionChanged = QtCore.pyqtSignal(str)
  2325. ui_type = GeometryObjectUI
  2326. def merge(self, geo_list, geo_final, multigeo=None):
  2327. """
  2328. Merges the geometry of objects in grb_list into
  2329. the geometry of geo_final.
  2330. :param geo_list: List of FlatCAMGerber Objects to join.
  2331. :param geo_final: Destination FlatCAMGerber object.
  2332. :return: None
  2333. """
  2334. if geo_final.solid_geometry is None:
  2335. geo_final.solid_geometry = []
  2336. if type(geo_final.solid_geometry) is not list:
  2337. geo_final.solid_geometry = [geo_final.solid_geometry]
  2338. for geo in geo_list:
  2339. for option in geo.options:
  2340. if option is not 'name':
  2341. try:
  2342. geo_final.options[option] = geo.options[option]
  2343. except:
  2344. log.warning("Failed to copy option.", option)
  2345. # Expand lists
  2346. if type(geo) is list:
  2347. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  2348. # If not list, just append
  2349. else:
  2350. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  2351. if multigeo is None or multigeo is False:
  2352. geo_final.multigeo = False
  2353. try:
  2354. geo_final.solid_geometry.append(geo.solid_geometry)
  2355. except Exception as e:
  2356. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  2357. else:
  2358. geo_final.multigeo = True
  2359. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  2360. # tools object attribute, as a key value
  2361. geo_final.solid_geometry = []
  2362. # find the tool_uid maximum value in the geo_final
  2363. geo_final_uid_list = []
  2364. for key in geo_final.tools:
  2365. geo_final_uid_list.append(int(key))
  2366. try:
  2367. max_uid = max(geo_final_uid_list, key=int)
  2368. except ValueError:
  2369. max_uid = 0
  2370. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2371. # to merge the obj.tools as it is likely there is none to merge.
  2372. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  2373. for tool_uid in geo.tools:
  2374. max_uid += 1
  2375. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  2376. @staticmethod
  2377. def get_pts(o):
  2378. """
  2379. Returns a list of all points in the object, where
  2380. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2381. of such. Search is done recursively.
  2382. :param: geometric object
  2383. :return: List of points
  2384. :rtype: list
  2385. """
  2386. pts = []
  2387. # Iterable: descend into each item.
  2388. try:
  2389. for subo in o:
  2390. pts += FlatCAMGeometry.get_pts(subo)
  2391. # Non-iterable
  2392. except TypeError:
  2393. if o is not None:
  2394. if type(o) == MultiPolygon:
  2395. for poly in o:
  2396. pts += FlatCAMGeometry.get_pts(poly)
  2397. # ## Descend into .exerior and .interiors
  2398. elif type(o) == Polygon:
  2399. pts += FlatCAMGeometry.get_pts(o.exterior)
  2400. for i in o.interiors:
  2401. pts += FlatCAMGeometry.get_pts(i)
  2402. elif type(o) == MultiLineString:
  2403. for line in o:
  2404. pts += FlatCAMGeometry.get_pts(line)
  2405. # ## Has .coords: list them.
  2406. else:
  2407. pts += list(o.coords)
  2408. else:
  2409. return
  2410. return pts
  2411. def __init__(self, name):
  2412. FlatCAMObj.__init__(self, name)
  2413. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2414. self.kind = "geometry"
  2415. self.options.update({
  2416. "plot": True,
  2417. "cutz": -0.002,
  2418. "vtipdia": 0.1,
  2419. "vtipangle": 30,
  2420. "travelz": 0.1,
  2421. "feedrate": 5.0,
  2422. "feedrate_z": 5.0,
  2423. "feedrate_rapid": 5.0,
  2424. "spindlespeed": None,
  2425. "dwell": True,
  2426. "dwelltime": 1000,
  2427. "multidepth": False,
  2428. "depthperpass": 0.002,
  2429. "extracut": False,
  2430. "endz": 2.0,
  2431. "toolchange": False,
  2432. "toolchangez": 1.0,
  2433. "toolchangexy": "0.0, 0.0",
  2434. "startz": None,
  2435. "ppname_g": 'default',
  2436. "z_pdepth": -0.02,
  2437. "feedrate_probe": 3.0,
  2438. })
  2439. if "cnctooldia" not in self.options:
  2440. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2441. self.options["startz"] = self.app.defaults["geometry_startz"]
  2442. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2443. self.tooluid = 0
  2444. '''
  2445. self.tools = {}
  2446. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2447. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2448. {tooluid: {
  2449. 'tooldia': 1,
  2450. 'offset': 'Path',
  2451. 'offset_value': 0.0
  2452. 'type': 'Rough',
  2453. 'tool_type': 'C1',
  2454. 'data': self.default_tool_data
  2455. 'solid_geometry': []
  2456. }
  2457. }
  2458. '''
  2459. self.tools = {}
  2460. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2461. # those elements are the ones used for generating GCode
  2462. self.sel_tools = {}
  2463. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2464. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  2465. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2466. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2467. self.v_tool_type = None
  2468. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2469. # the default value is False
  2470. self.multigeo = False
  2471. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2472. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2473. self. special_group = None
  2474. self.old_pp_state = ''
  2475. self.old_toolchangeg_state = ''
  2476. # store here the default data for Geometry Data
  2477. self.default_data = {}
  2478. # Attributes to be included in serialization
  2479. # Always append to it because it carries contents
  2480. # from predecessors.
  2481. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2482. def build_ui(self):
  2483. self.ui_disconnect()
  2484. FlatCAMObj.build_ui(self)
  2485. offset = 0
  2486. tool_idx = 0
  2487. n = len(self.tools)
  2488. self.ui.geo_tools_table.setRowCount(n)
  2489. for tooluid_key, tooluid_value in self.tools.items():
  2490. tool_idx += 1
  2491. row_no = tool_idx - 1
  2492. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2493. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2494. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2495. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2496. # There are no tool bits in MM with more than 3 decimals diameter.
  2497. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2498. if self.units == 'MM':
  2499. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2500. else:
  2501. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2502. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2503. offset_item = QtWidgets.QComboBox()
  2504. for item in self.offset_item_options:
  2505. offset_item.addItem(item)
  2506. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2507. idx = offset_item.findText(tooluid_value['offset'])
  2508. offset_item.setCurrentIndex(idx)
  2509. type_item = QtWidgets.QComboBox()
  2510. for item in self.type_item_options:
  2511. type_item.addItem(item)
  2512. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2513. idx = type_item.findText(tooluid_value['type'])
  2514. type_item.setCurrentIndex(idx)
  2515. tool_type_item = QtWidgets.QComboBox()
  2516. for item in self.tool_type_item_options:
  2517. tool_type_item.addItem(item)
  2518. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2519. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2520. tool_type_item.setCurrentIndex(idx)
  2521. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2522. plot_item = FCCheckBox()
  2523. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2524. if self.ui.plot_cb.isChecked():
  2525. plot_item.setChecked(True)
  2526. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2527. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2528. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2529. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2530. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  2531. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2532. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2533. try:
  2534. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2535. except:
  2536. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2537. # make the diameter column editable
  2538. for row in range(tool_idx):
  2539. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2540. QtCore.Qt.ItemIsEditable |
  2541. QtCore.Qt.ItemIsEnabled)
  2542. # sort the tool diameter column
  2543. # self.ui.geo_tools_table.sortItems(1)
  2544. # all the tools are selected by default
  2545. # self.ui.geo_tools_table.selectColumn(0)
  2546. self.ui.geo_tools_table.resizeColumnsToContents()
  2547. self.ui.geo_tools_table.resizeRowsToContents()
  2548. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2549. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2550. vertical_header.hide()
  2551. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2552. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2553. horizontal_header.setMinimumSectionSize(10)
  2554. horizontal_header.setDefaultSectionSize(70)
  2555. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2556. horizontal_header.resizeSection(0, 20)
  2557. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2558. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2559. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2560. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2561. horizontal_header.resizeSection(4, 40)
  2562. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2563. horizontal_header.resizeSection(4, 17)
  2564. # horizontal_header.setStretchLastSection(True)
  2565. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2566. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2567. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2568. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2569. # self.ui.geo_tools_table.setSortingEnabled(True)
  2570. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2571. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2572. # update UI for all rows - useful after units conversion but only if there is at least one row
  2573. row_cnt = self.ui.geo_tools_table.rowCount()
  2574. if row_cnt > 0:
  2575. for r in range(row_cnt):
  2576. self.update_ui(r)
  2577. # select only the first tool / row
  2578. selected_row = 0
  2579. try:
  2580. self.select_tools_table_row(selected_row, clearsel=True)
  2581. # update the Geometry UI
  2582. self.update_ui()
  2583. except Exception as e:
  2584. # when the tools table is empty there will be this error but once the table is populated it will go away
  2585. log.debug(str(e))
  2586. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2587. # and can create some problems
  2588. if self.multigeo is False:
  2589. self.ui.geo_tools_table.setColumnHidden(6, True)
  2590. else:
  2591. self.ui.geo_tools_table.setColumnHidden(6, False)
  2592. self.set_tool_offset_visibility(selected_row)
  2593. self.ui_connect()
  2594. def set_ui(self, ui):
  2595. FlatCAMObj.set_ui(self, ui)
  2596. log.debug("FlatCAMGeometry.set_ui()")
  2597. assert isinstance(self.ui, GeometryObjectUI), \
  2598. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2599. # populate postprocessor names in the combobox
  2600. for name in list(self.app.postprocessors.keys()):
  2601. self.ui.pp_geometry_name_cb.addItem(name)
  2602. self.form_fields.update({
  2603. "plot": self.ui.plot_cb,
  2604. "cutz": self.ui.cutz_entry,
  2605. "vtipdia": self.ui.tipdia_entry,
  2606. "vtipangle": self.ui.tipangle_entry,
  2607. "travelz": self.ui.travelz_entry,
  2608. "feedrate": self.ui.cncfeedrate_entry,
  2609. "feedrate_z": self.ui.cncplunge_entry,
  2610. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2611. "spindlespeed": self.ui.cncspindlespeed_entry,
  2612. "dwell": self.ui.dwell_cb,
  2613. "dwelltime": self.ui.dwelltime_entry,
  2614. "multidepth": self.ui.mpass_cb,
  2615. "ppname_g": self.ui.pp_geometry_name_cb,
  2616. "z_pdepth": self.ui.pdepth_entry,
  2617. "feedrate_probe": self.ui.feedrate_probe_entry,
  2618. "depthperpass": self.ui.maxdepth_entry,
  2619. "extracut": self.ui.extracut_cb,
  2620. "toolchange": self.ui.toolchangeg_cb,
  2621. "toolchangez": self.ui.toolchangez_entry,
  2622. "endz": self.ui.gendz_entry,
  2623. })
  2624. # Fill form fields only on object create
  2625. self.to_form()
  2626. self.ui.tipdialabel.hide()
  2627. self.ui.tipdia_entry.hide()
  2628. self.ui.tipanglelabel.hide()
  2629. self.ui.tipangle_entry.hide()
  2630. self.ui.cutz_entry.setDisabled(False)
  2631. # store here the default data for Geometry Data
  2632. self.default_data = {}
  2633. self.default_data.update({
  2634. "name": None,
  2635. "plot": None,
  2636. "cutz": None,
  2637. "vtipdia": None,
  2638. "vtipangle": None,
  2639. "travelz": None,
  2640. "feedrate": None,
  2641. "feedrate_z": None,
  2642. "feedrate_rapid": None,
  2643. "dwell": None,
  2644. "dwelltime": None,
  2645. "multidepth": None,
  2646. "ppname_g": None,
  2647. "depthperpass": None,
  2648. "extracut": None,
  2649. "toolchange": None,
  2650. "toolchangez": None,
  2651. "endz": None,
  2652. "spindlespeed": None,
  2653. "toolchangexy": None,
  2654. "startz": None
  2655. })
  2656. # fill in self.default_data values from self.options
  2657. for def_key in self.default_data:
  2658. for opt_key, opt_val in self.options.items():
  2659. if def_key == opt_key:
  2660. self.default_data[def_key] = opt_val
  2661. self.tooluid += 1
  2662. if not self.tools:
  2663. self.tools.update({
  2664. self.tooluid: {
  2665. 'tooldia': float(self.options["cnctooldia"]),
  2666. 'offset': ('Path'),
  2667. 'offset_value': 0.0,
  2668. 'type': _('Rough'),
  2669. 'tool_type': 'C1',
  2670. 'data': self.default_data,
  2671. 'solid_geometry': self.solid_geometry
  2672. }
  2673. })
  2674. else:
  2675. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2676. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2677. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2678. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2679. # following convoluted way of changing the keys from string to float type
  2680. temp_tools = {}
  2681. new_key = 0.0
  2682. for tooluid_key in self.tools:
  2683. val = deepcopy(self.tools[tooluid_key])
  2684. new_key = deepcopy(int(tooluid_key))
  2685. temp_tools[new_key] = val
  2686. self.tools.clear()
  2687. self.tools = deepcopy(temp_tools)
  2688. self.ui.tool_offset_entry.hide()
  2689. self.ui.tool_offset_lbl.hide()
  2690. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2691. self.old_pp_state = self.default_data['multidepth']
  2692. self.old_toolchangeg_state = self.default_data['toolchange']
  2693. if not isinstance(self.ui, GeometryObjectUI):
  2694. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2695. return
  2696. self.ui.geo_tools_table.setupContextMenu()
  2697. self.ui.geo_tools_table.addContextMenu(
  2698. _("Copy"), self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2699. self.ui.geo_tools_table.addContextMenu(
  2700. _("Delete"), lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2701. # Show/Hide Advanced Options
  2702. if self.app.defaults["global_app_level"] == 'b':
  2703. self.ui.level.setText(_(
  2704. '<span style="color:green;"><b>Basic</b></span>'
  2705. ))
  2706. self.ui.geo_tools_table.setColumnHidden(2, True)
  2707. self.ui.geo_tools_table.setColumnHidden(3, True)
  2708. self.ui.geo_tools_table.setColumnHidden(4, True)
  2709. self.ui.addtool_entry_lbl.hide()
  2710. self.ui.addtool_entry.hide()
  2711. self.ui.addtool_btn.hide()
  2712. self.ui.copytool_btn.hide()
  2713. self.ui.deltool_btn.hide()
  2714. self.ui.endzlabel.hide()
  2715. self.ui.gendz_entry.hide()
  2716. self.ui.fr_rapidlabel.hide()
  2717. self.ui.cncfeedrate_rapid_entry.hide()
  2718. self.ui.extracut_cb.hide()
  2719. self.ui.pdepth_label.hide()
  2720. self.ui.pdepth_entry.hide()
  2721. self.ui.feedrate_probe_label.hide()
  2722. self.ui.feedrate_probe_entry.hide()
  2723. else:
  2724. self.ui.level.setText(_(
  2725. '<span style="color:red;"><b>Advanced</b></span>'
  2726. ))
  2727. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2728. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2729. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  2730. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2731. self.ui.addtool_entry.returnPressed.connect(lambda: self.on_tool_add())
  2732. def set_tool_offset_visibility(self, current_row):
  2733. if current_row is None:
  2734. return
  2735. try:
  2736. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2737. if tool_offset is not None:
  2738. tool_offset_txt = tool_offset.currentText()
  2739. if tool_offset_txt == ('Custom'):
  2740. self.ui.tool_offset_entry.show()
  2741. self.ui.tool_offset_lbl.show()
  2742. else:
  2743. self.ui.tool_offset_entry.hide()
  2744. self.ui.tool_offset_lbl.hide()
  2745. except Exception as e:
  2746. log.debug("set_tool_offset_visibility() --> " + str(e))
  2747. return
  2748. def on_offset_value_edited(self):
  2749. '''
  2750. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2751. :return:
  2752. '''
  2753. for current_row in self.ui.geo_tools_table.selectedItems():
  2754. # sometime the header get selected and it has row number -1
  2755. # we don't want to do anything with the header :)
  2756. if current_row.row() < 0:
  2757. continue
  2758. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2759. self.set_tool_offset_visibility(current_row.row())
  2760. for tooluid_key, tooluid_value in self.tools.items():
  2761. if int(tooluid_key) == tool_uid:
  2762. try:
  2763. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2764. except ValueError:
  2765. # try to convert comma to decimal point. if it's still not working error message and return
  2766. try:
  2767. tooluid_value['offset_value'] = float(
  2768. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2769. )
  2770. except ValueError:
  2771. self.app.inform.emit(_(
  2772. "[ERROR_NOTCL] Wrong value format entered, "
  2773. "use a number."
  2774. )
  2775. )
  2776. return
  2777. def ui_connect(self):
  2778. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2779. # changes in geometry UI
  2780. for i in range(self.ui.grid3.count()):
  2781. try:
  2782. # works for CheckBoxes
  2783. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2784. except Exception as e:
  2785. # works for ComboBoxes
  2786. try:
  2787. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2788. except Exception as e2:
  2789. # works for Entry
  2790. try:
  2791. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2792. except:
  2793. pass
  2794. for row in range(self.ui.geo_tools_table.rowCount()):
  2795. for col in [2, 3, 4]:
  2796. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2797. self.on_tooltable_cellwidget_change)
  2798. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2799. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2800. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2801. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2802. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2803. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2804. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2805. for row in range(self.ui.geo_tools_table.rowCount()):
  2806. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2807. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2808. def ui_disconnect(self):
  2809. try:
  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. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2814. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2815. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2816. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2817. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2818. isinstance(self.ui.grid3.itemAt(i).widget(), IntEntry) or \
  2819. isinstance(self.ui.grid3.itemAt(i).widget(), FCEntry):
  2820. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2821. except:
  2822. pass
  2823. try:
  2824. for row in range(self.ui.geo_tools_table.rowCount()):
  2825. for col in [2, 3, 4]:
  2826. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2827. except:
  2828. pass
  2829. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2830. try:
  2831. self.ui.addtool_btn.clicked.disconnect()
  2832. except:
  2833. pass
  2834. try:
  2835. self.ui.copytool_btn.clicked.disconnect()
  2836. except:
  2837. pass
  2838. try:
  2839. self.ui.deltool_btn.clicked.disconnect()
  2840. except:
  2841. pass
  2842. try:
  2843. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2844. except:
  2845. pass
  2846. try:
  2847. self.ui.geo_tools_table.itemChanged.disconnect()
  2848. except:
  2849. pass
  2850. try:
  2851. self.ui.tool_offset_entry.editingFinished.disconnect()
  2852. except:
  2853. pass
  2854. for row in range(self.ui.geo_tools_table.rowCount()):
  2855. try:
  2856. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2857. except:
  2858. pass
  2859. try:
  2860. self.ui.plot_cb.stateChanged.disconnect()
  2861. except:
  2862. pass
  2863. def on_tool_add(self, dia=None):
  2864. self.ui_disconnect()
  2865. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2866. # because the Default value for Tool is used.
  2867. change_message = False
  2868. if dia is not None:
  2869. tooldia = dia
  2870. else:
  2871. try:
  2872. tooldia = float(self.ui.addtool_entry.get_value())
  2873. except ValueError:
  2874. # try to convert comma to decimal point. if it's still not working error message and return
  2875. try:
  2876. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2877. except ValueError:
  2878. change_message = True
  2879. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2880. if tooldia is None:
  2881. self.build_ui()
  2882. self.app.inform.emit(_(
  2883. "[ERROR_NOTCL] Please enter the desired tool diameter in Float format."
  2884. ))
  2885. return
  2886. # construct a list of all 'tooluid' in the self.tools
  2887. tool_uid_list = []
  2888. for tooluid_key in self.tools:
  2889. tool_uid_item = int(tooluid_key)
  2890. tool_uid_list.append(tool_uid_item)
  2891. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2892. if not tool_uid_list:
  2893. max_uid = 0
  2894. else:
  2895. max_uid = max(tool_uid_list)
  2896. self.tooluid = max_uid + 1
  2897. if self.units == 'IN':
  2898. tooldia = float('%.4f' % tooldia)
  2899. else:
  2900. tooldia = float('%.2f' % tooldia)
  2901. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2902. # otherwise we add a tool with data copied from last tool
  2903. if not self.tools:
  2904. self.tools.update({
  2905. self.tooluid: {
  2906. 'tooldia': tooldia,
  2907. 'offset': 'Path',
  2908. 'offset_value': 0.0,
  2909. 'type': _('Rough'),
  2910. 'tool_type': 'C1',
  2911. 'data': deepcopy(self.default_data),
  2912. 'solid_geometry': self.solid_geometry
  2913. }
  2914. })
  2915. else:
  2916. last_data = self.tools[max_uid]['data']
  2917. last_offset = self.tools[max_uid]['offset']
  2918. last_offset_value = self.tools[max_uid]['offset_value']
  2919. last_type = self.tools[max_uid]['type']
  2920. last_tool_type = self.tools[max_uid]['tool_type']
  2921. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2922. # if previous geometry was empty (it may happen for the first tool added)
  2923. # then copy the object.solid_geometry
  2924. if not last_solid_geometry:
  2925. last_solid_geometry = self.solid_geometry
  2926. self.tools.update({
  2927. self.tooluid: {
  2928. 'tooldia': tooldia,
  2929. 'offset': last_offset,
  2930. 'offset_value': last_offset_value,
  2931. 'type': last_type,
  2932. 'tool_type': last_tool_type,
  2933. 'data': deepcopy(last_data),
  2934. 'solid_geometry': deepcopy(last_solid_geometry)
  2935. }
  2936. })
  2937. self.ui.tool_offset_entry.hide()
  2938. self.ui.tool_offset_lbl.hide()
  2939. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2940. try:
  2941. self.ser_attrs.remove('tools')
  2942. except:
  2943. pass
  2944. self.ser_attrs.append('tools')
  2945. if change_message is False:
  2946. self.app.inform.emit(_(
  2947. "[success] Tool added in Tool Table."
  2948. ))
  2949. else:
  2950. change_message = False
  2951. self.app.inform.emit(_(
  2952. "[ERROR_NOTCL] Default Tool added. Wrong value format entered."
  2953. ))
  2954. self.build_ui()
  2955. def on_tool_copy(self, all=None):
  2956. self.ui_disconnect()
  2957. # find the tool_uid maximum value in the self.tools
  2958. uid_list = []
  2959. for key in self.tools:
  2960. uid_list.append(int(key))
  2961. try:
  2962. max_uid = max(uid_list, key=int)
  2963. except ValueError:
  2964. max_uid = 0
  2965. if all is None:
  2966. if self.ui.geo_tools_table.selectedItems():
  2967. for current_row in self.ui.geo_tools_table.selectedItems():
  2968. # sometime the header get selected and it has row number -1
  2969. # we don't want to do anything with the header :)
  2970. if current_row.row() < 0:
  2971. continue
  2972. try:
  2973. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2974. self.set_tool_offset_visibility(current_row.row())
  2975. max_uid += 1
  2976. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  2977. except AttributeError:
  2978. self.app.inform.emit(_(
  2979. "[WARNING_NOTCL] Failed. Select a tool to copy."
  2980. ))
  2981. self.build_ui()
  2982. return
  2983. except Exception as e:
  2984. log.debug("on_tool_copy() --> " + str(e))
  2985. # deselect the table
  2986. # self.ui.geo_tools_table.clearSelection()
  2987. else:
  2988. self.app.inform.emit(_(
  2989. "[WARNING_NOTCL] Failed. Select a tool to copy."
  2990. ))
  2991. self.build_ui()
  2992. return
  2993. else:
  2994. # we copy all tools in geo_tools_table
  2995. try:
  2996. temp_tools = deepcopy(self.tools)
  2997. max_uid += 1
  2998. for tooluid in temp_tools:
  2999. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3000. temp_tools.clear()
  3001. except Exception as e:
  3002. log.debug("on_tool_copy() --> " + str(e))
  3003. # if there are no more tools in geo tools table then hide the tool offset
  3004. if not self.tools:
  3005. self.ui.tool_offset_entry.hide()
  3006. self.ui.tool_offset_lbl.hide()
  3007. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3008. try:
  3009. self.ser_attrs.remove('tools')
  3010. except:
  3011. pass
  3012. self.ser_attrs.append('tools')
  3013. self.build_ui()
  3014. self.app.inform.emit(_(
  3015. "[success] Tool was copied in Tool Table."
  3016. ))
  3017. def on_tool_edit(self, current_item):
  3018. self.ui_disconnect()
  3019. current_row = current_item.row()
  3020. try:
  3021. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3022. except ValueError:
  3023. # try to convert comma to decimal point. if it's still not working error message and return
  3024. try:
  3025. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3026. except ValueError:
  3027. self.app.inform.emit(_(
  3028. "[ERROR_NOTCL] Wrong value format entered, "
  3029. "use a number."
  3030. ))
  3031. return
  3032. tool_dia = float('%.4f' % d)
  3033. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3034. self.tools[tooluid]['tooldia'] = tool_dia
  3035. try:
  3036. self.ser_attrs.remove('tools')
  3037. self.ser_attrs.append('tools')
  3038. except:
  3039. pass
  3040. self.app.inform.emit(_(
  3041. "[success] Tool was edited in Tool Table."
  3042. ))
  3043. self.build_ui()
  3044. def on_tool_delete(self, all=None):
  3045. self.ui_disconnect()
  3046. if all is None:
  3047. if self.ui.geo_tools_table.selectedItems():
  3048. for current_row in self.ui.geo_tools_table.selectedItems():
  3049. # sometime the header get selected and it has row number -1
  3050. # we don't want to do anything with the header :)
  3051. if current_row.row() < 0:
  3052. continue
  3053. try:
  3054. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3055. self.set_tool_offset_visibility(current_row.row())
  3056. temp_tools = deepcopy(self.tools)
  3057. for tooluid_key in self.tools:
  3058. if int(tooluid_key) == tooluid_del:
  3059. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3060. # as a property of the object otherwise there will be nothing to hold it
  3061. if len(self.tools) == 1:
  3062. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3063. temp_tools.pop(tooluid_del, None)
  3064. self.tools = deepcopy(temp_tools)
  3065. temp_tools.clear()
  3066. except AttributeError:
  3067. self.app.inform.emit(_(
  3068. "[WARNING_NOTCL] Failed. Select a tool to delete."
  3069. ))
  3070. self.build_ui()
  3071. return
  3072. except Exception as e:
  3073. log.debug("on_tool_delete() --> " + str(e))
  3074. # deselect the table
  3075. # self.ui.geo_tools_table.clearSelection()
  3076. else:
  3077. self.app.inform.emit(_(
  3078. "[WARNING_NOTCL] Failed. Select a tool to delete."
  3079. ))
  3080. self.build_ui()
  3081. return
  3082. else:
  3083. # we delete all tools in geo_tools_table
  3084. self.tools.clear()
  3085. self.app.plot_all()
  3086. # if there are no more tools in geo tools table then hide the tool offset
  3087. if not self.tools:
  3088. self.ui.tool_offset_entry.hide()
  3089. self.ui.tool_offset_lbl.hide()
  3090. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3091. try:
  3092. self.ser_attrs.remove('tools')
  3093. except:
  3094. pass
  3095. self.ser_attrs.append('tools')
  3096. self.build_ui()
  3097. self.app.inform.emit(_(
  3098. "[success] Tool was deleted in Tool Table."
  3099. ))
  3100. obj_active = self.app.collection.get_active()
  3101. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  3102. # we make it back SingleGeo
  3103. if self.ui.geo_tools_table.rowCount() <= 0:
  3104. obj_active.multigeo = False
  3105. obj_active.options['xmin'] = 0
  3106. obj_active.options['ymin'] = 0
  3107. obj_active.options['xmax'] = 0
  3108. obj_active.options['ymax'] = 0
  3109. if obj_active.multigeo is True:
  3110. try:
  3111. xmin, ymin, xmax, ymax = obj_active.bounds()
  3112. obj_active.options['xmin'] = xmin
  3113. obj_active.options['ymin'] = ymin
  3114. obj_active.options['xmax'] = xmax
  3115. obj_active.options['ymax'] = ymax
  3116. except:
  3117. obj_active.options['xmin'] = 0
  3118. obj_active.options['ymin'] = 0
  3119. obj_active.options['xmax'] = 0
  3120. obj_active.options['ymax'] = 0
  3121. def on_row_selection_change(self):
  3122. self.update_ui()
  3123. def update_ui(self, row=None):
  3124. self.ui_disconnect()
  3125. if row is None:
  3126. try:
  3127. current_row = self.ui.geo_tools_table.currentRow()
  3128. except:
  3129. current_row = 0
  3130. else:
  3131. current_row = row
  3132. if current_row < 0:
  3133. current_row = 0
  3134. self.set_tool_offset_visibility(current_row)
  3135. # populate the form with the data from the tool associated with the row parameter
  3136. try:
  3137. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3138. except Exception as e:
  3139. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3140. return
  3141. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3142. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3143. try:
  3144. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  3145. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3146. except Exception as e:
  3147. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3148. return
  3149. try:
  3150. # set the form with data from the newly selected tool
  3151. for tooluid_key, tooluid_value in self.tools.items():
  3152. if int(tooluid_key) == tooluid:
  3153. for key, value in tooluid_value.items():
  3154. if key == 'data':
  3155. form_value_storage = tooluid_value[key]
  3156. self.update_form(form_value_storage)
  3157. if key == 'offset_value':
  3158. # update the offset value in the entry even if the entry is hidden
  3159. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  3160. if key == 'tool_type' and value == 'V':
  3161. self.update_cutz()
  3162. except Exception as e:
  3163. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  3164. self.ui_connect()
  3165. def ui_update_v_shape(self, tool_type_txt):
  3166. if tool_type_txt == 'V':
  3167. self.ui.tipdialabel.show()
  3168. self.ui.tipdia_entry.show()
  3169. self.ui.tipanglelabel.show()
  3170. self.ui.tipangle_entry.show()
  3171. self.ui.cutz_entry.setDisabled(True)
  3172. self.update_cutz()
  3173. else:
  3174. self.ui.tipdialabel.hide()
  3175. self.ui.tipdia_entry.hide()
  3176. self.ui.tipanglelabel.hide()
  3177. self.ui.tipangle_entry.hide()
  3178. self.ui.cutz_entry.setDisabled(False)
  3179. def update_cutz(self):
  3180. try:
  3181. vdia = float(self.ui.tipdia_entry.get_value())
  3182. except ValueError:
  3183. # try to convert comma to decimal point. if it's still not working error message and return
  3184. try:
  3185. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  3186. except ValueError:
  3187. self.app.inform.emit(_(
  3188. "[ERROR_NOTCL] Wrong value format entered, "
  3189. "use a number."
  3190. ))
  3191. return
  3192. try:
  3193. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  3194. except ValueError:
  3195. # try to convert comma to decimal point. if it's still not working error message and return
  3196. try:
  3197. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  3198. except ValueError:
  3199. self.app.inform.emit(_(
  3200. "[ERROR_NOTCL] Wrong value format entered, "
  3201. "use a number."
  3202. ))
  3203. return
  3204. row = self.ui.geo_tools_table.currentRow()
  3205. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  3206. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  3207. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3208. new_cutz = float('%.4f' % -new_cutz)
  3209. self.ui.cutz_entry.set_value(new_cutz)
  3210. # store the new CutZ value into storage (self.tools)
  3211. for tooluid_key, tooluid_value in self.tools.items():
  3212. if int(tooluid_key) == tool_uid:
  3213. tooluid_value['data']['cutz'] = new_cutz
  3214. def on_tooltable_cellwidget_change(self):
  3215. cw = self.sender()
  3216. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3217. cw_row = cw_index.row()
  3218. cw_col = cw_index.column()
  3219. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3220. # store the text of the cellWidget that changed it's index in the self.tools
  3221. for tooluid_key, tooluid_value in self.tools.items():
  3222. if int(tooluid_key) == current_uid:
  3223. cb_txt = cw.currentText()
  3224. if cw_col == 2:
  3225. tooluid_value['offset'] = cb_txt
  3226. if cb_txt == ('Custom'):
  3227. self.ui.tool_offset_entry.show()
  3228. self.ui.tool_offset_lbl.show()
  3229. else:
  3230. self.ui.tool_offset_entry.hide()
  3231. self.ui.tool_offset_lbl.hide()
  3232. # reset the offset_value in storage self.tools
  3233. tooluid_value['offset_value'] = 0.0
  3234. elif cw_col == 3:
  3235. # force toolpath type as 'Iso' if the tool type is V-Shape
  3236. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3237. tooluid_value['type'] = _('Iso')
  3238. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3239. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3240. else:
  3241. tooluid_value['type'] = cb_txt
  3242. elif cw_col == 4:
  3243. tooluid_value['tool_type'] = cb_txt
  3244. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3245. if cb_txt == 'V':
  3246. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3247. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3248. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3249. def update_form(self, dict_storage):
  3250. for form_key in self.form_fields:
  3251. for storage_key in dict_storage:
  3252. if form_key == storage_key:
  3253. try:
  3254. self.form_fields[form_key].set_value(dict_storage[form_key])
  3255. except Exception as e:
  3256. log.debug(str(e))
  3257. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3258. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3259. self.ui.ois_dwell_geo.on_cb_change()
  3260. self.ui.ois_mpass_geo.on_cb_change()
  3261. self.ui.ois_tcz_geo.on_cb_change()
  3262. def gui_form_to_storage(self):
  3263. self.ui_disconnect()
  3264. widget_changed = self.sender()
  3265. try:
  3266. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3267. except:
  3268. return
  3269. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3270. if widget_idx == 1 or widget_idx == 3:
  3271. self.update_cutz()
  3272. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  3273. # ui_diconnect() so I use this 'hack'
  3274. if isinstance(widget_changed, FCCheckBox):
  3275. if widget_changed.text() == 'Multi-Depth:':
  3276. self.ui.ois_mpass_geo.on_cb_change()
  3277. if widget_changed.text() == 'Tool change':
  3278. self.ui.ois_tcz_geo.on_cb_change()
  3279. if widget_changed.text() == 'Dwell:':
  3280. self.ui.ois_dwell_geo.on_cb_change()
  3281. row = self.ui.geo_tools_table.currentRow()
  3282. if row < 0:
  3283. row = 0
  3284. # store all the data associated with the row parameter to the self.tools storage
  3285. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3286. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3287. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3288. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3289. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3290. try:
  3291. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3292. except ValueError:
  3293. # try to convert comma to decimal point. if it's still not working error message and return
  3294. try:
  3295. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3296. )
  3297. except ValueError:
  3298. self.app.inform.emit(_(
  3299. "[ERROR_NOTCL] Wrong value format entered, "
  3300. "use a number."
  3301. ))
  3302. return
  3303. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3304. temp_tools = {}
  3305. temp_dia = {}
  3306. temp_data = {}
  3307. for tooluid_key, tooluid_value in self.tools.items():
  3308. if int(tooluid_key) == tooluid_item:
  3309. for key, value in tooluid_value.items():
  3310. if key == 'tooldia':
  3311. temp_dia[key] = tooldia_item
  3312. # update the 'offset', 'type' and 'tool_type' sections
  3313. if key == 'offset':
  3314. temp_dia[key] = offset_item
  3315. if key == 'type':
  3316. temp_dia[key] = type_item
  3317. if key == 'tool_type':
  3318. temp_dia[key] = tool_type_item
  3319. if key == 'offset_value':
  3320. temp_dia[key] = offset_value_item
  3321. if key == 'data':
  3322. # update the 'data' section
  3323. for data_key in tooluid_value[key].keys():
  3324. for form_key, form_value in self.form_fields.items():
  3325. if form_key == data_key:
  3326. temp_data[data_key] = form_value.get_value()
  3327. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3328. # updated from self.app.defaults
  3329. if data_key not in self.form_fields:
  3330. temp_data[data_key] = value[data_key]
  3331. temp_dia[key] = deepcopy(temp_data)
  3332. temp_data.clear()
  3333. if key == 'solid_geometry':
  3334. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3335. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3336. else:
  3337. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3338. self.tools.clear()
  3339. self.tools = deepcopy(temp_tools)
  3340. temp_tools.clear()
  3341. self.ui_connect()
  3342. def select_tools_table_row(self, row, clearsel=None):
  3343. if clearsel:
  3344. self.ui.geo_tools_table.clearSelection()
  3345. if self.ui.geo_tools_table.rowCount() > 0:
  3346. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3347. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3348. def export_dxf(self):
  3349. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3350. dwg = None
  3351. try:
  3352. dwg = ezdxf.new('R2010')
  3353. msp = dwg.modelspace()
  3354. def g2dxf(dxf_space, geo):
  3355. if isinstance(geo, MultiPolygon):
  3356. for poly in geo:
  3357. ext_points = list(poly.exterior.coords)
  3358. dxf_space.add_lwpolyline(ext_points)
  3359. for interior in poly.interiors:
  3360. dxf_space.add_lwpolyline(list(interior.coords))
  3361. if isinstance(geo, Polygon):
  3362. ext_points = list(geo.exterior.coords)
  3363. dxf_space.add_lwpolyline(ext_points)
  3364. for interior in geo.interiors:
  3365. dxf_space.add_lwpolyline(list(interior.coords))
  3366. if isinstance(geo, MultiLineString):
  3367. for line in geo:
  3368. dxf_space.add_lwpolyline(list(line.coords))
  3369. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  3370. dxf_space.add_lwpolyline(list(geo.coords))
  3371. multigeo_solid_geometry = []
  3372. if self.multigeo:
  3373. for tool in self.tools:
  3374. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  3375. else:
  3376. multigeo_solid_geometry = self.solid_geometry
  3377. for geo in multigeo_solid_geometry:
  3378. if type(geo) == list:
  3379. for g in geo:
  3380. g2dxf(msp, g)
  3381. else:
  3382. g2dxf(msp, geo)
  3383. # points = FlatCAMGeometry.get_pts(geo)
  3384. # msp.add_lwpolyline(points)
  3385. except Exception as e:
  3386. log.debug(str(e))
  3387. return dwg
  3388. def get_selected_tools_table_items(self):
  3389. """
  3390. Returns a list of lists, each list in the list is made out of row elements
  3391. :return: List of table_tools items.
  3392. :rtype: list
  3393. """
  3394. table_tools_items = []
  3395. if self.multigeo:
  3396. for x in self.ui.geo_tools_table.selectedItems():
  3397. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  3398. for column in range(0, self.ui.geo_tools_table.columnCount())])
  3399. else:
  3400. for x in self.ui.geo_tools_table.selectedItems():
  3401. r = []
  3402. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  3403. # so we don't read them
  3404. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  3405. # the columns have items that have text but also have items that are widgets
  3406. # for which the text they hold has to be read differently
  3407. try:
  3408. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  3409. except AttributeError:
  3410. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  3411. except:
  3412. pass
  3413. r.append(txt)
  3414. table_tools_items.append(r)
  3415. for item in table_tools_items:
  3416. item[0] = str(item[0])
  3417. return table_tools_items
  3418. def on_pp_changed(self):
  3419. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3420. if current_pp == 'hpgl':
  3421. self.old_pp_state = self.ui.mpass_cb.get_value()
  3422. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3423. self.ui.mpass_cb.set_value(False)
  3424. self.ui.mpass_cb.setDisabled(True)
  3425. self.ui.toolchangeg_cb.set_value(True)
  3426. self.ui.toolchangeg_cb.setDisabled(True)
  3427. else:
  3428. self.ui.mpass_cb.set_value(self.old_pp_state)
  3429. self.ui.mpass_cb.setDisabled(False)
  3430. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3431. self.ui.toolchangeg_cb.setDisabled(False)
  3432. if "toolchange_probe" in current_pp.lower():
  3433. self.ui.pdepth_entry.setVisible(True)
  3434. self.ui.pdepth_label.show()
  3435. self.ui.feedrate_probe_entry.setVisible(True)
  3436. self.ui.feedrate_probe_label.show()
  3437. else:
  3438. self.ui.pdepth_entry.setVisible(False)
  3439. self.ui.pdepth_label.hide()
  3440. self.ui.feedrate_probe_entry.setVisible(False)
  3441. self.ui.feedrate_probe_label.hide()
  3442. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  3443. self.ui.fr_rapidlabel.show()
  3444. self.ui.cncfeedrate_rapid_entry.show()
  3445. else:
  3446. self.ui.fr_rapidlabel.hide()
  3447. self.ui.cncfeedrate_rapid_entry.hide()
  3448. def on_generatecnc_button_click(self, *args):
  3449. self.app.report_usage("geometry_on_generatecnc_button")
  3450. self.read_form()
  3451. self.sel_tools = {}
  3452. try:
  3453. if self.special_group:
  3454. self.app.inform.emit(_(
  3455. "[WARNING_NOTCL] This Geometry can't be processed because it is %s geometry."
  3456. ) % str(self.special_group))
  3457. return
  3458. except AttributeError:
  3459. pass
  3460. # test to see if we have tools available in the tool table
  3461. if self.ui.geo_tools_table.selectedItems():
  3462. for x in self.ui.geo_tools_table.selectedItems():
  3463. try:
  3464. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3465. except ValueError:
  3466. # try to convert comma to decimal point. if it's still not working error message and return
  3467. try:
  3468. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3469. except ValueError:
  3470. self.app.inform.emit(_(
  3471. "[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  3472. "use a number."
  3473. ))
  3474. return
  3475. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3476. for tooluid_key, tooluid_value in self.tools.items():
  3477. if int(tooluid_key) == tooluid:
  3478. self.sel_tools.update({
  3479. tooluid: deepcopy(tooluid_value)
  3480. })
  3481. self.mtool_gen_cncjob()
  3482. self.ui.geo_tools_table.clearSelection()
  3483. elif self.ui.geo_tools_table.rowCount() == 1:
  3484. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3485. for tooluid_key, tooluid_value in self.tools.items():
  3486. if int(tooluid_key) == tooluid:
  3487. self.sel_tools.update({
  3488. tooluid: deepcopy(tooluid_value)
  3489. })
  3490. self.mtool_gen_cncjob()
  3491. self.ui.geo_tools_table.clearSelection()
  3492. else:
  3493. self.app.inform.emit(_(
  3494. "[ERROR_NOTCL] Failed. No tool selected in the tool table ..."
  3495. ))
  3496. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3497. """
  3498. Creates a multi-tool CNCJob out of this Geometry object.
  3499. The actual work is done by the target FlatCAMCNCjob object's
  3500. `generate_from_geometry_2()` method.
  3501. :param z_cut: Cut depth (negative)
  3502. :param z_move: Hight of the tool when travelling (not cutting)
  3503. :param feedrate: Feed rate while cutting on X - Y plane
  3504. :param feedrate_z: Feed rate while cutting on Z plane
  3505. :param feedrate_rapid: Feed rate while moving with rapids
  3506. :param tooldia: Tool diameter
  3507. :param outname: Name of the new object
  3508. :param spindlespeed: Spindle speed (RPM)
  3509. :param ppname_g Name of the postprocessor
  3510. :return: None
  3511. """
  3512. offset_str = ''
  3513. multitool_gcode = ''
  3514. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3515. outname = "%s_%s" % (self.options["name"], 'cnc')
  3516. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3517. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3518. try:
  3519. xmin = self.options['xmin']
  3520. ymin = self.options['ymin']
  3521. xmax = self.options['xmax']
  3522. ymax = self.options['ymax']
  3523. except Exception as e:
  3524. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3525. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  3526. msg += _('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s') % str(e)
  3527. msg += traceback.format_exc()
  3528. self.app.inform.emit(msg)
  3529. return
  3530. # Object initialization function for app.new_object()
  3531. # RUNNING ON SEPARATE THREAD!
  3532. def job_init_single_geometry(job_obj, app_obj):
  3533. log.debug("Creating a CNCJob out of a single-geometry")
  3534. assert isinstance(job_obj, FlatCAMCNCjob), \
  3535. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3536. # count the tools
  3537. tool_cnt = 0
  3538. dia_cnc_dict = {}
  3539. # this turn on the FlatCAMCNCJob plot for multiple tools
  3540. job_obj.multitool = True
  3541. job_obj.multigeo = False
  3542. job_obj.cnc_tools.clear()
  3543. # job_obj.create_geometry()
  3544. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3545. job_obj.segx = segx
  3546. job_obj.segy = segy
  3547. try:
  3548. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3549. except ValueError:
  3550. # try to convert comma to decimal point. if it's still not working error message and return
  3551. try:
  3552. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3553. except ValueError:
  3554. self.app.inform.emit(
  3555. _(
  3556. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3557. ))
  3558. try:
  3559. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3560. except ValueError:
  3561. # try to convert comma to decimal point. if it's still not working error message and return
  3562. try:
  3563. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3564. except ValueError:
  3565. self.app.inform.emit(
  3566. _(
  3567. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3568. 'or self.options["feedrate_probe"]'
  3569. ))
  3570. for tooluid_key in self.sel_tools:
  3571. tool_cnt += 1
  3572. app_obj.progress.emit(20)
  3573. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3574. if diadict_key == 'tooldia':
  3575. tooldia_val = float('%.4f' % float(diadict_value))
  3576. dia_cnc_dict.update({
  3577. diadict_key: tooldia_val
  3578. })
  3579. if diadict_key == 'offset':
  3580. o_val = diadict_value.lower()
  3581. dia_cnc_dict.update({
  3582. diadict_key: o_val
  3583. })
  3584. if diadict_key == 'type':
  3585. t_val = diadict_value
  3586. dia_cnc_dict.update({
  3587. diadict_key: t_val
  3588. })
  3589. if diadict_key == 'tool_type':
  3590. tt_val = diadict_value
  3591. dia_cnc_dict.update({
  3592. diadict_key: tt_val
  3593. })
  3594. if diadict_key == 'data':
  3595. for data_key, data_value in diadict_value.items():
  3596. if data_key == "multidepth":
  3597. multidepth = data_value
  3598. if data_key == "depthperpass":
  3599. depthpercut = data_value
  3600. if data_key == "extracut":
  3601. extracut = data_value
  3602. if data_key == "startz":
  3603. startz = data_value
  3604. if data_key == "endz":
  3605. endz = data_value
  3606. if data_key == "toolchangez":
  3607. toolchangez =data_value
  3608. if data_key == "toolchangexy":
  3609. toolchangexy = data_value
  3610. if data_key == "toolchange":
  3611. toolchange = data_value
  3612. if data_key == "cutz":
  3613. z_cut = data_value
  3614. if data_key == "travelz":
  3615. z_move = data_value
  3616. if data_key == "feedrate":
  3617. feedrate = data_value
  3618. if data_key == "feedrate_z":
  3619. feedrate_z = data_value
  3620. if data_key == "feedrate_rapid":
  3621. feedrate_rapid = data_value
  3622. if data_key == "ppname_g":
  3623. pp_geometry_name = data_value
  3624. if data_key == "spindlespeed":
  3625. spindlespeed = data_value
  3626. if data_key == "dwell":
  3627. dwell = data_value
  3628. if data_key == "dwelltime":
  3629. dwelltime = data_value
  3630. datadict = deepcopy(diadict_value)
  3631. dia_cnc_dict.update({
  3632. diadict_key: datadict
  3633. })
  3634. if dia_cnc_dict['offset'] == ('in'):
  3635. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3636. offset_str = 'inside'
  3637. elif dia_cnc_dict['offset'].lower() == ('out'):
  3638. tool_offset = dia_cnc_dict['tooldia'] / 2
  3639. offset_str = 'outside'
  3640. elif dia_cnc_dict['offset'].lower() == ('path'):
  3641. offset_str = 'onpath'
  3642. tool_offset = 0.0
  3643. else:
  3644. offset_str = 'custom'
  3645. try:
  3646. offset_value = float(self.ui.tool_offset_entry.get_value())
  3647. except ValueError:
  3648. # try to convert comma to decimal point. if it's still not working error message and return
  3649. try:
  3650. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3651. )
  3652. except ValueError:
  3653. self.app.inform.emit(_(
  3654. "[ERROR_NOTCL] Wrong value format entered, "
  3655. "use a number."
  3656. ))
  3657. return
  3658. if offset_value:
  3659. tool_offset = float(offset_value)
  3660. else:
  3661. self.app.inform.emit(
  3662. _(
  3663. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3664. "Add a Tool Offset or change the Offset Type."
  3665. )
  3666. )
  3667. return
  3668. dia_cnc_dict.update({
  3669. 'offset_value': tool_offset
  3670. })
  3671. spindledir = self.app.defaults['geometry_spindledir']
  3672. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3673. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3674. # Propagate options
  3675. job_obj.options["tooldia"] = tooldia_val
  3676. job_obj.options['type'] = 'Geometry'
  3677. job_obj.options['tool_dia'] = tooldia_val
  3678. job_obj.options['xmin'] = xmin
  3679. job_obj.options['ymin'] = ymin
  3680. job_obj.options['xmax'] = xmax
  3681. job_obj.options['ymax'] = ymax
  3682. app_obj.progress.emit(40)
  3683. tol = float(self.app.defaults['global_tolerance'])
  3684. res = job_obj.generate_from_geometry_2(
  3685. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  3686. z_cut=z_cut, z_move=z_move,
  3687. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3688. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3689. multidepth=multidepth, depthpercut=depthpercut,
  3690. extracut=extracut, startz=startz, endz=endz,
  3691. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3692. pp_geometry_name=pp_geometry_name,
  3693. tool_no=tool_cnt)
  3694. if res == 'fail':
  3695. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3696. return 'fail'
  3697. else:
  3698. dia_cnc_dict['gcode'] = res
  3699. app_obj.progress.emit(50)
  3700. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3701. # object is the source of gcode
  3702. job_obj.toolchange_xy_type = "geometry"
  3703. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3704. # TODO this serve for bounding box creation only; should be optimized
  3705. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3706. app_obj.progress.emit(80)
  3707. job_obj.cnc_tools.update({
  3708. tooluid_key: deepcopy(dia_cnc_dict)
  3709. })
  3710. dia_cnc_dict.clear()
  3711. # Object initialization function for app.new_object()
  3712. # RUNNING ON SEPARATE THREAD!
  3713. def job_init_multi_geometry(job_obj, app_obj):
  3714. log.debug("Creating a CNCJob out of a multi-geometry")
  3715. assert isinstance(job_obj, FlatCAMCNCjob), \
  3716. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3717. # count the tools
  3718. tool_cnt = 0
  3719. dia_cnc_dict = {}
  3720. current_uid = int(1)
  3721. # this turn on the FlatCAMCNCJob plot for multiple tools
  3722. job_obj.multitool = True
  3723. job_obj.multigeo = True
  3724. job_obj.cnc_tools.clear()
  3725. job_obj.options['xmin'] = xmin
  3726. job_obj.options['ymin'] = ymin
  3727. job_obj.options['xmax'] = xmax
  3728. job_obj.options['ymax'] = ymax
  3729. try:
  3730. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3731. except ValueError:
  3732. # try to convert comma to decimal point. if it's still not working error message and return
  3733. try:
  3734. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3735. except ValueError:
  3736. self.app.inform.emit(
  3737. _(
  3738. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3739. ))
  3740. try:
  3741. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3742. except ValueError:
  3743. # try to convert comma to decimal point. if it's still not working error message and return
  3744. try:
  3745. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3746. except ValueError:
  3747. self.app.inform.emit(
  3748. _(
  3749. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3750. 'or self.options["feedrate_probe"]'
  3751. ))
  3752. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3753. if not self.solid_geometry:
  3754. a = 0
  3755. for tooluid_key in self.tools:
  3756. if self.tools[tooluid_key]['solid_geometry'] is None:
  3757. a += 1
  3758. if a == len(self.tools):
  3759. self.app.inform.emit(_(
  3760. '[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'
  3761. ))
  3762. return 'fail'
  3763. for tooluid_key in self.sel_tools:
  3764. tool_cnt += 1
  3765. app_obj.progress.emit(20)
  3766. # find the tool_dia associated with the tooluid_key
  3767. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3768. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3769. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3770. for k, v in self.tools.items():
  3771. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3772. current_uid = int(k)
  3773. break
  3774. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3775. if diadict_key == 'tooldia':
  3776. tooldia_val = float('%.4f' % float(diadict_value))
  3777. dia_cnc_dict.update({
  3778. diadict_key: tooldia_val
  3779. })
  3780. if diadict_key == 'offset':
  3781. o_val = diadict_value.lower()
  3782. dia_cnc_dict.update({
  3783. diadict_key: o_val
  3784. })
  3785. if diadict_key == 'type':
  3786. t_val = diadict_value
  3787. dia_cnc_dict.update({
  3788. diadict_key: t_val
  3789. })
  3790. if diadict_key == 'tool_type':
  3791. tt_val = diadict_value
  3792. dia_cnc_dict.update({
  3793. diadict_key: tt_val
  3794. })
  3795. if diadict_key == 'data':
  3796. for data_key, data_value in diadict_value.items():
  3797. if data_key == "multidepth":
  3798. multidepth = data_value
  3799. if data_key == "depthperpass":
  3800. depthpercut = data_value
  3801. if data_key == "extracut":
  3802. extracut = data_value
  3803. if data_key == "startz":
  3804. startz = data_value
  3805. if data_key == "endz":
  3806. endz = data_value
  3807. if data_key == "toolchangez":
  3808. toolchangez =data_value
  3809. if data_key == "toolchangexy":
  3810. toolchangexy = data_value
  3811. if data_key == "toolchange":
  3812. toolchange = data_value
  3813. if data_key == "cutz":
  3814. z_cut = data_value
  3815. if data_key == "travelz":
  3816. z_move = data_value
  3817. if data_key == "feedrate":
  3818. feedrate = data_value
  3819. if data_key == "feedrate_z":
  3820. feedrate_z = data_value
  3821. if data_key == "feedrate_rapid":
  3822. feedrate_rapid = data_value
  3823. if data_key == "ppname_g":
  3824. pp_geometry_name = data_value
  3825. if data_key == "spindlespeed":
  3826. spindlespeed = data_value
  3827. if data_key == "dwell":
  3828. dwell = data_value
  3829. if data_key == "dwelltime":
  3830. dwelltime = data_value
  3831. datadict = deepcopy(diadict_value)
  3832. dia_cnc_dict.update({
  3833. diadict_key: datadict
  3834. })
  3835. if dia_cnc_dict['offset'] == ('in'):
  3836. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3837. offset_str = 'inside'
  3838. elif dia_cnc_dict['offset'].lower() == ('out'):
  3839. tool_offset = dia_cnc_dict['tooldia'] / 2
  3840. offset_str = 'outside'
  3841. elif dia_cnc_dict['offset'].lower() == ('path'):
  3842. offset_str = 'onpath'
  3843. tool_offset = 0.0
  3844. else:
  3845. offset_str = 'custom'
  3846. try:
  3847. offset_value = float(self.ui.tool_offset_entry.get_value())
  3848. except ValueError:
  3849. # try to convert comma to decimal point. if it's still not working error message and return
  3850. try:
  3851. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3852. )
  3853. except ValueError:
  3854. self.app.inform.emit(_(
  3855. "[ERROR_NOTCL] Wrong value format entered, "
  3856. "use a number."
  3857. ))
  3858. return
  3859. if offset_value:
  3860. tool_offset = float(offset_value)
  3861. else:
  3862. self.app.inform.emit(
  3863. _(
  3864. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3865. "Add a Tool Offset or change the Offset Type."
  3866. )
  3867. )
  3868. return
  3869. dia_cnc_dict.update({
  3870. 'offset_value': tool_offset
  3871. })
  3872. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3873. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3874. # Propagate options
  3875. job_obj.options["tooldia"] = tooldia_val
  3876. job_obj.options['type'] = 'Geometry'
  3877. job_obj.options['tool_dia'] = tooldia_val
  3878. app_obj.progress.emit(40)
  3879. spindledir = self.app.defaults['geometry_spindledir']
  3880. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3881. tol = float(self.app.defaults['global_tolerance'])
  3882. res = job_obj.generate_from_multitool_geometry(
  3883. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3884. tolerance=tol, z_cut=z_cut, z_move=z_move,
  3885. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3886. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3887. multidepth=multidepth, depthpercut=depthpercut,
  3888. extracut=extracut, startz=startz, endz=endz,
  3889. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3890. pp_geometry_name=pp_geometry_name,
  3891. tool_no=tool_cnt)
  3892. if res == 'fail':
  3893. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3894. return 'fail'
  3895. else:
  3896. dia_cnc_dict['gcode'] = res
  3897. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3898. # TODO this serve for bounding box creation only; should be optimized
  3899. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3900. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3901. # object is the source of gcode
  3902. job_obj.toolchange_xy_type = "geometry"
  3903. app_obj.progress.emit(80)
  3904. job_obj.cnc_tools.update({
  3905. tooluid_key: deepcopy(dia_cnc_dict)
  3906. })
  3907. dia_cnc_dict.clear()
  3908. if use_thread:
  3909. # To be run in separate thread
  3910. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3911. # separate solid_geometry in the self.tools dictionary
  3912. def job_thread(app_obj):
  3913. if self.solid_geometry:
  3914. with self.app.proc_container.new(_("Generating CNC Code")):
  3915. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3916. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3917. app_obj.progress.emit(100)
  3918. else:
  3919. with self.app.proc_container.new(_("Generating CNC Code")):
  3920. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3921. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3922. app_obj.progress.emit(100)
  3923. # Create a promise with the name
  3924. self.app.collection.promise(outname)
  3925. # Send to worker
  3926. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3927. else:
  3928. if self.solid_geometry:
  3929. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3930. else:
  3931. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3932. def generatecncjob(self, outname=None,
  3933. tooldia=None, offset=None,
  3934. z_cut=None, z_move=None,
  3935. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3936. spindlespeed=None, dwell=None, dwelltime=None,
  3937. multidepth=None, depthperpass=None,
  3938. toolchange=None, toolchangez=None, toolchangexy=None,
  3939. extracut=None, startz=None, endz=None,
  3940. ppname_g=None,
  3941. segx=None,
  3942. segy=None,
  3943. use_thread=True):
  3944. """
  3945. Only used for TCL Command.
  3946. Creates a CNCJob out of this Geometry object. The actual
  3947. work is done by the target FlatCAMCNCjob object's
  3948. `generate_from_geometry_2()` method.
  3949. :param z_cut: Cut depth (negative)
  3950. :param z_move: Hight of the tool when travelling (not cutting)
  3951. :param feedrate: Feed rate while cutting on X - Y plane
  3952. :param feedrate_z: Feed rate while cutting on Z plane
  3953. :param feedrate_rapid: Feed rate while moving with rapids
  3954. :param tooldia: Tool diameter
  3955. :param outname: Name of the new object
  3956. :param spindlespeed: Spindle speed (RPM)
  3957. :param ppname_g Name of the postprocessor
  3958. :return: None
  3959. """
  3960. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3961. outname = outname if outname is not None else self.options["name"]
  3962. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3963. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3964. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3965. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3966. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3967. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3968. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3969. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3970. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3971. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3972. startz = startz if startz is not None else self.options["startz"]
  3973. endz = endz if endz is not None else float(self.options["endz"])
  3974. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3975. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3976. toolchange = toolchange if toolchange else self.options["toolchange"]
  3977. offset = offset if offset else 0.0
  3978. # int or None.
  3979. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3980. dwell = dwell if dwell else self.options["dwell"]
  3981. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3982. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3983. # Object initialization function for app.new_object()
  3984. # RUNNING ON SEPARATE THREAD!
  3985. def job_init(job_obj, app_obj):
  3986. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3987. # Propagate options
  3988. job_obj.options["tooldia"] = tooldia
  3989. app_obj.progress.emit(20)
  3990. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3991. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3992. app_obj.progress.emit(40)
  3993. job_obj.options['type'] = 'Geometry'
  3994. job_obj.options['tool_dia'] = tooldia
  3995. job_obj.segx = segx
  3996. job_obj.segy = segy
  3997. try:
  3998. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3999. except ValueError:
  4000. # try to convert comma to decimal point. if it's still not working error message and return
  4001. try:
  4002. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  4003. except ValueError:
  4004. self.app.inform.emit(
  4005. _(
  4006. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  4007. ))
  4008. try:
  4009. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4010. except ValueError:
  4011. # try to convert comma to decimal point. if it's still not working error message and return
  4012. try:
  4013. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  4014. except ValueError:
  4015. self.app.inform.emit(
  4016. _(
  4017. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  4018. 'or self.options["feedrate_probe"]'
  4019. ))
  4020. job_obj.options['xmin'] = self.options['xmin']
  4021. job_obj.options['ymin'] = self.options['ymin']
  4022. job_obj.options['xmax'] = self.options['xmax']
  4023. job_obj.options['ymax'] = self.options['ymax']
  4024. tol = float(self.app.defaults['global_tolerance'])
  4025. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=tol,
  4026. z_cut=z_cut, z_move=z_move,
  4027. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4028. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4029. multidepth=multidepth, depthpercut=depthperpass,
  4030. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4031. extracut=extracut, startz=startz, endz=endz,
  4032. pp_geometry_name=ppname_g
  4033. )
  4034. app_obj.progress.emit(50)
  4035. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4036. # source of gcode
  4037. job_obj.toolchange_xy_type = "geometry"
  4038. job_obj.gcode_parse()
  4039. app_obj.progress.emit(80)
  4040. if use_thread:
  4041. # To be run in separate thread
  4042. def job_thread(app_obj):
  4043. with self.app.proc_container.new(_("Generating CNC Code")):
  4044. app_obj.new_object("cncjob", outname, job_init)
  4045. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  4046. app_obj.progress.emit(100)
  4047. # Create a promise with the name
  4048. self.app.collection.promise(outname)
  4049. # Send to worker
  4050. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4051. else:
  4052. self.app.new_object("cncjob", outname, job_init)
  4053. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4054. # if self.muted_ui:
  4055. # return
  4056. # self.read_form_item('plot')
  4057. def scale(self, xfactor, yfactor=None, point=None):
  4058. """
  4059. Scales all geometry by a given factor.
  4060. :param xfactor: Factor by which to scale the object's geometry/
  4061. :type xfactor: float
  4062. :param yfactor: Factor by which to scale the object's geometry/
  4063. :type yfactor: float
  4064. :return: None
  4065. :rtype: None
  4066. """
  4067. try:
  4068. xfactor = float(xfactor)
  4069. except:
  4070. self.app.inform.emit(_(
  4071. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  4072. return
  4073. if yfactor is None:
  4074. yfactor = xfactor
  4075. else:
  4076. try:
  4077. yfactor = float(yfactor)
  4078. except:
  4079. self.app.inform.emit(_(
  4080. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."
  4081. ))
  4082. return
  4083. if point is None:
  4084. px = 0
  4085. py = 0
  4086. else:
  4087. px, py = point
  4088. # if type(self.solid_geometry) == list:
  4089. # geo_list = self.flatten(self.solid_geometry)
  4090. # self.solid_geometry = []
  4091. # # for g in geo_list:
  4092. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  4093. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  4094. # for g in geo_list]
  4095. # else:
  4096. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  4097. # origin=(px, py))
  4098. # self.app.inform.emit("[success] Geometry Scale done.")
  4099. def scale_recursion(geom):
  4100. if type(geom) == list:
  4101. geoms=list()
  4102. for local_geom in geom:
  4103. geoms.append(scale_recursion(local_geom))
  4104. return geoms
  4105. else:
  4106. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4107. if self.multigeo is True:
  4108. for tool in self.tools:
  4109. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4110. else:
  4111. self.solid_geometry=scale_recursion(self.solid_geometry)
  4112. self.app.inform.emit(_(
  4113. "[success] Geometry Scale done."
  4114. ))
  4115. def offset(self, vect):
  4116. """
  4117. Offsets all geometry by a given vector/
  4118. :param vect: (x, y) vector by which to offset the object's geometry.
  4119. :type vect: tuple
  4120. :return: None
  4121. :rtype: None
  4122. """
  4123. try:
  4124. dx, dy = vect
  4125. except TypeError:
  4126. self.app.inform.emit(_(
  4127. "[ERROR_NOTCL] An (x,y) pair of values are needed. "
  4128. "Probable you entered only one value in the Offset field."
  4129. ))
  4130. return
  4131. def translate_recursion(geom):
  4132. if type(geom) == list:
  4133. geoms=list()
  4134. for local_geom in geom:
  4135. geoms.append(translate_recursion(local_geom))
  4136. return geoms
  4137. else:
  4138. return affinity.translate(geom, xoff=dx, yoff=dy)
  4139. if self.multigeo is True:
  4140. for tool in self.tools:
  4141. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  4142. else:
  4143. self.solid_geometry=translate_recursion(self.solid_geometry)
  4144. self.app.inform.emit(_(
  4145. "[success] Geometry Offset done."
  4146. ))
  4147. def convert_units(self, units):
  4148. self.ui_disconnect()
  4149. factor = Geometry.convert_units(self, units)
  4150. self.options['cutz'] = float(self.options['cutz']) * factor
  4151. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  4152. self.options['travelz'] = float(self.options['travelz']) * factor
  4153. self.options['feedrate'] = float(self.options['feedrate']) * factor
  4154. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  4155. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  4156. self.options['endz'] = float(self.options['endz']) * factor
  4157. # self.options['cnctooldia'] *= factor
  4158. # self.options['painttooldia'] *= factor
  4159. # self.options['paintmargin'] *= factor
  4160. # self.options['paintoverlap'] *= factor
  4161. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  4162. if self.app.defaults["geometry_toolchangexy"] == '':
  4163. self.options['toolchangexy'] = "0.0, 0.0"
  4164. else:
  4165. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  4166. if len(coords_xy) < 2:
  4167. self.app.inform.emit(_(
  4168. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4169. "in the format (x, y) \nbut now there is only one value, not two. "
  4170. ))
  4171. return 'fail'
  4172. coords_xy[0] *= factor
  4173. coords_xy[1] *= factor
  4174. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4175. if self.options['startz'] is not None:
  4176. self.options['startz'] = float(self.options['startz']) * factor
  4177. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4178. 'endz', 'toolchangez']
  4179. if isinstance(self, FlatCAMGeometry):
  4180. temp_tools_dict = {}
  4181. tool_dia_copy = {}
  4182. data_copy = {}
  4183. for tooluid_key, tooluid_value in self.tools.items():
  4184. for dia_key, dia_value in tooluid_value.items():
  4185. if dia_key == 'tooldia':
  4186. dia_value *= factor
  4187. dia_value = float('%.4f' % dia_value)
  4188. tool_dia_copy[dia_key] = dia_value
  4189. if dia_key == 'offset':
  4190. tool_dia_copy[dia_key] = dia_value
  4191. if dia_key == 'offset_value':
  4192. dia_value *= factor
  4193. tool_dia_copy[dia_key] = dia_value
  4194. # convert the value in the Custom Tool Offset entry in UI
  4195. custom_offset = None
  4196. try:
  4197. custom_offset = float(self.ui.tool_offset_entry.get_value())
  4198. except ValueError:
  4199. # try to convert comma to decimal point. if it's still not working error message and return
  4200. try:
  4201. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  4202. )
  4203. except ValueError:
  4204. self.app.inform.emit(_(
  4205. "[ERROR_NOTCL] Wrong value format entered, "
  4206. "use a number."
  4207. ))
  4208. return
  4209. except TypeError:
  4210. pass
  4211. if custom_offset:
  4212. custom_offset *= factor
  4213. self.ui.tool_offset_entry.set_value(custom_offset)
  4214. if dia_key == 'type':
  4215. tool_dia_copy[dia_key] = dia_value
  4216. if dia_key == 'tool_type':
  4217. tool_dia_copy[dia_key] = dia_value
  4218. if dia_key == 'data':
  4219. for data_key, data_value in dia_value.items():
  4220. # convert the form fields that are convertible
  4221. for param in param_list:
  4222. if data_key == param and data_value is not None:
  4223. data_copy[data_key] = data_value * factor
  4224. # copy the other dict entries that are not convertible
  4225. if data_key not in param_list:
  4226. data_copy[data_key] = data_value
  4227. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4228. data_copy.clear()
  4229. temp_tools_dict.update({
  4230. tooluid_key: deepcopy(tool_dia_copy)
  4231. })
  4232. tool_dia_copy.clear()
  4233. self.tools.clear()
  4234. self.tools = deepcopy(temp_tools_dict)
  4235. # if there is a value in the new tool field then convert that one too
  4236. tooldia = self.ui.addtool_entry.get_value()
  4237. if tooldia:
  4238. tooldia *= factor
  4239. # limit the decimals to 2 for METRIC and 3 for INCH
  4240. if units.lower() == 'in':
  4241. tooldia = float('%.4f' % tooldia)
  4242. else:
  4243. tooldia = float('%.2f' % tooldia)
  4244. self.ui.addtool_entry.set_value(tooldia)
  4245. return factor
  4246. def plot_element(self, element, color='red', visible=None):
  4247. visible = visible if visible else self.options['plot']
  4248. try:
  4249. for sub_el in element:
  4250. self.plot_element(sub_el)
  4251. except TypeError: # Element is not iterable...
  4252. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4253. def plot(self, visible=None, kind=None):
  4254. """
  4255. Plot the object.
  4256. :param visible: Controls if the added shape is visible of not
  4257. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4258. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4259. :return:
  4260. """
  4261. # Does all the required setup and returns False
  4262. # if the 'ptint' option is set to False.
  4263. if not FlatCAMObj.plot(self):
  4264. return
  4265. try:
  4266. # plot solid geometries found as members of self.tools attribute dict
  4267. # for MultiGeo
  4268. if self.multigeo == True: # geo multi tool usage
  4269. for tooluid_key in self.tools:
  4270. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4271. self.plot_element(solid_geometry, visible=visible)
  4272. # plot solid geometry that may be an direct attribute of the geometry object
  4273. # for SingleGeo
  4274. if self.solid_geometry:
  4275. self.plot_element(self.solid_geometry, visible=visible)
  4276. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4277. self.shapes.redraw()
  4278. except (ObjectDeleted, AttributeError):
  4279. self.shapes.clear(update=True)
  4280. def on_plot_cb_click(self, *args):
  4281. if self.muted_ui:
  4282. return
  4283. self.plot()
  4284. self.read_form_item('plot')
  4285. self.ui_disconnect()
  4286. cb_flag = self.ui.plot_cb.isChecked()
  4287. for row in range(self.ui.geo_tools_table.rowCount()):
  4288. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4289. if cb_flag:
  4290. table_cb.setChecked(True)
  4291. else:
  4292. table_cb.setChecked(False)
  4293. self.ui_connect()
  4294. def on_plot_cb_click_table(self):
  4295. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4296. self.ui_disconnect()
  4297. cw = self.sender()
  4298. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4299. cw_row = cw_index.row()
  4300. check_row = 0
  4301. self.shapes.clear(update=True)
  4302. for tooluid_key in self.tools:
  4303. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4304. # find the geo_tool_table row associated with the tooluid_key
  4305. for row in range(self.ui.geo_tools_table.rowCount()):
  4306. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4307. if tooluid_item == int(tooluid_key):
  4308. check_row = row
  4309. break
  4310. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4311. self.plot_element(element=solid_geometry, visible=True)
  4312. self.shapes.redraw()
  4313. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4314. # if all the row plot's are enabled also enable the general plot checkbox
  4315. cb_cnt = 0
  4316. total_row = self.ui.geo_tools_table.rowCount()
  4317. for row in range(total_row):
  4318. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4319. cb_cnt += 1
  4320. else:
  4321. cb_cnt -= 1
  4322. if cb_cnt < total_row:
  4323. self.ui.plot_cb.setChecked(False)
  4324. else:
  4325. self.ui.plot_cb.setChecked(True)
  4326. self.ui_connect()
  4327. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4328. """
  4329. Represents G-Code.
  4330. """
  4331. optionChanged = QtCore.pyqtSignal(str)
  4332. ui_type = CNCObjectUI
  4333. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4334. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4335. spindlespeed=None):
  4336. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4337. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4338. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4339. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4340. FlatCAMObj.__init__(self, name)
  4341. self.kind = "cncjob"
  4342. self.options.update({
  4343. "plot": True,
  4344. "tooldia": 0.03937, # 0.4mm in inches
  4345. "append": "",
  4346. "prepend": "",
  4347. "dwell": False,
  4348. "dwelltime": 1,
  4349. "type": 'Geometry',
  4350. "toolchange_macro": '',
  4351. "toolchange_macro_enable": False
  4352. })
  4353. '''
  4354. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4355. diameter of the tools and the value is another dict that will hold the data under the following form:
  4356. {tooldia: {
  4357. 'tooluid': 1,
  4358. 'offset': 'Path',
  4359. 'type_item': 'Rough',
  4360. 'tool_type': 'C1',
  4361. 'data': {} # a dict to hold the parameters
  4362. 'gcode': "" # a string with the actual GCODE
  4363. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4364. 'solid_geometry': []
  4365. },
  4366. ...
  4367. }
  4368. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  4369. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4370. '''
  4371. self.cnc_tools = {}
  4372. '''
  4373. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4374. diameter of the tools and the value is another dict that will hold the data under the following form:
  4375. {tooldia: {
  4376. 'tool': int,
  4377. 'nr_drills': int,
  4378. 'nr_slots': int,
  4379. 'offset': float,
  4380. 'data': {} # a dict to hold the parameters
  4381. 'gcode': "" # a string with the actual GCODE
  4382. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4383. 'solid_geometry': []
  4384. },
  4385. ...
  4386. }
  4387. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  4388. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  4389. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4390. '''
  4391. self.exc_cnc_tools = {}
  4392. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  4393. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  4394. self.special_group = None
  4395. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  4396. # (like the one in the TCL Command), False
  4397. self.multitool = False
  4398. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  4399. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  4400. self.g_x_re = re.compile(gcodex_re_string)
  4401. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  4402. self.g_y_re = re.compile(gcodey_re_string)
  4403. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  4404. self.g_z_re = re.compile(gcodez_re_string)
  4405. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  4406. self.g_f_re = re.compile(gcodef_re_string)
  4407. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  4408. self.g_t_re = re.compile(gcodet_re_string)
  4409. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  4410. self.g_nr_re = re.compile(gcodenr_re_string)
  4411. # Attributes to be included in serialization
  4412. # Always append to it because it carries contents
  4413. # from predecessors.
  4414. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  4415. self.annotation = self.app.plotcanvas.new_text_group()
  4416. def build_ui(self):
  4417. self.ui_disconnect()
  4418. FlatCAMObj.build_ui(self)
  4419. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  4420. if self.cnc_tools:
  4421. self.ui.cnc_tools_table.show()
  4422. else:
  4423. self.ui.cnc_tools_table.hide()
  4424. offset = 0
  4425. tool_idx = 0
  4426. n = len(self.cnc_tools)
  4427. self.ui.cnc_tools_table.setRowCount(n)
  4428. for dia_key, dia_value in self.cnc_tools.items():
  4429. tool_idx += 1
  4430. row_no = tool_idx - 1
  4431. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  4432. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4433. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  4434. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  4435. # There are no tool bits in MM with more than 2 decimals diameter.
  4436. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  4437. if self.units == 'MM':
  4438. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  4439. else:
  4440. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  4441. offset_txt = list(str(dia_value['offset']))
  4442. offset_txt[0] = offset_txt[0].upper()
  4443. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  4444. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  4445. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  4446. id.setFlags(QtCore.Qt.ItemIsEnabled)
  4447. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4448. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4449. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4450. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4451. # hack so the checkbox stay centered in the table cell
  4452. # used this:
  4453. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  4454. # plot_item = QtWidgets.QWidget()
  4455. # checkbox = FCCheckBox()
  4456. # checkbox.setCheckState(QtCore.Qt.Checked)
  4457. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  4458. # qhboxlayout.addWidget(checkbox)
  4459. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  4460. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  4461. plot_item = FCCheckBox()
  4462. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  4463. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  4464. if self.ui.plot_cb.isChecked():
  4465. plot_item.setChecked(True)
  4466. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  4467. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  4468. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  4469. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  4470. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  4471. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  4472. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  4473. # make the diameter column editable
  4474. # for row in range(tool_idx):
  4475. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4476. # QtCore.Qt.ItemIsEnabled)
  4477. for row in range(tool_idx):
  4478. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4479. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4480. self.ui.cnc_tools_table.resizeColumnsToContents()
  4481. self.ui.cnc_tools_table.resizeRowsToContents()
  4482. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4483. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4484. vertical_header.hide()
  4485. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4486. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4487. horizontal_header.setMinimumSectionSize(10)
  4488. horizontal_header.setDefaultSectionSize(70)
  4489. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4490. horizontal_header.resizeSection(0, 20)
  4491. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4492. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4493. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4494. horizontal_header.resizeSection(4, 40)
  4495. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4496. horizontal_header.resizeSection(4, 17)
  4497. # horizontal_header.setStretchLastSection(True)
  4498. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4499. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4500. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4501. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4502. # self.ui.geo_tools_table.setSortingEnabled(True)
  4503. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4504. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4505. self.ui_connect()
  4506. def set_ui(self, ui):
  4507. FlatCAMObj.set_ui(self, ui)
  4508. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4509. assert isinstance(self.ui, CNCObjectUI), \
  4510. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4511. # this signal has to be connected to it's slot before the defaults are populated
  4512. # the decision done in the slot has to override the default value set bellow
  4513. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  4514. self.form_fields.update({
  4515. "plot": self.ui.plot_cb,
  4516. # "tooldia": self.ui.tooldia_entry,
  4517. "append": self.ui.append_text,
  4518. "prepend": self.ui.prepend_text,
  4519. "toolchange_macro": self.ui.toolchange_text,
  4520. "toolchange_macro_enable": self.ui.toolchange_cb
  4521. })
  4522. # Fill form fields only on object create
  4523. self.to_form()
  4524. # this means that the object that created this CNCJob was an Excellon
  4525. try:
  4526. if self.travel_distance:
  4527. self.ui.t_distance_label.show()
  4528. self.ui.t_distance_entry.setVisible(True)
  4529. self.ui.t_distance_entry.setDisabled(True)
  4530. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4531. self.ui.units_label.setText(str(self.units).lower())
  4532. self.ui.units_label.setDisabled(True)
  4533. except AttributeError:
  4534. pass
  4535. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4536. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4537. try:
  4538. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  4539. except:
  4540. pass
  4541. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  4542. # set if to display text annotations
  4543. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  4544. # Show/Hide Advanced Options
  4545. if self.app.defaults["global_app_level"] == 'b':
  4546. self.ui.level.setText(_(
  4547. '<span style="color:green;"><b>Basic</b></span>'
  4548. ))
  4549. self.ui.cnc_frame.hide()
  4550. else:
  4551. self.ui.level.setText(_(
  4552. '<span style="color:red;"><b>Advanced</b></span>'
  4553. ))
  4554. self.ui.cnc_frame.show()
  4555. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4556. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4557. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  4558. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  4559. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4560. def on_cnc_custom_parameters(self, signal_text):
  4561. if signal_text == 'Parameters':
  4562. return
  4563. else:
  4564. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4565. def ui_connect(self):
  4566. for row in range(self.ui.cnc_tools_table.rowCount()):
  4567. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4568. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4569. def ui_disconnect(self):
  4570. for row in range(self.ui.cnc_tools_table.rowCount()):
  4571. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4572. try:
  4573. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4574. except:
  4575. pass
  4576. def on_updateplot_button_click(self, *args):
  4577. """
  4578. Callback for the "Updata Plot" button. Reads the form for updates
  4579. and plots the object.
  4580. """
  4581. self.read_form()
  4582. self.plot()
  4583. def on_plot_kind_change(self):
  4584. kind = self.ui.cncplot_method_combo.get_value()
  4585. self.plot(kind=kind)
  4586. def on_exportgcode_button_click(self, *args):
  4587. self.app.report_usage("cncjob_on_exportgcode_button")
  4588. self.read_form()
  4589. name = self.app.collection.get_active().options['name']
  4590. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4591. _filter_ = "RML1 Files (*.rol);;" \
  4592. "All Files (*.*)"
  4593. elif 'hpgl' in self.pp_geometry_name:
  4594. _filter_ = "HPGL Files (*.plt);;" \
  4595. "All Files (*.*)"
  4596. else:
  4597. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4598. "G-Code Files (*.g-code);;All Files (*.*)"
  4599. try:
  4600. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4601. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4602. caption=_("Export Machine Code ..."),
  4603. directory=dir_file_to_save,
  4604. filter=_filter_
  4605. )
  4606. except TypeError:
  4607. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  4608. filename = str(filename)
  4609. if filename == '':
  4610. self.app.inform.emit(_(
  4611. "[WARNING_NOTCL] Export Machine Code cancelled ..."))
  4612. return
  4613. preamble = str(self.ui.prepend_text.get_value())
  4614. postamble = str(self.ui.append_text.get_value())
  4615. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4616. if gc == 'fail':
  4617. return
  4618. if self.app.defaults["global_open_style"] is False:
  4619. self.app.file_opened.emit("gcode", filename)
  4620. self.app.file_saved.emit("gcode", filename)
  4621. self.app.inform.emit(_("[success] Machine Code file saved to: %s") % filename)
  4622. def on_edit_code_click(self, *args):
  4623. preamble = str(self.ui.prepend_text.get_value())
  4624. postamble = str(self.ui.append_text.get_value())
  4625. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4626. if gc == 'fail':
  4627. return
  4628. else:
  4629. self.app.gcode_edited = gc
  4630. self.app.init_code_editor(name=_("Code Editor"))
  4631. self.app.ui.buttonOpen.clicked.connect(self.app.handleOpen)
  4632. self.app.ui.buttonSave.clicked.connect(self.app.handleSaveGCode)
  4633. # then append the text from GCode to the text editor
  4634. try:
  4635. for line in self.app.gcode_edited:
  4636. proc_line = str(line).strip('\n')
  4637. self.app.ui.code_editor.append(proc_line)
  4638. except Exception as e:
  4639. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  4640. self.app.inform.emit(_('[ERROR]FlatCAMCNNJob.on_edit_code_click() -->%s') % str(e))
  4641. return
  4642. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4643. self.app.handleTextChanged()
  4644. self.app.ui.show()
  4645. def gcode_header(self):
  4646. log.debug("FlatCAMCNCJob.gcode_header()")
  4647. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4648. marlin = False
  4649. hpgl = False
  4650. probe_pp = False
  4651. try:
  4652. for key in self.cnc_tools:
  4653. ppg = self.cnc_tools[key]['data']['ppname_g']
  4654. if ppg == 'marlin' or ppg == 'Repetier':
  4655. marlin = True
  4656. break
  4657. if ppg == 'hpgl':
  4658. hpgl = True
  4659. break
  4660. if "toolchange_probe" in ppg.lower():
  4661. probe_pp = True
  4662. break
  4663. except Exception as e:
  4664. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4665. try:
  4666. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4667. marlin = True
  4668. except Exception as e:
  4669. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4670. try:
  4671. if "toolchange_probe" in self.options['ppname_e'].lower():
  4672. probe_pp = True
  4673. except Exception as e:
  4674. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4675. if marlin is True:
  4676. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4677. (str(self.app.version), str(self.app.version_date)) + '\n'
  4678. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4679. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4680. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4681. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4682. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4683. gcode += ';Created on ' + time_str + '\n' + '\n'
  4684. elif hpgl is True:
  4685. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4686. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4687. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4688. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4689. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4690. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4691. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4692. gcode += 'CO "Created on ' + time_str + '";\n'
  4693. elif probe_pp is True:
  4694. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4695. (str(self.app.version), str(self.app.version_date)) + '\n'
  4696. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4697. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4698. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4699. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4700. 'Then zero the Z axis.)\n' + '\n'
  4701. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4702. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4703. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4704. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4705. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4706. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4707. else:
  4708. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4709. (str(self.app.version), str(self.app.version_date)) + '\n'
  4710. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4711. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4712. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4713. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4714. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4715. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4716. return gcode
  4717. def gcode_footer(self, end_command=None):
  4718. """
  4719. :param end_command: 'M02' or 'M30' - String
  4720. :return:
  4721. """
  4722. if end_command:
  4723. return end_command
  4724. else:
  4725. return 'M02'
  4726. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4727. gcode = ''
  4728. roland = False
  4729. hpgl = False
  4730. try:
  4731. if self.special_group:
  4732. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed because "
  4733. "it is a %s CNCJob object.") % str(self.special_group))
  4734. return 'fail'
  4735. except AttributeError:
  4736. pass
  4737. # detect if using Roland postprocessor
  4738. try:
  4739. for key in self.cnc_tools:
  4740. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4741. roland = True
  4742. break
  4743. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4744. hpgl = True
  4745. break
  4746. except:
  4747. try:
  4748. for key in self.cnc_tools:
  4749. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4750. roland = True
  4751. break
  4752. except:
  4753. pass
  4754. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4755. if roland is False and hpgl is False:
  4756. gcode = self.gcode_header()
  4757. # detect if using multi-tool and make the Gcode summation correctly for each case
  4758. if self.multitool is True:
  4759. for tooluid_key in self.cnc_tools:
  4760. for key, value in self.cnc_tools[tooluid_key].items():
  4761. if key == 'gcode':
  4762. gcode += value
  4763. break
  4764. else:
  4765. gcode += self.gcode
  4766. if roland is True:
  4767. g = preamble + gcode + postamble
  4768. elif hpgl is True:
  4769. g = self.gcode_header() + preamble + gcode + postamble
  4770. else:
  4771. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4772. g_idx = gcode.rfind('G20')
  4773. # if it did not find 'G20' then search for 'G21'
  4774. if g_idx == -1:
  4775. g_idx = gcode.rfind('G21')
  4776. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4777. if g_idx == -1:
  4778. self.app.inform.emit(_(
  4779. "[ERROR_NOTCL] G-code does not have a units code: either G20 or G21"
  4780. ))
  4781. return
  4782. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + self.gcode_footer()
  4783. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  4784. if self.ui.toolchange_cb.get_value() is True:
  4785. # match = self.re_toolchange.search(g)
  4786. if 'M6' in g:
  4787. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  4788. if m6_code is None or m6_code == '':
  4789. self.app.inform.emit(_(
  4790. "[ERROR_NOTCL] Cancelled. The Toolchange Custom code is enabled "
  4791. "but it's empty."
  4792. ))
  4793. return 'fail'
  4794. g = g.replace('M6', m6_code)
  4795. self.app.inform.emit(_(
  4796. "[success] Toolchange G-code was replaced by a custom code."
  4797. ))
  4798. # lines = StringIO(self.gcode)
  4799. lines = StringIO(g)
  4800. # Write
  4801. if filename is not None:
  4802. try:
  4803. with open(filename, 'w') as f:
  4804. for line in lines:
  4805. f.write(line)
  4806. except FileNotFoundError:
  4807. self.app.inform.emit(_(
  4808. "[WARNING_NOTCL] No such file or directory"
  4809. ))
  4810. return
  4811. elif to_file is False:
  4812. # Just for adding it to the recent files list.
  4813. if self.app.defaults["global_open_style"] is False:
  4814. self.app.file_opened.emit("cncjob", filename)
  4815. self.app.file_saved.emit("cncjob", filename)
  4816. self.app.inform.emit("[success] Saved to: " + filename)
  4817. else:
  4818. return lines
  4819. def on_toolchange_custom_clicked(self, signal):
  4820. try:
  4821. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  4822. if self.ui.toolchange_cb.get_value():
  4823. self.ui.toolchange_cb.set_value(False)
  4824. self.app.inform.emit(
  4825. _(
  4826. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: 'toolchange_custom'"
  4827. ))
  4828. except KeyError:
  4829. try:
  4830. for key in self.cnc_tools:
  4831. ppg = self.cnc_tools[key]['data']['ppname_g']
  4832. if 'toolchange_custom' not in str(ppg).lower():
  4833. print(ppg)
  4834. if self.ui.toolchange_cb.get_value():
  4835. self.ui.toolchange_cb.set_value(False)
  4836. self.app.inform.emit(
  4837. _(
  4838. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: "
  4839. "'toolchange_custom'"
  4840. ))
  4841. except KeyError:
  4842. self.app.inform.emit(
  4843. _(
  4844. "[ERROR] There is no postprocessor file."
  4845. ))
  4846. def get_gcode(self, preamble='', postamble=''):
  4847. #we need this to be able get_gcode separatelly for shell command export_gcode
  4848. return preamble + '\n' + self.gcode + "\n" + postamble
  4849. def get_svg(self):
  4850. # we need this to be able get_svg separately for shell command export_svg
  4851. pass
  4852. def on_plot_cb_click(self, *args):
  4853. if self.muted_ui:
  4854. return
  4855. kind = self.ui.cncplot_method_combo.get_value()
  4856. self.plot(kind=kind)
  4857. self.read_form_item('plot')
  4858. self.ui_disconnect()
  4859. cb_flag = self.ui.plot_cb.isChecked()
  4860. for row in range(self.ui.cnc_tools_table.rowCount()):
  4861. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4862. if cb_flag:
  4863. table_cb.setChecked(True)
  4864. else:
  4865. table_cb.setChecked(False)
  4866. self.ui_connect()
  4867. def on_plot_cb_click_table(self):
  4868. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4869. self.ui_disconnect()
  4870. cw = self.sender()
  4871. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4872. cw_row = cw_index.row()
  4873. kind = self.ui.cncplot_method_combo.get_value()
  4874. self.shapes.clear(update=True)
  4875. for tooluid_key in self.cnc_tools:
  4876. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4877. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4878. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4879. for r in range(self.ui.cnc_tools_table.rowCount()):
  4880. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4881. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4882. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4883. self.shapes.redraw()
  4884. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4885. # if all the row plot's are enabled also enable the general plot checkbox
  4886. cb_cnt = 0
  4887. total_row = self.ui.cnc_tools_table.rowCount()
  4888. for row in range(total_row):
  4889. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4890. cb_cnt += 1
  4891. else:
  4892. cb_cnt -= 1
  4893. if cb_cnt < total_row:
  4894. self.ui.plot_cb.setChecked(False)
  4895. else:
  4896. self.ui.plot_cb.setChecked(True)
  4897. self.ui_connect()
  4898. def plot(self, visible=None, kind='all'):
  4899. # Does all the required setup and returns False
  4900. # if the 'ptint' option is set to False.
  4901. if not FlatCAMObj.plot(self):
  4902. return
  4903. visible = visible if visible else self.options['plot']
  4904. try:
  4905. if self.multitool is False: # single tool usage
  4906. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4907. else:
  4908. # multiple tools usage
  4909. for tooluid_key in self.cnc_tools:
  4910. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4911. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4912. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4913. self.shapes.redraw()
  4914. except (ObjectDeleted, AttributeError):
  4915. self.shapes.clear(update=True)
  4916. self.annotation.clear(update=True)
  4917. def on_annotation_change(self):
  4918. if self.ui.annotation_cb.get_value():
  4919. self.app.plotcanvas.text_collection.enabled = True
  4920. else:
  4921. self.app.plotcanvas.text_collection.enabled = False
  4922. kind = self.ui.cncplot_method_combo.get_value()
  4923. self.plot(kind=kind)
  4924. def convert_units(self, units):
  4925. factor = CNCjob.convert_units(self, units)
  4926. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4927. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4928. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4929. 'endz', 'toolchangez']
  4930. temp_tools_dict = {}
  4931. tool_dia_copy = {}
  4932. data_copy = {}
  4933. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4934. for dia_key, dia_value in tooluid_value.items():
  4935. if dia_key == 'tooldia':
  4936. dia_value *= factor
  4937. dia_value = float('%.4f' % dia_value)
  4938. tool_dia_copy[dia_key] = dia_value
  4939. if dia_key == 'offset':
  4940. tool_dia_copy[dia_key] = dia_value
  4941. if dia_key == 'offset_value':
  4942. dia_value *= factor
  4943. tool_dia_copy[dia_key] = dia_value
  4944. if dia_key == 'type':
  4945. tool_dia_copy[dia_key] = dia_value
  4946. if dia_key == 'tool_type':
  4947. tool_dia_copy[dia_key] = dia_value
  4948. if dia_key == 'data':
  4949. for data_key, data_value in dia_value.items():
  4950. # convert the form fields that are convertible
  4951. for param in param_list:
  4952. if data_key == param and data_value is not None:
  4953. data_copy[data_key] = data_value * factor
  4954. # copy the other dict entries that are not convertible
  4955. if data_key not in param_list:
  4956. data_copy[data_key] = data_value
  4957. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4958. data_copy.clear()
  4959. if dia_key == 'gcode':
  4960. tool_dia_copy[dia_key] = dia_value
  4961. if dia_key == 'gcode_parsed':
  4962. tool_dia_copy[dia_key] = dia_value
  4963. if dia_key == 'solid_geometry':
  4964. tool_dia_copy[dia_key] = dia_value
  4965. # if dia_key == 'solid_geometry':
  4966. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4967. # if dia_key == 'gcode_parsed':
  4968. # for g in dia_value:
  4969. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4970. #
  4971. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  4972. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4973. temp_tools_dict.update({
  4974. tooluid_key: deepcopy(tool_dia_copy)
  4975. })
  4976. tool_dia_copy.clear()
  4977. self.cnc_tools.clear()
  4978. self.cnc_tools = deepcopy(temp_tools_dict)
  4979. # end of file