FlatCAMObj.py 172 KB

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