FlatCAMObj.py 223 KB

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