FlatCAMObj.py 236 KB

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