FlatCAMObj.py 249 KB

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