FlatCAMObj.py 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277
  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_advanced"] is False:
  392. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</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 Mode</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_advanced"] is False:
  1288. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</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 Mode</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. self.multigeo = False
  2086. # Attributes to be included in serialization
  2087. # Always append to it because it carries contents
  2088. # from predecessors.
  2089. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2090. def build_ui(self):
  2091. self.ui_disconnect()
  2092. FlatCAMObj.build_ui(self)
  2093. offset = 0
  2094. tool_idx = 0
  2095. n = len(self.tools)
  2096. self.ui.geo_tools_table.setRowCount(n)
  2097. for tooluid_key, tooluid_value in self.tools.items():
  2098. tool_idx += 1
  2099. row_no = tool_idx - 1
  2100. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2101. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2102. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2103. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2104. # There are no tool bits in MM with more than 3 decimals diameter.
  2105. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2106. if self.units == 'MM':
  2107. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2108. else:
  2109. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2110. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2111. offset_item = QtWidgets.QComboBox()
  2112. for item in self.offset_item_options:
  2113. offset_item.addItem(item)
  2114. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2115. idx = offset_item.findText(tooluid_value['offset'])
  2116. offset_item.setCurrentIndex(idx)
  2117. type_item = QtWidgets.QComboBox()
  2118. for item in self.type_item_options:
  2119. type_item.addItem(item)
  2120. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2121. idx = type_item.findText(tooluid_value['type'])
  2122. type_item.setCurrentIndex(idx)
  2123. tool_type_item = QtWidgets.QComboBox()
  2124. for item in self.tool_type_item_options:
  2125. tool_type_item.addItem(item)
  2126. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2127. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2128. tool_type_item.setCurrentIndex(idx)
  2129. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2130. plot_item = FCCheckBox()
  2131. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2132. if self.ui.plot_cb.isChecked():
  2133. plot_item.setChecked(True)
  2134. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2135. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2136. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2137. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2138. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  2139. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2140. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2141. try:
  2142. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2143. except:
  2144. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2145. # make the diameter column editable
  2146. for row in range(tool_idx):
  2147. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2148. QtCore.Qt.ItemIsEditable |
  2149. QtCore.Qt.ItemIsEnabled)
  2150. # sort the tool diameter column
  2151. # self.ui.geo_tools_table.sortItems(1)
  2152. # all the tools are selected by default
  2153. # self.ui.geo_tools_table.selectColumn(0)
  2154. self.ui.geo_tools_table.resizeColumnsToContents()
  2155. self.ui.geo_tools_table.resizeRowsToContents()
  2156. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2157. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2158. vertical_header.hide()
  2159. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2160. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2161. horizontal_header.setMinimumSectionSize(10)
  2162. horizontal_header.setDefaultSectionSize(70)
  2163. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2164. horizontal_header.resizeSection(0, 20)
  2165. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2166. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2167. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2168. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2169. horizontal_header.resizeSection(4, 40)
  2170. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2171. horizontal_header.resizeSection(4, 17)
  2172. # horizontal_header.setStretchLastSection(True)
  2173. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2174. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2175. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2176. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2177. # self.ui.geo_tools_table.setSortingEnabled(True)
  2178. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2179. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2180. # update UI for all rows - useful after units conversion but only if there is at least one row
  2181. row_cnt = self.ui.geo_tools_table.rowCount()
  2182. if row_cnt > 0:
  2183. for r in range(row_cnt):
  2184. self.update_ui(r)
  2185. # select only the first tool / row
  2186. selected_row = 0
  2187. try:
  2188. self.select_tools_table_row(selected_row, clearsel=True)
  2189. # update the Geometry UI
  2190. self.update_ui()
  2191. except Exception as e:
  2192. # when the tools table is empty there will be this error but once the table is populated it will go away
  2193. log.debug(str(e))
  2194. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2195. # and can create some problems
  2196. if self.multigeo is False:
  2197. self.ui.geo_tools_table.setColumnHidden(6, True)
  2198. else:
  2199. self.ui.geo_tools_table.setColumnHidden(6, False)
  2200. self.set_tool_offset_visibility(selected_row)
  2201. self.ui_connect()
  2202. def set_ui(self, ui):
  2203. FlatCAMObj.set_ui(self, ui)
  2204. log.debug("FlatCAMGeometry.set_ui()")
  2205. assert isinstance(self.ui, GeometryObjectUI), \
  2206. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2207. # populate postprocessor names in the combobox
  2208. for name in list(self.app.postprocessors.keys()):
  2209. self.ui.pp_geometry_name_cb.addItem(name)
  2210. self.form_fields.update({
  2211. "plot": self.ui.plot_cb,
  2212. "cutz": self.ui.cutz_entry,
  2213. "vtipdia": self.ui.tipdia_entry,
  2214. "vtipangle": self.ui.tipangle_entry,
  2215. "travelz": self.ui.travelz_entry,
  2216. "feedrate": self.ui.cncfeedrate_entry,
  2217. "feedrate_z": self.ui.cncplunge_entry,
  2218. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2219. "spindlespeed": self.ui.cncspindlespeed_entry,
  2220. "dwell": self.ui.dwell_cb,
  2221. "dwelltime": self.ui.dwelltime_entry,
  2222. "multidepth": self.ui.mpass_cb,
  2223. "ppname_g": self.ui.pp_geometry_name_cb,
  2224. "z_pdepth": self.ui.pdepth_entry,
  2225. "feedrate_probe": self.ui.feedrate_probe_entry,
  2226. "depthperpass": self.ui.maxdepth_entry,
  2227. "extracut": self.ui.extracut_cb,
  2228. "toolchange": self.ui.toolchangeg_cb,
  2229. "toolchangez": self.ui.toolchangez_entry,
  2230. "endz": self.ui.gendz_entry,
  2231. })
  2232. # Fill form fields only on object create
  2233. self.to_form()
  2234. self.ui.tipdialabel.hide()
  2235. self.ui.tipdia_entry.hide()
  2236. self.ui.tipanglelabel.hide()
  2237. self.ui.tipangle_entry.hide()
  2238. self.ui.cutz_entry.setDisabled(False)
  2239. # store here the default data for Geometry Data
  2240. self.default_data = {}
  2241. self.default_data.update({
  2242. "name": None,
  2243. "plot": None,
  2244. "cutz": None,
  2245. "vtipdia": None,
  2246. "vtipangle": None,
  2247. "travelz": None,
  2248. "feedrate": None,
  2249. "feedrate_z": None,
  2250. "feedrate_rapid": None,
  2251. "dwell": None,
  2252. "dwelltime": None,
  2253. "multidepth": None,
  2254. "ppname_g": None,
  2255. "depthperpass": None,
  2256. "extracut": None,
  2257. "toolchange": None,
  2258. "toolchangez": None,
  2259. "endz": None,
  2260. "spindlespeed": None,
  2261. "toolchangexy": None,
  2262. "startz": None
  2263. })
  2264. # fill in self.default_data values from self.options
  2265. for def_key in self.default_data:
  2266. for opt_key, opt_val in self.options.items():
  2267. if def_key == opt_key:
  2268. self.default_data[def_key] = opt_val
  2269. self.tooluid += 1
  2270. if not self.tools:
  2271. self.tools.update({
  2272. self.tooluid: {
  2273. 'tooldia': float(self.options["cnctooldia"]),
  2274. 'offset': 'Path',
  2275. 'offset_value': 0.0,
  2276. 'type': 'Rough',
  2277. 'tool_type': 'C1',
  2278. 'data': self.default_data,
  2279. 'solid_geometry': self.solid_geometry
  2280. }
  2281. })
  2282. else:
  2283. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2284. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2285. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2286. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2287. # following convoluted way of changing the keys from string to float type
  2288. temp_tools = {}
  2289. new_key = 0.0
  2290. for tooluid_key in self.tools:
  2291. val = copy.deepcopy(self.tools[tooluid_key])
  2292. new_key = copy.deepcopy(int(tooluid_key))
  2293. temp_tools[new_key] = val
  2294. self.tools.clear()
  2295. self.tools = copy.deepcopy(temp_tools)
  2296. self.ui.tool_offset_entry.hide()
  2297. self.ui.tool_offset_lbl.hide()
  2298. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2299. self.old_pp_state = self.default_data['multidepth']
  2300. self.old_toolchangeg_state = self.default_data['toolchange']
  2301. if not isinstance(self.ui, GeometryObjectUI):
  2302. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2303. return
  2304. self.ui.geo_tools_table.setupContextMenu()
  2305. self.ui.geo_tools_table.addContextMenu(
  2306. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2307. self.ui.geo_tools_table.addContextMenu(
  2308. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2309. # Show/Hide Advanced Options
  2310. if self.app.defaults["global_advanced"] is False:
  2311. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  2312. self.ui.geo_tools_table.setColumnHidden(2, True)
  2313. self.ui.geo_tools_table.setColumnHidden(3, True)
  2314. self.ui.geo_tools_table.setColumnHidden(4, True)
  2315. self.ui.addtool_entry_lbl.hide()
  2316. self.ui.addtool_entry.hide()
  2317. self.ui.addtool_btn.hide()
  2318. self.ui.copytool_btn.hide()
  2319. self.ui.deltool_btn.hide()
  2320. self.ui.endzlabel.hide()
  2321. self.ui.gendz_entry.hide()
  2322. self.ui.fr_rapidlabel.hide()
  2323. self.ui.cncfeedrate_rapid_entry.hide()
  2324. self.ui.extracut_cb.hide()
  2325. self.ui.pdepth_label.hide()
  2326. self.ui.pdepth_entry.hide()
  2327. self.ui.feedrate_probe_label.hide()
  2328. self.ui.feedrate_probe_entry.hide()
  2329. else:
  2330. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  2331. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2332. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2333. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  2334. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2335. def set_tool_offset_visibility(self, current_row):
  2336. if current_row is None:
  2337. return
  2338. try:
  2339. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2340. if tool_offset is not None:
  2341. tool_offset_txt = tool_offset.currentText()
  2342. if tool_offset_txt == 'Custom':
  2343. self.ui.tool_offset_entry.show()
  2344. self.ui.tool_offset_lbl.show()
  2345. else:
  2346. self.ui.tool_offset_entry.hide()
  2347. self.ui.tool_offset_lbl.hide()
  2348. except Exception as e:
  2349. log.debug("set_tool_offset_visibility() --> " + str(e))
  2350. return
  2351. def on_offset_value_edited(self):
  2352. '''
  2353. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2354. :return:
  2355. '''
  2356. for current_row in self.ui.geo_tools_table.selectedItems():
  2357. # sometime the header get selected and it has row number -1
  2358. # we don't want to do anything with the header :)
  2359. if current_row.row() < 0:
  2360. continue
  2361. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2362. self.set_tool_offset_visibility(current_row.row())
  2363. for tooluid_key, tooluid_value in self.tools.items():
  2364. if int(tooluid_key) == tool_uid:
  2365. try:
  2366. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2367. except ValueError:
  2368. # try to convert comma to decimal point. if it's still not working error message and return
  2369. try:
  2370. tooluid_value['offset_value'] = float(
  2371. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2372. )
  2373. except ValueError:
  2374. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2375. "use a number.")
  2376. return
  2377. def ui_connect(self):
  2378. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2379. # changes in geometry UI
  2380. for i in range(self.ui.grid3.count()):
  2381. try:
  2382. # works for CheckBoxes
  2383. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2384. except:
  2385. # works for ComboBoxes
  2386. try:
  2387. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2388. except:
  2389. # works for Entry
  2390. try:
  2391. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2392. except:
  2393. pass
  2394. for row in range(self.ui.geo_tools_table.rowCount()):
  2395. for col in [2, 3, 4]:
  2396. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2397. self.on_tooltable_cellwidget_change)
  2398. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2399. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2400. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2401. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2402. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2403. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2404. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2405. for row in range(self.ui.geo_tools_table.rowCount()):
  2406. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2407. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2408. def ui_disconnect(self):
  2409. try:
  2410. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2411. # changes in geometry UI
  2412. for i in range(self.ui.grid3.count()):
  2413. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2414. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2415. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2416. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2417. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2418. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  2419. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  2420. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2421. except:
  2422. pass
  2423. try:
  2424. for row in range(self.ui.geo_tools_table.rowCount()):
  2425. for col in [2, 3, 4]:
  2426. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2427. except:
  2428. pass
  2429. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2430. try:
  2431. self.ui.addtool_btn.clicked.disconnect()
  2432. except:
  2433. pass
  2434. try:
  2435. self.ui.copytool_btn.clicked.disconnect()
  2436. except:
  2437. pass
  2438. try:
  2439. self.ui.deltool_btn.clicked.disconnect()
  2440. except:
  2441. pass
  2442. try:
  2443. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2444. except:
  2445. pass
  2446. try:
  2447. self.ui.geo_tools_table.itemChanged.disconnect()
  2448. except:
  2449. pass
  2450. try:
  2451. self.ui.tool_offset_entry.editingFinished.disconnect()
  2452. except:
  2453. pass
  2454. for row in range(self.ui.geo_tools_table.rowCount()):
  2455. try:
  2456. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2457. except:
  2458. pass
  2459. try:
  2460. self.ui.plot_cb.stateChanged.disconnect()
  2461. except:
  2462. pass
  2463. def on_tool_add(self, dia=None):
  2464. self.ui_disconnect()
  2465. last_offset = None
  2466. last_offset_value = None
  2467. last_type = None
  2468. last_tool_type = None
  2469. last_data = None
  2470. last_solid_geometry = []
  2471. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2472. # because the Default value for Tool is used.
  2473. change_message = False
  2474. if dia is not None:
  2475. tooldia = dia
  2476. else:
  2477. try:
  2478. tooldia = float(self.ui.addtool_entry.get_value())
  2479. except ValueError:
  2480. # try to convert comma to decimal point. if it's still not working error message and return
  2481. try:
  2482. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2483. except ValueError:
  2484. change_message = True
  2485. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2486. if tooldia is None:
  2487. self.build_ui()
  2488. self.app.inform.emit("[ERROR_NOTCL] Please enter the desired tool diameter in Float format.")
  2489. return
  2490. # construct a list of all 'tooluid' in the self.tools
  2491. tool_uid_list = []
  2492. for tooluid_key in self.tools:
  2493. tool_uid_item = int(tooluid_key)
  2494. tool_uid_list.append(tool_uid_item)
  2495. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2496. if not tool_uid_list:
  2497. max_uid = 0
  2498. else:
  2499. max_uid = max(tool_uid_list)
  2500. self.tooluid = max_uid + 1
  2501. if self.units == 'IN':
  2502. tooldia = float('%.4f' % tooldia)
  2503. else:
  2504. tooldia = float('%.2f' % tooldia)
  2505. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2506. # otherwise we add a tool with data copied from last tool
  2507. if not self.tools:
  2508. self.tools.update({
  2509. self.tooluid: {
  2510. 'tooldia': tooldia,
  2511. 'offset': 'Path',
  2512. 'offset_value': 0.0,
  2513. 'type': 'Rough',
  2514. 'tool_type': 'C1',
  2515. 'data': copy.deepcopy(self.default_data),
  2516. 'solid_geometry': self.solid_geometry
  2517. }
  2518. })
  2519. else:
  2520. # print("LAST", self.tools[maxuid])
  2521. last_data = self.tools[max_uid]['data']
  2522. last_offset = self.tools[max_uid]['offset']
  2523. last_offset_value = self.tools[max_uid]['offset_value']
  2524. last_type = self.tools[max_uid]['type']
  2525. last_tool_type = self.tools[max_uid]['tool_type']
  2526. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2527. # if previous geometry was empty (it may happen for the first tool added)
  2528. # then copy the object.solid_geometry
  2529. if not last_solid_geometry:
  2530. last_solid_geometry = self.solid_geometry
  2531. self.tools.update({
  2532. self.tooluid: {
  2533. 'tooldia': tooldia,
  2534. 'offset': last_offset,
  2535. 'offset_value': last_offset_value,
  2536. 'type': last_type,
  2537. 'tool_type': last_tool_type,
  2538. 'data': copy.deepcopy(last_data),
  2539. 'solid_geometry': copy.deepcopy(last_solid_geometry)
  2540. }
  2541. })
  2542. # print("CURRENT", self.tools[-1])
  2543. self.ui.tool_offset_entry.hide()
  2544. self.ui.tool_offset_lbl.hide()
  2545. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2546. try:
  2547. self.ser_attrs.remove('tools')
  2548. except:
  2549. pass
  2550. self.ser_attrs.append('tools')
  2551. if change_message is False:
  2552. self.app.inform.emit("[success] Tool added in Tool Table.")
  2553. else:
  2554. change_message = False
  2555. self.app.inform.emit("[ERROR_NOTCL]Default Tool added. Wrong value format entered.")
  2556. self.build_ui()
  2557. def on_tool_copy(self, all=None):
  2558. self.ui_disconnect()
  2559. # find the tool_uid maximum value in the self.tools
  2560. uid_list = []
  2561. for key in self.tools:
  2562. uid_list.append(int(key))
  2563. try:
  2564. max_uid = max(uid_list, key=int)
  2565. except ValueError:
  2566. max_uid = 0
  2567. if all is None:
  2568. if self.ui.geo_tools_table.selectedItems():
  2569. for current_row in self.ui.geo_tools_table.selectedItems():
  2570. # sometime the header get selected and it has row number -1
  2571. # we don't want to do anything with the header :)
  2572. if current_row.row() < 0:
  2573. continue
  2574. try:
  2575. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2576. self.set_tool_offset_visibility(current_row.row())
  2577. max_uid += 1
  2578. self.tools[int(max_uid)] = copy.deepcopy(self.tools[tooluid_copy])
  2579. except AttributeError:
  2580. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2581. self.build_ui()
  2582. return
  2583. except Exception as e:
  2584. log.debug("on_tool_copy() --> " + str(e))
  2585. # deselect the table
  2586. # self.ui.geo_tools_table.clearSelection()
  2587. else:
  2588. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2589. self.build_ui()
  2590. return
  2591. else:
  2592. # we copy all tools in geo_tools_table
  2593. try:
  2594. temp_tools = copy.deepcopy(self.tools)
  2595. max_uid += 1
  2596. for tooluid in temp_tools:
  2597. self.tools[int(max_uid)] = copy.deepcopy(temp_tools[tooluid])
  2598. temp_tools.clear()
  2599. except Exception as e:
  2600. log.debug("on_tool_copy() --> " + str(e))
  2601. # if there are no more tools in geo tools table then hide the tool offset
  2602. if not self.tools:
  2603. self.ui.tool_offset_entry.hide()
  2604. self.ui.tool_offset_lbl.hide()
  2605. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2606. try:
  2607. self.ser_attrs.remove('tools')
  2608. except:
  2609. pass
  2610. self.ser_attrs.append('tools')
  2611. self.build_ui()
  2612. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2613. def on_tool_edit(self, current_item):
  2614. self.ui_disconnect()
  2615. current_row = current_item.row()
  2616. try:
  2617. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  2618. except ValueError:
  2619. # try to convert comma to decimal point. if it's still not working error message and return
  2620. try:
  2621. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  2622. except ValueError:
  2623. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2624. "use a number.")
  2625. return
  2626. tool_dia = float('%.4f' % d)
  2627. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2628. self.tools[tooluid]['tooldia'] = tool_dia
  2629. try:
  2630. self.ser_attrs.remove('tools')
  2631. self.ser_attrs.append('tools')
  2632. except:
  2633. pass
  2634. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2635. self.build_ui()
  2636. def on_tool_delete(self, all=None):
  2637. self.ui_disconnect()
  2638. if all is None:
  2639. if self.ui.geo_tools_table.selectedItems():
  2640. for current_row in self.ui.geo_tools_table.selectedItems():
  2641. # sometime the header get selected and it has row number -1
  2642. # we don't want to do anything with the header :)
  2643. if current_row.row() < 0:
  2644. continue
  2645. try:
  2646. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2647. self.set_tool_offset_visibility(current_row.row())
  2648. temp_tools = copy.deepcopy(self.tools)
  2649. for tooluid_key in self.tools:
  2650. if int(tooluid_key) == tooluid_del:
  2651. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  2652. # as a property of the object otherwise there will be nothing to hold it
  2653. if len(self.tools) == 1:
  2654. self.solid_geometry = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2655. temp_tools.pop(tooluid_del, None)
  2656. self.tools = copy.deepcopy(temp_tools)
  2657. temp_tools.clear()
  2658. except AttributeError:
  2659. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2660. self.build_ui()
  2661. return
  2662. except Exception as e:
  2663. log.debug("on_tool_delete() --> " + str(e))
  2664. # deselect the table
  2665. # self.ui.geo_tools_table.clearSelection()
  2666. else:
  2667. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2668. self.build_ui()
  2669. return
  2670. else:
  2671. # we delete all tools in geo_tools_table
  2672. self.tools.clear()
  2673. self.app.plot_all()
  2674. # if there are no more tools in geo tools table then hide the tool offset
  2675. if not self.tools:
  2676. self.ui.tool_offset_entry.hide()
  2677. self.ui.tool_offset_lbl.hide()
  2678. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2679. try:
  2680. self.ser_attrs.remove('tools')
  2681. except:
  2682. pass
  2683. self.ser_attrs.append('tools')
  2684. self.build_ui()
  2685. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2686. obj_active = self.app.collection.get_active()
  2687. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2688. # we make it back SingleGeo
  2689. if self.ui.geo_tools_table.rowCount() <= 0:
  2690. obj_active.multigeo = False
  2691. obj_active.options['xmin'] = 0
  2692. obj_active.options['ymin'] = 0
  2693. obj_active.options['xmax'] = 0
  2694. obj_active.options['ymax'] = 0
  2695. if obj_active.multigeo is True:
  2696. try:
  2697. xmin, ymin, xmax, ymax = obj_active.bounds()
  2698. obj_active.options['xmin'] = xmin
  2699. obj_active.options['ymin'] = ymin
  2700. obj_active.options['xmax'] = xmax
  2701. obj_active.options['ymax'] = ymax
  2702. except:
  2703. obj_active.options['xmin'] = 0
  2704. obj_active.options['ymin'] = 0
  2705. obj_active.options['xmax'] = 0
  2706. obj_active.options['ymax'] = 0
  2707. def on_row_selection_change(self):
  2708. self.update_ui()
  2709. def update_ui(self, row=None):
  2710. self.ui_disconnect()
  2711. if row is None:
  2712. try:
  2713. current_row = self.ui.geo_tools_table.currentRow()
  2714. except:
  2715. current_row = 0
  2716. else:
  2717. current_row = row
  2718. if current_row < 0:
  2719. current_row = 0
  2720. self.set_tool_offset_visibility(current_row)
  2721. # populate the form with the data from the tool associated with the row parameter
  2722. try:
  2723. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2724. except Exception as e:
  2725. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2726. return
  2727. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2728. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2729. try:
  2730. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2731. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2732. except Exception as e:
  2733. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2734. return
  2735. try:
  2736. # set the form with data from the newly selected tool
  2737. for tooluid_key, tooluid_value in self.tools.items():
  2738. if int(tooluid_key) == tooluid:
  2739. for key, value in tooluid_value.items():
  2740. if key == 'data':
  2741. form_value_storage = tooluid_value[key]
  2742. self.update_form(form_value_storage)
  2743. if key == 'offset_value':
  2744. # update the offset value in the entry even if the entry is hidden
  2745. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2746. if key == 'tool_type' and value == 'V':
  2747. self.update_cutz()
  2748. except Exception as e:
  2749. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2750. self.ui_connect()
  2751. def ui_update_v_shape(self, tool_type_txt):
  2752. if tool_type_txt == 'V':
  2753. self.ui.tipdialabel.show()
  2754. self.ui.tipdia_entry.show()
  2755. self.ui.tipanglelabel.show()
  2756. self.ui.tipangle_entry.show()
  2757. self.ui.cutz_entry.setDisabled(True)
  2758. self.update_cutz()
  2759. else:
  2760. self.ui.tipdialabel.hide()
  2761. self.ui.tipdia_entry.hide()
  2762. self.ui.tipanglelabel.hide()
  2763. self.ui.tipangle_entry.hide()
  2764. self.ui.cutz_entry.setDisabled(False)
  2765. def update_cutz(self):
  2766. try:
  2767. vdia = float(self.ui.tipdia_entry.get_value())
  2768. except ValueError:
  2769. # try to convert comma to decimal point. if it's still not working error message and return
  2770. try:
  2771. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  2772. except ValueError:
  2773. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2774. "use a number.")
  2775. return
  2776. try:
  2777. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2778. except ValueError:
  2779. # try to convert comma to decimal point. if it's still not working error message and return
  2780. try:
  2781. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  2782. except ValueError:
  2783. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2784. "use a number.")
  2785. return
  2786. row = self.ui.geo_tools_table.currentRow()
  2787. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2788. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2789. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2790. new_cutz = float('%.4f' % -new_cutz)
  2791. self.ui.cutz_entry.set_value(new_cutz)
  2792. # store the new CutZ value into storage (self.tools)
  2793. for tooluid_key, tooluid_value in self.tools.items():
  2794. if int(tooluid_key) == tool_uid:
  2795. tooluid_value['data']['cutz'] = new_cutz
  2796. def on_tooltable_cellwidget_change(self):
  2797. cw = self.sender()
  2798. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2799. cw_row = cw_index.row()
  2800. cw_col = cw_index.column()
  2801. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2802. # store the text of the cellWidget that changed it's index in the self.tools
  2803. for tooluid_key, tooluid_value in self.tools.items():
  2804. if int(tooluid_key) == current_uid:
  2805. cb_txt = cw.currentText()
  2806. if cw_col == 2:
  2807. tooluid_value['offset'] = cb_txt
  2808. if cb_txt == 'Custom':
  2809. self.ui.tool_offset_entry.show()
  2810. self.ui.tool_offset_lbl.show()
  2811. else:
  2812. self.ui.tool_offset_entry.hide()
  2813. self.ui.tool_offset_lbl.hide()
  2814. # reset the offset_value in storage self.tools
  2815. tooluid_value['offset_value'] = 0.0
  2816. elif cw_col == 3:
  2817. # force toolpath type as 'Iso' if the tool type is V-Shape
  2818. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2819. tooluid_value['type'] = 'Iso'
  2820. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2821. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2822. else:
  2823. tooluid_value['type'] = cb_txt
  2824. elif cw_col == 4:
  2825. tooluid_value['tool_type'] = cb_txt
  2826. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2827. if cb_txt == 'V':
  2828. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2829. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2830. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2831. def update_form(self, dict_storage):
  2832. for form_key in self.form_fields:
  2833. for storage_key in dict_storage:
  2834. if form_key == storage_key:
  2835. try:
  2836. self.form_fields[form_key].set_value(dict_storage[form_key])
  2837. except Exception as e:
  2838. log.debug(str(e))
  2839. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2840. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2841. self.ui.ois_dwell_geo.on_cb_change()
  2842. self.ui.ois_mpass_geo.on_cb_change()
  2843. self.ui.ois_tcz_geo.on_cb_change()
  2844. def gui_form_to_storage(self):
  2845. self.ui_disconnect()
  2846. widget_changed = self.sender()
  2847. try:
  2848. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2849. except:
  2850. return
  2851. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2852. if widget_idx == 1 or widget_idx == 3:
  2853. self.update_cutz()
  2854. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2855. # ui_diconnect() so I use this 'hack'
  2856. if isinstance(widget_changed, FCCheckBox):
  2857. if widget_changed.text() == 'Multi-Depth:':
  2858. self.ui.ois_mpass_geo.on_cb_change()
  2859. if widget_changed.text() == 'Tool change':
  2860. self.ui.ois_tcz_geo.on_cb_change()
  2861. if widget_changed.text() == 'Dwell:':
  2862. self.ui.ois_dwell_geo.on_cb_change()
  2863. row = self.ui.geo_tools_table.currentRow()
  2864. if row < 0:
  2865. row = 0
  2866. # store all the data associated with the row parameter to the self.tools storage
  2867. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2868. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2869. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2870. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2871. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2872. try:
  2873. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  2874. except ValueError:
  2875. # try to convert comma to decimal point. if it's still not working error message and return
  2876. try:
  2877. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  2878. )
  2879. except ValueError:
  2880. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2881. "use a number.")
  2882. return
  2883. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2884. temp_tools = {}
  2885. temp_dia = {}
  2886. temp_data = {}
  2887. for tooluid_key, tooluid_value in self.tools.items():
  2888. if int(tooluid_key) == tooluid_item:
  2889. for key, value in tooluid_value.items():
  2890. if key == 'tooldia':
  2891. temp_dia[key] = tooldia_item
  2892. # update the 'offset', 'type' and 'tool_type' sections
  2893. if key == 'offset':
  2894. temp_dia[key] = offset_item
  2895. if key == 'type':
  2896. temp_dia[key] = type_item
  2897. if key == 'tool_type':
  2898. temp_dia[key] = tool_type_item
  2899. if key == 'offset_value':
  2900. temp_dia[key] = offset_value_item
  2901. if key == 'data':
  2902. # update the 'data' section
  2903. for data_key in tooluid_value[key].keys():
  2904. for form_key, form_value in self.form_fields.items():
  2905. if form_key == data_key:
  2906. temp_data[data_key] = form_value.get_value()
  2907. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2908. # updated from self.app.defaults
  2909. if data_key not in self.form_fields:
  2910. temp_data[data_key] = value[data_key]
  2911. temp_dia[key] = copy.deepcopy(temp_data)
  2912. temp_data.clear()
  2913. if key == 'solid_geometry':
  2914. temp_dia[key] = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2915. temp_tools[tooluid_key] = copy.deepcopy(temp_dia)
  2916. else:
  2917. temp_tools[tooluid_key] = copy.deepcopy(tooluid_value)
  2918. self.tools.clear()
  2919. self.tools = copy.deepcopy(temp_tools)
  2920. temp_tools.clear()
  2921. self.ui_connect()
  2922. def select_tools_table_row(self, row, clearsel=None):
  2923. if clearsel:
  2924. self.ui.geo_tools_table.clearSelection()
  2925. if self.ui.geo_tools_table.rowCount() > 0:
  2926. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2927. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2928. def export_dxf(self):
  2929. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  2930. dwg = None
  2931. try:
  2932. dwg = ezdxf.new('R2010')
  2933. msp = dwg.modelspace()
  2934. def g2dxf(dxf_space, geo):
  2935. if isinstance(geo, MultiPolygon):
  2936. for poly in geo:
  2937. ext_points = list(poly.exterior.coords)
  2938. dxf_space.add_lwpolyline(ext_points)
  2939. for interior in poly.interiors:
  2940. dxf_space.add_lwpolyline(list(interior.coords))
  2941. if isinstance(geo, Polygon):
  2942. ext_points = list(geo.exterior.coords)
  2943. dxf_space.add_lwpolyline(ext_points)
  2944. for interior in geo.interiors:
  2945. dxf_space.add_lwpolyline(list(interior.coords))
  2946. if isinstance(geo, MultiLineString):
  2947. for line in geo:
  2948. dxf_space.add_lwpolyline(list(line.coords))
  2949. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2950. dxf_space.add_lwpolyline(list(geo.coords))
  2951. multigeo_solid_geometry = []
  2952. if self.multigeo:
  2953. for tool in self.tools:
  2954. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2955. else:
  2956. multigeo_solid_geometry = self.solid_geometry
  2957. for geo in multigeo_solid_geometry:
  2958. if type(geo) == list:
  2959. for g in geo:
  2960. g2dxf(msp, g)
  2961. else:
  2962. g2dxf(msp, geo)
  2963. # points = FlatCAMGeometry.get_pts(geo)
  2964. # msp.add_lwpolyline(points)
  2965. except Exception as e:
  2966. log.debug(str(e))
  2967. return dwg
  2968. def get_selected_tools_table_items(self):
  2969. """
  2970. Returns a list of lists, each list in the list is made out of row elements
  2971. :return: List of table_tools items.
  2972. :rtype: list
  2973. """
  2974. table_tools_items = []
  2975. if self.multigeo:
  2976. for x in self.ui.geo_tools_table.selectedItems():
  2977. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2978. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2979. else:
  2980. for x in self.ui.geo_tools_table.selectedItems():
  2981. r = []
  2982. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  2983. # so we don't read them
  2984. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  2985. # the columns have items that have text but also have items that are widgets
  2986. # for which the text they hold has to be read differently
  2987. try:
  2988. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  2989. except AttributeError:
  2990. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  2991. except:
  2992. pass
  2993. r.append(txt)
  2994. table_tools_items.append(r)
  2995. for item in table_tools_items:
  2996. item[0] = str(item[0])
  2997. return table_tools_items
  2998. def on_pp_changed(self):
  2999. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3000. if current_pp == 'hpgl':
  3001. self.old_pp_state = self.ui.mpass_cb.get_value()
  3002. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3003. self.ui.mpass_cb.set_value(False)
  3004. self.ui.mpass_cb.setDisabled(True)
  3005. self.ui.toolchangeg_cb.set_value(True)
  3006. self.ui.toolchangeg_cb.setDisabled(True)
  3007. else:
  3008. self.ui.mpass_cb.set_value(self.old_pp_state)
  3009. self.ui.mpass_cb.setDisabled(False)
  3010. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3011. self.ui.toolchangeg_cb.setDisabled(False)
  3012. if "toolchange_probe" in current_pp.lower():
  3013. self.ui.pdepth_entry.setVisible(True)
  3014. self.ui.pdepth_label.show()
  3015. self.ui.feedrate_probe_entry.setVisible(True)
  3016. self.ui.feedrate_probe_label.show()
  3017. else:
  3018. self.ui.pdepth_entry.setVisible(False)
  3019. self.ui.pdepth_label.hide()
  3020. self.ui.feedrate_probe_entry.setVisible(False)
  3021. self.ui.feedrate_probe_label.hide()
  3022. def on_generatecnc_button_click(self, *args):
  3023. self.app.report_usage("geometry_on_generatecnc_button")
  3024. self.read_form()
  3025. self.sel_tools = {}
  3026. # test to see if we have tools available in the tool table
  3027. if self.ui.geo_tools_table.selectedItems():
  3028. for x in self.ui.geo_tools_table.selectedItems():
  3029. try:
  3030. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3031. except ValueError:
  3032. # try to convert comma to decimal point. if it's still not working error message and return
  3033. try:
  3034. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3035. except ValueError:
  3036. self.app.inform.emit("[ERROR_NOTCL]Wrong Tool Dia value format entered, "
  3037. "use a number.")
  3038. return
  3039. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3040. for tooluid_key, tooluid_value in self.tools.items():
  3041. if int(tooluid_key) == tooluid:
  3042. self.sel_tools.update({
  3043. tooluid: copy.deepcopy(tooluid_value)
  3044. })
  3045. self.mtool_gen_cncjob()
  3046. self.ui.geo_tools_table.clearSelection()
  3047. elif self.ui.geo_tools_table.rowCount() == 1:
  3048. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3049. for tooluid_key, tooluid_value in self.tools.items():
  3050. if int(tooluid_key) == tooluid:
  3051. self.sel_tools.update({
  3052. tooluid: copy.deepcopy(tooluid_value)
  3053. })
  3054. self.mtool_gen_cncjob()
  3055. self.ui.geo_tools_table.clearSelection()
  3056. else:
  3057. self.app.inform.emit("[ERROR_NOTCL] Failed. No tool selected in the tool table ...")
  3058. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3059. """
  3060. Creates a multi-tool CNCJob out of this Geometry object.
  3061. The actual work is done by the target FlatCAMCNCjob object's
  3062. `generate_from_geometry_2()` method.
  3063. :param z_cut: Cut depth (negative)
  3064. :param z_move: Hight of the tool when travelling (not cutting)
  3065. :param feedrate: Feed rate while cutting on X - Y plane
  3066. :param feedrate_z: Feed rate while cutting on Z plane
  3067. :param feedrate_rapid: Feed rate while moving with rapids
  3068. :param tooldia: Tool diameter
  3069. :param outname: Name of the new object
  3070. :param spindlespeed: Spindle speed (RPM)
  3071. :param ppname_g Name of the postprocessor
  3072. :return: None
  3073. """
  3074. offset_str = ''
  3075. multitool_gcode = ''
  3076. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3077. outname = "%s_%s" % (self.options["name"], 'cnc')
  3078. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3079. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3080. try:
  3081. xmin = self.options['xmin']
  3082. ymin = self.options['ymin']
  3083. xmax = self.options['xmax']
  3084. ymax = self.options['ymax']
  3085. except Exception as e:
  3086. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3087. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  3088. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  3089. msg += traceback.format_exc()
  3090. self.app.inform.emit(msg)
  3091. return
  3092. # Object initialization function for app.new_object()
  3093. # RUNNING ON SEPARATE THREAD!
  3094. def job_init_single_geometry(job_obj, app_obj):
  3095. assert isinstance(job_obj, FlatCAMCNCjob), \
  3096. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3097. # count the tools
  3098. tool_cnt = 0
  3099. dia_cnc_dict = {}
  3100. # this turn on the FlatCAMCNCJob plot for multiple tools
  3101. job_obj.multitool = True
  3102. job_obj.multigeo = False
  3103. job_obj.cnc_tools.clear()
  3104. # job_obj.create_geometry()
  3105. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3106. job_obj.segx = segx
  3107. job_obj.segy = segy
  3108. try:
  3109. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3110. except ValueError:
  3111. # try to convert comma to decimal point. if it's still not working error message and return
  3112. try:
  3113. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3114. except ValueError:
  3115. self.app.inform.emit(
  3116. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3117. try:
  3118. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3119. except ValueError:
  3120. # try to convert comma to decimal point. if it's still not working error message and return
  3121. try:
  3122. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3123. except ValueError:
  3124. self.app.inform.emit(
  3125. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3126. 'or self.options["feedrate_probe"]')
  3127. for tooluid_key in self.sel_tools:
  3128. tool_cnt += 1
  3129. app_obj.progress.emit(20)
  3130. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3131. if diadict_key == 'tooldia':
  3132. tooldia_val = float('%.4f' % float(diadict_value))
  3133. dia_cnc_dict.update({
  3134. diadict_key: tooldia_val
  3135. })
  3136. if diadict_key == 'offset':
  3137. o_val = diadict_value.lower()
  3138. dia_cnc_dict.update({
  3139. diadict_key: o_val
  3140. })
  3141. if diadict_key == 'type':
  3142. t_val = diadict_value
  3143. dia_cnc_dict.update({
  3144. diadict_key: t_val
  3145. })
  3146. if diadict_key == 'tool_type':
  3147. tt_val = diadict_value
  3148. dia_cnc_dict.update({
  3149. diadict_key: tt_val
  3150. })
  3151. if diadict_key == 'data':
  3152. for data_key, data_value in diadict_value.items():
  3153. if data_key == "multidepth":
  3154. multidepth = data_value
  3155. if data_key == "depthperpass":
  3156. depthpercut = data_value
  3157. if data_key == "extracut":
  3158. extracut = data_value
  3159. if data_key == "startz":
  3160. startz = data_value
  3161. if data_key == "endz":
  3162. endz = data_value
  3163. if data_key == "toolchangez":
  3164. toolchangez =data_value
  3165. if data_key == "toolchangexy":
  3166. toolchangexy = data_value
  3167. if data_key == "toolchange":
  3168. toolchange = data_value
  3169. if data_key == "cutz":
  3170. z_cut = data_value
  3171. if data_key == "travelz":
  3172. z_move = data_value
  3173. if data_key == "feedrate":
  3174. feedrate = data_value
  3175. if data_key == "feedrate_z":
  3176. feedrate_z = data_value
  3177. if data_key == "feedrate_rapid":
  3178. feedrate_rapid = data_value
  3179. if data_key == "ppname_g":
  3180. pp_geometry_name = data_value
  3181. if data_key == "spindlespeed":
  3182. spindlespeed = data_value
  3183. if data_key == "dwell":
  3184. dwell = data_value
  3185. if data_key == "dwelltime":
  3186. dwelltime = data_value
  3187. datadict = copy.deepcopy(diadict_value)
  3188. dia_cnc_dict.update({
  3189. diadict_key: datadict
  3190. })
  3191. if dia_cnc_dict['offset'] == 'in':
  3192. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3193. offset_str = 'inside'
  3194. elif dia_cnc_dict['offset'].lower() == 'out':
  3195. tool_offset = dia_cnc_dict['tooldia'] / 2
  3196. offset_str = 'outside'
  3197. elif dia_cnc_dict['offset'].lower() == 'path':
  3198. offset_str = 'onpath'
  3199. tool_offset = 0.0
  3200. else:
  3201. offset_str = 'custom'
  3202. try:
  3203. offset_value = float(self.ui.tool_offset_entry.get_value())
  3204. except ValueError:
  3205. # try to convert comma to decimal point. if it's still not working error message and return
  3206. try:
  3207. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3208. )
  3209. except ValueError:
  3210. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3211. "use a number.")
  3212. return
  3213. if offset_value:
  3214. tool_offset = float(offset_value)
  3215. else:
  3216. self.app.inform.emit(
  3217. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3218. "Add a Tool Offset or change the Offset Type."
  3219. )
  3220. return
  3221. dia_cnc_dict.update({
  3222. 'offset_value': tool_offset
  3223. })
  3224. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3225. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3226. # Propagate options
  3227. job_obj.options["tooldia"] = tooldia_val
  3228. job_obj.options['type'] = 'Geometry'
  3229. job_obj.options['tool_dia'] = tooldia_val
  3230. job_obj.options['xmin'] = xmin
  3231. job_obj.options['ymin'] = ymin
  3232. job_obj.options['xmax'] = xmax
  3233. job_obj.options['ymax'] = ymax
  3234. app_obj.progress.emit(40)
  3235. res = job_obj.generate_from_geometry_2(
  3236. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  3237. z_cut=z_cut, z_move=z_move,
  3238. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3239. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3240. multidepth=multidepth, depthpercut=depthpercut,
  3241. extracut=extracut, startz=startz, endz=endz,
  3242. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3243. pp_geometry_name=pp_geometry_name,
  3244. tool_no=tool_cnt)
  3245. if res == 'fail':
  3246. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3247. return 'fail'
  3248. else:
  3249. dia_cnc_dict['gcode'] = res
  3250. app_obj.progress.emit(50)
  3251. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3252. # object is the source of gcode
  3253. job_obj.toolchange_xy_type = "geometry"
  3254. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3255. # TODO this serve for bounding box creation only; should be optimized
  3256. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3257. app_obj.progress.emit(80)
  3258. job_obj.cnc_tools.update({
  3259. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3260. })
  3261. dia_cnc_dict.clear()
  3262. # Object initialization function for app.new_object()
  3263. # RUNNING ON SEPARATE THREAD!
  3264. def job_init_multi_geometry(job_obj, app_obj):
  3265. assert isinstance(job_obj, FlatCAMCNCjob), \
  3266. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3267. # count the tools
  3268. tool_cnt = 0
  3269. dia_cnc_dict = {}
  3270. current_uid = int(1)
  3271. # this turn on the FlatCAMCNCJob plot for multiple tools
  3272. job_obj.multitool = True
  3273. job_obj.multigeo = True
  3274. job_obj.cnc_tools.clear()
  3275. job_obj.options['xmin'] = xmin
  3276. job_obj.options['ymin'] = ymin
  3277. job_obj.options['xmax'] = xmax
  3278. job_obj.options['ymax'] = ymax
  3279. try:
  3280. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3281. except ValueError:
  3282. # try to convert comma to decimal point. if it's still not working error message and return
  3283. try:
  3284. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3285. except ValueError:
  3286. self.app.inform.emit(
  3287. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3288. try:
  3289. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3290. except ValueError:
  3291. # try to convert comma to decimal point. if it's still not working error message and return
  3292. try:
  3293. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3294. except ValueError:
  3295. self.app.inform.emit(
  3296. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3297. 'or self.options["feedrate_probe"]')
  3298. for tooluid_key in self.sel_tools:
  3299. tool_cnt += 1
  3300. app_obj.progress.emit(20)
  3301. # find the tool_dia associated with the tooluid_key
  3302. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3303. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3304. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3305. for k, v in self.tools.items():
  3306. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3307. current_uid = int(k)
  3308. break
  3309. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3310. if diadict_key == 'tooldia':
  3311. tooldia_val = float('%.4f' % float(diadict_value))
  3312. dia_cnc_dict.update({
  3313. diadict_key: tooldia_val
  3314. })
  3315. if diadict_key == 'offset':
  3316. o_val = diadict_value.lower()
  3317. dia_cnc_dict.update({
  3318. diadict_key: o_val
  3319. })
  3320. if diadict_key == 'type':
  3321. t_val = diadict_value
  3322. dia_cnc_dict.update({
  3323. diadict_key: t_val
  3324. })
  3325. if diadict_key == 'tool_type':
  3326. tt_val = diadict_value
  3327. dia_cnc_dict.update({
  3328. diadict_key: tt_val
  3329. })
  3330. if diadict_key == 'data':
  3331. for data_key, data_value in diadict_value.items():
  3332. if data_key == "multidepth":
  3333. multidepth = data_value
  3334. if data_key == "depthperpass":
  3335. depthpercut = data_value
  3336. if data_key == "extracut":
  3337. extracut = data_value
  3338. if data_key == "startz":
  3339. startz = data_value
  3340. if data_key == "endz":
  3341. endz = data_value
  3342. if data_key == "toolchangez":
  3343. toolchangez =data_value
  3344. if data_key == "toolchangexy":
  3345. toolchangexy = data_value
  3346. if data_key == "toolchange":
  3347. toolchange = data_value
  3348. if data_key == "cutz":
  3349. z_cut = data_value
  3350. if data_key == "travelz":
  3351. z_move = data_value
  3352. if data_key == "feedrate":
  3353. feedrate = data_value
  3354. if data_key == "feedrate_z":
  3355. feedrate_z = data_value
  3356. if data_key == "feedrate_rapid":
  3357. feedrate_rapid = data_value
  3358. if data_key == "ppname_g":
  3359. pp_geometry_name = data_value
  3360. if data_key == "spindlespeed":
  3361. spindlespeed = data_value
  3362. if data_key == "dwell":
  3363. dwell = data_value
  3364. if data_key == "dwelltime":
  3365. dwelltime = data_value
  3366. datadict = copy.deepcopy(diadict_value)
  3367. dia_cnc_dict.update({
  3368. diadict_key: datadict
  3369. })
  3370. if dia_cnc_dict['offset'] == 'in':
  3371. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3372. offset_str = 'inside'
  3373. elif dia_cnc_dict['offset'].lower() == 'out':
  3374. tool_offset = dia_cnc_dict['tooldia'] / 2
  3375. offset_str = 'outside'
  3376. elif dia_cnc_dict['offset'].lower() == 'path':
  3377. offset_str = 'onpath'
  3378. tool_offset = 0.0
  3379. else:
  3380. offset_str = 'custom'
  3381. try:
  3382. offset_value = float(self.ui.tool_offset_entry.get_value())
  3383. except ValueError:
  3384. # try to convert comma to decimal point. if it's still not working error message and return
  3385. try:
  3386. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3387. )
  3388. except ValueError:
  3389. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3390. "use a number.")
  3391. return
  3392. if offset_value:
  3393. tool_offset = float(offset_value)
  3394. else:
  3395. self.app.inform.emit(
  3396. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3397. "Add a Tool Offset or change the Offset Type."
  3398. )
  3399. return
  3400. dia_cnc_dict.update({
  3401. 'offset_value': tool_offset
  3402. })
  3403. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3404. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3405. # Propagate options
  3406. job_obj.options["tooldia"] = tooldia_val
  3407. job_obj.options['type'] = 'Geometry'
  3408. job_obj.options['tool_dia'] = tooldia_val
  3409. app_obj.progress.emit(40)
  3410. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3411. res = job_obj.generate_from_multitool_geometry(
  3412. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3413. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  3414. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3415. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3416. multidepth=multidepth, depthpercut=depthpercut,
  3417. extracut=extracut, startz=startz, endz=endz,
  3418. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3419. pp_geometry_name=pp_geometry_name,
  3420. tool_no=tool_cnt)
  3421. if res == 'fail':
  3422. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3423. return 'fail'
  3424. else:
  3425. dia_cnc_dict['gcode'] = res
  3426. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3427. # TODO this serve for bounding box creation only; should be optimized
  3428. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3429. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3430. # object is the source of gcode
  3431. job_obj.toolchange_xy_type = "geometry"
  3432. app_obj.progress.emit(80)
  3433. job_obj.cnc_tools.update({
  3434. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3435. })
  3436. dia_cnc_dict.clear()
  3437. if use_thread:
  3438. # To be run in separate thread
  3439. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3440. # separate solid_geometry in the self.tools dictionary
  3441. def job_thread(app_obj):
  3442. if self.solid_geometry:
  3443. with self.app.proc_container.new("Generating CNC Code"):
  3444. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3445. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3446. app_obj.progress.emit(100)
  3447. else:
  3448. with self.app.proc_container.new("Generating CNC Code"):
  3449. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3450. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3451. app_obj.progress.emit(100)
  3452. # Create a promise with the name
  3453. self.app.collection.promise(outname)
  3454. # Send to worker
  3455. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3456. else:
  3457. if self.solid_geometry:
  3458. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3459. else:
  3460. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3461. def generatecncjob(self, outname=None,
  3462. tooldia=None, offset=None,
  3463. z_cut=None, z_move=None,
  3464. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3465. spindlespeed=None, dwell=None, dwelltime=None,
  3466. multidepth=None, depthperpass=None,
  3467. toolchange=None, toolchangez=None, toolchangexy=None,
  3468. extracut=None, startz=None, endz=None,
  3469. ppname_g=None,
  3470. segx=None,
  3471. segy=None,
  3472. use_thread=True):
  3473. """
  3474. Only used for TCL Command.
  3475. Creates a CNCJob out of this Geometry object. The actual
  3476. work is done by the target FlatCAMCNCjob object's
  3477. `generate_from_geometry_2()` method.
  3478. :param z_cut: Cut depth (negative)
  3479. :param z_move: Hight of the tool when travelling (not cutting)
  3480. :param feedrate: Feed rate while cutting on X - Y plane
  3481. :param feedrate_z: Feed rate while cutting on Z plane
  3482. :param feedrate_rapid: Feed rate while moving with rapids
  3483. :param tooldia: Tool diameter
  3484. :param outname: Name of the new object
  3485. :param spindlespeed: Spindle speed (RPM)
  3486. :param ppname_g Name of the postprocessor
  3487. :return: None
  3488. """
  3489. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3490. outname = outname if outname is not None else self.options["name"]
  3491. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3492. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3493. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3494. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3495. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3496. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3497. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3498. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3499. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3500. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3501. startz = startz if startz is not None else self.options["startz"]
  3502. endz = endz if endz is not None else float(self.options["endz"])
  3503. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3504. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3505. toolchange = toolchange if toolchange else self.options["toolchange"]
  3506. offset = offset if offset else 0.0
  3507. # int or None.
  3508. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3509. dwell = dwell if dwell else self.options["dwell"]
  3510. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3511. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3512. # Object initialization function for app.new_object()
  3513. # RUNNING ON SEPARATE THREAD!
  3514. def job_init(job_obj, app_obj):
  3515. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3516. # Propagate options
  3517. job_obj.options["tooldia"] = tooldia
  3518. app_obj.progress.emit(20)
  3519. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3520. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3521. app_obj.progress.emit(40)
  3522. job_obj.options['type'] = 'Geometry'
  3523. job_obj.options['tool_dia'] = tooldia
  3524. job_obj.segx = segx
  3525. job_obj.segy = segy
  3526. try:
  3527. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3528. except ValueError:
  3529. # try to convert comma to decimal point. if it's still not working error message and return
  3530. try:
  3531. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3532. except ValueError:
  3533. self.app.inform.emit(
  3534. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3535. try:
  3536. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3537. except ValueError:
  3538. # try to convert comma to decimal point. if it's still not working error message and return
  3539. try:
  3540. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3541. except ValueError:
  3542. self.app.inform.emit(
  3543. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3544. 'or self.options["feedrate_probe"]')
  3545. # TODO: The tolerance should not be hard coded. Just for testing.
  3546. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  3547. z_cut=z_cut, z_move=z_move,
  3548. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3549. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3550. multidepth=multidepth, depthpercut=depthperpass,
  3551. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3552. extracut=extracut, startz=startz, endz=endz,
  3553. pp_geometry_name=ppname_g
  3554. )
  3555. app_obj.progress.emit(50)
  3556. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  3557. # source of gcode
  3558. job_obj.toolchange_xy_type = "geometry"
  3559. job_obj.gcode_parse()
  3560. app_obj.progress.emit(80)
  3561. if use_thread:
  3562. # To be run in separate thread
  3563. def job_thread(app_obj):
  3564. with self.app.proc_container.new("Generating CNC Code"):
  3565. app_obj.new_object("cncjob", outname, job_init)
  3566. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3567. app_obj.progress.emit(100)
  3568. # Create a promise with the name
  3569. self.app.collection.promise(outname)
  3570. # Send to worker
  3571. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3572. else:
  3573. self.app.new_object("cncjob", outname, job_init)
  3574. # def on_plot_cb_click(self, *args): # TODO: args not needed
  3575. # if self.muted_ui:
  3576. # return
  3577. # self.read_form_item('plot')
  3578. def scale(self, xfactor, yfactor=None, point=None):
  3579. """
  3580. Scales all geometry by a given factor.
  3581. :param xfactor: Factor by which to scale the object's geometry/
  3582. :type xfactor: float
  3583. :param yfactor: Factor by which to scale the object's geometry/
  3584. :type yfactor: float
  3585. :return: None
  3586. :rtype: None
  3587. """
  3588. try:
  3589. xfactor = float(xfactor)
  3590. except:
  3591. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3592. return
  3593. if yfactor is None:
  3594. yfactor = xfactor
  3595. else:
  3596. try:
  3597. yfactor = float(yfactor)
  3598. except:
  3599. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3600. return
  3601. if point is None:
  3602. px = 0
  3603. py = 0
  3604. else:
  3605. px, py = point
  3606. # if type(self.solid_geometry) == list:
  3607. # geo_list = self.flatten(self.solid_geometry)
  3608. # self.solid_geometry = []
  3609. # # for g in geo_list:
  3610. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  3611. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  3612. # for g in geo_list]
  3613. # else:
  3614. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  3615. # origin=(px, py))
  3616. # self.app.inform.emit("[success]Geometry Scale done.")
  3617. def scale_recursion(geom):
  3618. if type(geom) == list:
  3619. geoms=list()
  3620. for local_geom in geom:
  3621. geoms.append(scale_recursion(local_geom))
  3622. return geoms
  3623. else:
  3624. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  3625. if self.multigeo is True:
  3626. for tool in self.tools:
  3627. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  3628. else:
  3629. self.solid_geometry=scale_recursion(self.solid_geometry)
  3630. self.app.inform.emit("[success]Geometry Scale done.")
  3631. def offset(self, vect):
  3632. """
  3633. Offsets all geometry by a given vector/
  3634. :param vect: (x, y) vector by which to offset the object's geometry.
  3635. :type vect: tuple
  3636. :return: None
  3637. :rtype: None
  3638. """
  3639. try:
  3640. dx, dy = vect
  3641. except TypeError:
  3642. self.app.inform.emit("[ERROR_NOTCL]An (x,y) pair of values are needed. "
  3643. "Probable you entered only one value in the Offset field.")
  3644. return
  3645. def translate_recursion(geom):
  3646. if type(geom) == list:
  3647. geoms=list()
  3648. for local_geom in geom:
  3649. geoms.append(translate_recursion(local_geom))
  3650. return geoms
  3651. else:
  3652. return affinity.translate(geom, xoff=dx, yoff=dy)
  3653. if self.multigeo is True:
  3654. for tool in self.tools:
  3655. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  3656. else:
  3657. self.solid_geometry=translate_recursion(self.solid_geometry)
  3658. self.app.inform.emit("[success]Geometry Offset done.")
  3659. def convert_units(self, units):
  3660. self.ui_disconnect()
  3661. factor = Geometry.convert_units(self, units)
  3662. self.options['cutz'] = float(self.options['cutz']) * factor
  3663. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  3664. self.options['travelz'] = float(self.options['travelz']) * factor
  3665. self.options['feedrate'] = float(self.options['feedrate']) * factor
  3666. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  3667. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3668. self.options['endz'] = float(self.options['endz']) * factor
  3669. # self.options['cnctooldia'] *= factor
  3670. # self.options['painttooldia'] *= factor
  3671. # self.options['paintmargin'] *= factor
  3672. # self.options['paintoverlap'] *= factor
  3673. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  3674. if self.app.defaults["geometry_toolchangexy"] == '':
  3675. self.options['toolchangexy'] = "0.0, 0.0"
  3676. else:
  3677. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  3678. if len(coords_xy) < 2:
  3679. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3680. "in the format (x, y) \nbut now there is only one value, not two. ")
  3681. return 'fail'
  3682. coords_xy[0] *= factor
  3683. coords_xy[1] *= factor
  3684. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3685. if self.options['startz'] is not None:
  3686. self.options['startz'] = float(self.options['startz']) * factor
  3687. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3688. 'endz', 'toolchangez']
  3689. if isinstance(self, FlatCAMGeometry):
  3690. temp_tools_dict = {}
  3691. tool_dia_copy = {}
  3692. data_copy = {}
  3693. for tooluid_key, tooluid_value in self.tools.items():
  3694. for dia_key, dia_value in tooluid_value.items():
  3695. if dia_key == 'tooldia':
  3696. dia_value *= factor
  3697. dia_value = float('%.4f' % dia_value)
  3698. tool_dia_copy[dia_key] = dia_value
  3699. if dia_key == 'offset':
  3700. tool_dia_copy[dia_key] = dia_value
  3701. if dia_key == 'offset_value':
  3702. dia_value *= factor
  3703. tool_dia_copy[dia_key] = dia_value
  3704. # convert the value in the Custom Tool Offset entry in UI
  3705. custom_offset = None
  3706. try:
  3707. custom_offset = float(self.ui.tool_offset_entry.get_value())
  3708. except ValueError:
  3709. # try to convert comma to decimal point. if it's still not working error message and return
  3710. try:
  3711. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3712. )
  3713. except ValueError:
  3714. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3715. "use a number.")
  3716. return
  3717. except TypeError:
  3718. pass
  3719. if custom_offset:
  3720. custom_offset *= factor
  3721. self.ui.tool_offset_entry.set_value(custom_offset)
  3722. if dia_key == 'type':
  3723. tool_dia_copy[dia_key] = dia_value
  3724. if dia_key == 'tool_type':
  3725. tool_dia_copy[dia_key] = dia_value
  3726. if dia_key == 'data':
  3727. for data_key, data_value in dia_value.items():
  3728. # convert the form fields that are convertible
  3729. for param in param_list:
  3730. if data_key == param and data_value is not None:
  3731. data_copy[data_key] = data_value * factor
  3732. # copy the other dict entries that are not convertible
  3733. if data_key not in param_list:
  3734. data_copy[data_key] = data_value
  3735. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  3736. data_copy.clear()
  3737. temp_tools_dict.update({
  3738. tooluid_key: copy.deepcopy(tool_dia_copy)
  3739. })
  3740. tool_dia_copy.clear()
  3741. self.tools.clear()
  3742. self.tools = copy.deepcopy(temp_tools_dict)
  3743. # if there is a value in the new tool field then convert that one too
  3744. tooldia = self.ui.addtool_entry.get_value()
  3745. if tooldia:
  3746. tooldia *= factor
  3747. # limit the decimals to 2 for METRIC and 3 for INCH
  3748. if units.lower() == 'in':
  3749. tooldia = float('%.4f' % tooldia)
  3750. else:
  3751. tooldia = float('%.2f' % tooldia)
  3752. self.ui.addtool_entry.set_value(tooldia)
  3753. return factor
  3754. def plot_element(self, element, color='red', visible=None):
  3755. visible = visible if visible else self.options['plot']
  3756. try:
  3757. for sub_el in element:
  3758. self.plot_element(sub_el)
  3759. except TypeError: # Element is not iterable...
  3760. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3761. def plot(self, visible=None):
  3762. """
  3763. Adds the object into collection.
  3764. :return: None
  3765. """
  3766. # Does all the required setup and returns False
  3767. # if the 'ptint' option is set to False.
  3768. if not FlatCAMObj.plot(self):
  3769. return
  3770. try:
  3771. # plot solid geometries found as members of self.tools attribute dict
  3772. # for MultiGeo
  3773. if self.multigeo == True: # geo multi tool usage
  3774. for tooluid_key in self.tools:
  3775. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3776. self.plot_element(solid_geometry, visible=visible)
  3777. # plot solid geometry that may be an direct attribute of the geometry object
  3778. # for SingleGeo
  3779. if self.solid_geometry:
  3780. self.plot_element(self.solid_geometry, visible=visible)
  3781. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3782. self.shapes.redraw()
  3783. except (ObjectDeleted, AttributeError):
  3784. self.shapes.clear(update=True)
  3785. def on_plot_cb_click(self, *args):
  3786. if self.muted_ui:
  3787. return
  3788. self.plot()
  3789. self.read_form_item('plot')
  3790. self.ui_disconnect()
  3791. cb_flag = self.ui.plot_cb.isChecked()
  3792. for row in range(self.ui.geo_tools_table.rowCount()):
  3793. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3794. if cb_flag:
  3795. table_cb.setChecked(True)
  3796. else:
  3797. table_cb.setChecked(False)
  3798. self.ui_connect()
  3799. def on_plot_cb_click_table(self):
  3800. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3801. self.ui_disconnect()
  3802. cw = self.sender()
  3803. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3804. cw_row = cw_index.row()
  3805. check_row = 0
  3806. self.shapes.clear(update=True)
  3807. for tooluid_key in self.tools:
  3808. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3809. # find the geo_tool_table row associated with the tooluid_key
  3810. for row in range(self.ui.geo_tools_table.rowCount()):
  3811. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3812. if tooluid_item == int(tooluid_key):
  3813. check_row = row
  3814. break
  3815. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3816. self.plot_element(element=solid_geometry, visible=True)
  3817. self.shapes.redraw()
  3818. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3819. # if all the row plot's are enabled also enable the general plot checkbox
  3820. cb_cnt = 0
  3821. total_row = self.ui.geo_tools_table.rowCount()
  3822. for row in range(total_row):
  3823. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3824. cb_cnt += 1
  3825. else:
  3826. cb_cnt -= 1
  3827. if cb_cnt < total_row:
  3828. self.ui.plot_cb.setChecked(False)
  3829. else:
  3830. self.ui.plot_cb.setChecked(True)
  3831. self.ui_connect()
  3832. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  3833. """
  3834. Represents G-Code.
  3835. """
  3836. optionChanged = QtCore.pyqtSignal(str)
  3837. ui_type = CNCObjectUI
  3838. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  3839. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  3840. spindlespeed=None):
  3841. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  3842. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  3843. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  3844. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  3845. FlatCAMObj.__init__(self, name)
  3846. self.kind = "cncjob"
  3847. self.options.update({
  3848. "plot": True,
  3849. "tooldia": 0.03937, # 0.4mm in inches
  3850. "append": "",
  3851. "prepend": "",
  3852. "dwell": False,
  3853. "dwelltime": 1,
  3854. "type": 'Geometry'
  3855. })
  3856. '''
  3857. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3858. diameter of the tools and the value is another dict that will hold the data under the following form:
  3859. {tooldia: {
  3860. 'tooluid': 1,
  3861. 'offset': 'Path',
  3862. 'type_item': 'Rough',
  3863. 'tool_type': 'C1',
  3864. 'data': {} # a dict to hold the parameters
  3865. 'gcode': "" # a string with the actual GCODE
  3866. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3867. 'solid_geometry': []
  3868. },
  3869. ...
  3870. }
  3871. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3872. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3873. '''
  3874. self.cnc_tools = {}
  3875. '''
  3876. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3877. diameter of the tools and the value is another dict that will hold the data under the following form:
  3878. {tooldia: {
  3879. 'tool': int,
  3880. 'nr_drills': int,
  3881. 'nr_slots': int,
  3882. 'offset': float,
  3883. 'data': {} # a dict to hold the parameters
  3884. 'gcode': "" # a string with the actual GCODE
  3885. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3886. 'solid_geometry': []
  3887. },
  3888. ...
  3889. }
  3890. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  3891. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  3892. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3893. '''
  3894. self.exc_cnc_tools = {}
  3895. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3896. # (like the one in the TCL Command), False
  3897. self.multitool = False
  3898. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  3899. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3900. self.g_x_re = re.compile(gcodex_re_string)
  3901. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3902. self.g_y_re = re.compile(gcodey_re_string)
  3903. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  3904. self.g_z_re = re.compile(gcodez_re_string)
  3905. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  3906. self.g_f_re = re.compile(gcodef_re_string)
  3907. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  3908. self.g_t_re = re.compile(gcodet_re_string)
  3909. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  3910. self.g_nr_re = re.compile(gcodenr_re_string)
  3911. # Attributes to be included in serialization
  3912. # Always append to it because it carries contents
  3913. # from predecessors.
  3914. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3915. self.annotation = self.app.plotcanvas.new_text_group()
  3916. def build_ui(self):
  3917. self.ui_disconnect()
  3918. FlatCAMObj.build_ui(self)
  3919. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3920. if self.cnc_tools:
  3921. self.ui.cnc_tools_table.show()
  3922. else:
  3923. self.ui.cnc_tools_table.hide()
  3924. offset = 0
  3925. tool_idx = 0
  3926. n = len(self.cnc_tools)
  3927. self.ui.cnc_tools_table.setRowCount(n)
  3928. for dia_key, dia_value in self.cnc_tools.items():
  3929. tool_idx += 1
  3930. row_no = tool_idx - 1
  3931. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3932. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3933. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3934. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3935. # There are no tool bits in MM with more than 2 decimals diameter.
  3936. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3937. if self.units == 'MM':
  3938. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3939. else:
  3940. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3941. offset_txt = list(str(dia_value['offset']))
  3942. offset_txt[0] = offset_txt[0].upper()
  3943. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3944. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3945. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3946. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3947. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3948. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3949. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3950. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3951. # hack so the checkbox stay centered in the table cell
  3952. # used this:
  3953. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3954. # plot_item = QtWidgets.QWidget()
  3955. # checkbox = FCCheckBox()
  3956. # checkbox.setCheckState(QtCore.Qt.Checked)
  3957. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3958. # qhboxlayout.addWidget(checkbox)
  3959. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3960. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3961. plot_item = FCCheckBox()
  3962. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3963. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3964. if self.ui.plot_cb.isChecked():
  3965. plot_item.setChecked(True)
  3966. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3967. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3968. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3969. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3970. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3971. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3972. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3973. # make the diameter column editable
  3974. # for row in range(tool_idx):
  3975. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3976. # QtCore.Qt.ItemIsEnabled)
  3977. for row in range(tool_idx):
  3978. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3979. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3980. self.ui.cnc_tools_table.resizeColumnsToContents()
  3981. self.ui.cnc_tools_table.resizeRowsToContents()
  3982. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3983. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3984. vertical_header.hide()
  3985. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3986. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3987. horizontal_header.setMinimumSectionSize(10)
  3988. horizontal_header.setDefaultSectionSize(70)
  3989. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3990. horizontal_header.resizeSection(0, 20)
  3991. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3992. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3993. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3994. horizontal_header.resizeSection(4, 40)
  3995. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3996. horizontal_header.resizeSection(4, 17)
  3997. # horizontal_header.setStretchLastSection(True)
  3998. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3999. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4000. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4001. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4002. # self.ui.geo_tools_table.setSortingEnabled(True)
  4003. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4004. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4005. self.ui_connect()
  4006. def set_ui(self, ui):
  4007. FlatCAMObj.set_ui(self, ui)
  4008. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4009. assert isinstance(self.ui, CNCObjectUI), \
  4010. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4011. self.form_fields.update({
  4012. "plot": self.ui.plot_cb,
  4013. # "tooldia": self.ui.tooldia_entry,
  4014. "append": self.ui.append_text,
  4015. "prepend": self.ui.prepend_text,
  4016. })
  4017. # Fill form fields only on object create
  4018. self.to_form()
  4019. # this means that the object that created this CNCJob was an Excellon
  4020. try:
  4021. if self.travel_distance:
  4022. self.ui.t_distance_label.show()
  4023. self.ui.t_distance_entry.setVisible(True)
  4024. self.ui.t_distance_entry.setDisabled(True)
  4025. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4026. self.ui.units_label.setText(str(self.units).lower())
  4027. self.ui.units_label.setDisabled(True)
  4028. except AttributeError:
  4029. pass
  4030. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4031. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4032. # Show/Hide Advanced Options
  4033. if self.app.defaults["global_advanced"] is False:
  4034. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  4035. else:
  4036. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  4037. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4038. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4039. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  4040. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4041. def ui_connect(self):
  4042. for row in range(self.ui.cnc_tools_table.rowCount()):
  4043. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4044. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4045. def ui_disconnect(self):
  4046. for row in range(self.ui.cnc_tools_table.rowCount()):
  4047. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4048. try:
  4049. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4050. except:
  4051. pass
  4052. def on_updateplot_button_click(self, *args):
  4053. """
  4054. Callback for the "Updata Plot" button. Reads the form for updates
  4055. and plots the object.
  4056. """
  4057. self.read_form()
  4058. self.plot()
  4059. def on_plot_kind_change(self):
  4060. kind = self.ui.cncplot_method_combo.get_value()
  4061. self.plot(kind=kind)
  4062. def on_exportgcode_button_click(self, *args):
  4063. self.app.report_usage("cncjob_on_exportgcode_button")
  4064. self.read_form()
  4065. name = self.app.collection.get_active().options['name']
  4066. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4067. _filter_ = "RML1 Files (*.rol);;" \
  4068. "All Files (*.*)"
  4069. elif 'hpgl' in self.pp_geometry_name:
  4070. _filter_ = "HPGL Files (*.plt);;" \
  4071. "All Files (*.*)"
  4072. else:
  4073. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4074. "G-Code Files (*.g-code);;All Files (*.*)"
  4075. try:
  4076. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4077. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4078. caption="Export Machine Code ...",
  4079. directory=dir_file_to_save,
  4080. filter=_filter_
  4081. )
  4082. except TypeError:
  4083. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)
  4084. filename = str(filename)
  4085. if filename == '':
  4086. self.app.inform.emit("[WARNING_NOTCL]Export Machine Code cancelled ...")
  4087. return
  4088. preamble = str(self.ui.prepend_text.get_value())
  4089. postamble = str(self.ui.append_text.get_value())
  4090. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4091. self.app.file_saved.emit("gcode", filename)
  4092. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  4093. def on_modifygcode_button_click(self, *args):
  4094. # add the tab if it was closed
  4095. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  4096. # delete the absolute and relative position and messages in the infobar
  4097. self.app.ui.position_label.setText("")
  4098. self.app.ui.rel_position_label.setText("")
  4099. # Switch plot_area to CNCJob tab
  4100. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  4101. preamble = str(self.ui.prepend_text.get_value())
  4102. postamble = str(self.ui.append_text.get_value())
  4103. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4104. # first clear previous text in text editor (if any)
  4105. self.app.ui.code_editor.clear()
  4106. # then append the text from GCode to the text editor
  4107. try:
  4108. for line in self.app.gcode_edited:
  4109. proc_line = str(line).strip('\n')
  4110. self.app.ui.code_editor.append(proc_line)
  4111. except Exception as e:
  4112. log.debug('FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4113. self.app.inform.emit('[ERROR]FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4114. return
  4115. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4116. self.app.handleTextChanged()
  4117. self.app.ui.show()
  4118. def gcode_header(self):
  4119. log.debug("FlatCAMCNCJob.gcode_header()")
  4120. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4121. marlin = False
  4122. hpgl = False
  4123. probe_pp = False
  4124. try:
  4125. for key in self.cnc_tools:
  4126. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  4127. marlin = True
  4128. break
  4129. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4130. hpgl = True
  4131. break
  4132. if "toolchange_probe" in self.cnc_tools[key]['data']['ppname_g'].lower():
  4133. probe_pp = True
  4134. break
  4135. except Exception as e:
  4136. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4137. try:
  4138. if self.options['ppname_e'] == 'marlin':
  4139. marlin = True
  4140. except Exception as e:
  4141. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4142. try:
  4143. if "toolchange_probe" in self.options['ppname_e'].lower():
  4144. probe_pp = True
  4145. except Exception as e:
  4146. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4147. if marlin is True:
  4148. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4149. (str(self.app.version), str(self.app.version_date)) + '\n'
  4150. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4151. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4152. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4153. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4154. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4155. gcode += ';Created on ' + time_str + '\n' + '\n'
  4156. elif hpgl is True:
  4157. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4158. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4159. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4160. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4161. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4162. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4163. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4164. gcode += 'CO "Created on ' + time_str + '";\n'
  4165. elif probe_pp is True:
  4166. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4167. (str(self.app.version), str(self.app.version_date)) + '\n'
  4168. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4169. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4170. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4171. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4172. 'Then zero the Z axis.)\n' + '\n'
  4173. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4174. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4175. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4176. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4177. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4178. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4179. else:
  4180. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4181. (str(self.app.version), str(self.app.version_date)) + '\n'
  4182. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4183. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4184. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4185. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4186. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4187. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4188. return gcode
  4189. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4190. gcode = ''
  4191. roland = False
  4192. hpgl = False
  4193. # detect if using Roland postprocessor
  4194. try:
  4195. for key in self.cnc_tools:
  4196. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4197. roland = True
  4198. break
  4199. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4200. hpgl = True
  4201. break
  4202. except:
  4203. try:
  4204. for key in self.cnc_tools:
  4205. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4206. roland = True
  4207. break
  4208. except:
  4209. pass
  4210. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4211. if roland is False and hpgl is False:
  4212. gcode = self.gcode_header()
  4213. # detect if using multi-tool and make the Gcode summation correctly for each case
  4214. if self.multitool is True:
  4215. for tooluid_key in self.cnc_tools:
  4216. for key, value in self.cnc_tools[tooluid_key].items():
  4217. if key == 'gcode':
  4218. gcode += value
  4219. break
  4220. else:
  4221. gcode += self.gcode
  4222. if roland is True:
  4223. g = preamble + gcode + postamble
  4224. elif hpgl is True:
  4225. g = self.gcode_header() + preamble + gcode + postamble
  4226. else:
  4227. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4228. g_idx = gcode.rfind('G20')
  4229. # if it did not find 'G20' then search for 'G21'
  4230. if g_idx == -1:
  4231. g_idx = gcode.rfind('G21')
  4232. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4233. if g_idx == -1:
  4234. self.app.inform.emit("[ERROR_NOTCL] G-code does not have a units code: either G20 or G21")
  4235. return
  4236. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  4237. # lines = StringIO(self.gcode)
  4238. lines = StringIO(g)
  4239. ## Write
  4240. if filename is not None:
  4241. try:
  4242. with open(filename, 'w') as f:
  4243. for line in lines:
  4244. f.write(line)
  4245. except FileNotFoundError:
  4246. self.app.inform.emit("[WARNING_NOTCL] No such file or directory")
  4247. return
  4248. elif to_file is False:
  4249. # Just for adding it to the recent files list.
  4250. self.app.file_opened.emit("cncjob", filename)
  4251. self.app.file_saved.emit("cncjob", filename)
  4252. self.app.inform.emit("[success] Saved to: " + filename)
  4253. else:
  4254. return lines
  4255. def get_gcode(self, preamble='', postamble=''):
  4256. #we need this to be able get_gcode separatelly for shell command export_gcode
  4257. return preamble + '\n' + self.gcode + "\n" + postamble
  4258. def get_svg(self):
  4259. # we need this to be able get_svg separately for shell command export_svg
  4260. pass
  4261. def on_plot_cb_click(self, *args):
  4262. if self.muted_ui:
  4263. return
  4264. kind = self.ui.cncplot_method_combo.get_value()
  4265. self.plot(kind=kind)
  4266. self.read_form_item('plot')
  4267. self.ui_disconnect()
  4268. cb_flag = self.ui.plot_cb.isChecked()
  4269. for row in range(self.ui.cnc_tools_table.rowCount()):
  4270. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4271. if cb_flag:
  4272. table_cb.setChecked(True)
  4273. else:
  4274. table_cb.setChecked(False)
  4275. self.ui_connect()
  4276. def on_plot_cb_click_table(self):
  4277. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4278. self.ui_disconnect()
  4279. cw = self.sender()
  4280. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4281. cw_row = cw_index.row()
  4282. self.shapes.clear(update=True)
  4283. for tooluid_key in self.cnc_tools:
  4284. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4285. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4286. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4287. for r in range(self.ui.cnc_tools_table.rowCount()):
  4288. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4289. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4290. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  4291. self.shapes.redraw()
  4292. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4293. # if all the row plot's are enabled also enable the general plot checkbox
  4294. cb_cnt = 0
  4295. total_row = self.ui.cnc_tools_table.rowCount()
  4296. for row in range(total_row):
  4297. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4298. cb_cnt += 1
  4299. else:
  4300. cb_cnt -= 1
  4301. if cb_cnt < total_row:
  4302. self.ui.plot_cb.setChecked(False)
  4303. else:
  4304. self.ui.plot_cb.setChecked(True)
  4305. self.ui_connect()
  4306. def plot(self, visible=None, kind='all'):
  4307. # Does all the required setup and returns False
  4308. # if the 'ptint' option is set to False.
  4309. if not FlatCAMObj.plot(self):
  4310. return
  4311. visible = visible if visible else self.options['plot']
  4312. try:
  4313. if self.multitool is False: # single tool usage
  4314. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4315. else:
  4316. # multiple tools usage
  4317. for tooluid_key in self.cnc_tools:
  4318. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4319. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4320. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4321. self.shapes.redraw()
  4322. except (ObjectDeleted, AttributeError):
  4323. self.shapes.clear(update=True)
  4324. self.annotation.clear(update=True)
  4325. def convert_units(self, units):
  4326. factor = CNCjob.convert_units(self, units)
  4327. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4328. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4329. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4330. 'endz', 'toolchangez']
  4331. temp_tools_dict = {}
  4332. tool_dia_copy = {}
  4333. data_copy = {}
  4334. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4335. for dia_key, dia_value in tooluid_value.items():
  4336. if dia_key == 'tooldia':
  4337. dia_value *= factor
  4338. dia_value = float('%.4f' % dia_value)
  4339. tool_dia_copy[dia_key] = dia_value
  4340. if dia_key == 'offset':
  4341. tool_dia_copy[dia_key] = dia_value
  4342. if dia_key == 'offset_value':
  4343. dia_value *= factor
  4344. tool_dia_copy[dia_key] = dia_value
  4345. if dia_key == 'type':
  4346. tool_dia_copy[dia_key] = dia_value
  4347. if dia_key == 'tool_type':
  4348. tool_dia_copy[dia_key] = dia_value
  4349. if dia_key == 'data':
  4350. for data_key, data_value in dia_value.items():
  4351. # convert the form fields that are convertible
  4352. for param in param_list:
  4353. if data_key == param and data_value is not None:
  4354. data_copy[data_key] = data_value * factor
  4355. # copy the other dict entries that are not convertible
  4356. if data_key not in param_list:
  4357. data_copy[data_key] = data_value
  4358. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  4359. data_copy.clear()
  4360. if dia_key == 'gcode':
  4361. tool_dia_copy[dia_key] = dia_value
  4362. if dia_key == 'gcode_parsed':
  4363. tool_dia_copy[dia_key] = dia_value
  4364. if dia_key == 'solid_geometry':
  4365. tool_dia_copy[dia_key] = dia_value
  4366. # if dia_key == 'solid_geometry':
  4367. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4368. # if dia_key == 'gcode_parsed':
  4369. # for g in dia_value:
  4370. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4371. #
  4372. # tool_dia_copy['gcode_parsed'] = copy.deepcopy(dia_value)
  4373. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4374. temp_tools_dict.update({
  4375. tooluid_key: copy.deepcopy(tool_dia_copy)
  4376. })
  4377. tool_dia_copy.clear()
  4378. self.cnc_tools.clear()
  4379. self.cnc_tools = copy.deepcopy(temp_tools_dict)
  4380. # end of file