FlatCAMObj.py 237 KB

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