FlatCAMObj.py 211 KB

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