FlatCAMObj.py 159 KB

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