FlatCAMObj.py 192 KB

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