FlatCAMObj.py 235 KB

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