FlatCAMObj.py 159 KB

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