FlatCAMGeometry.py 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  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. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. import shapely.affinity as affinity
  13. from camlib import Geometry
  14. from appObjects.FlatCAMObj import *
  15. import ezdxf
  16. import math
  17. import numpy as np
  18. from copy import deepcopy
  19. import traceback
  20. import gettext
  21. import appTranslation as fcTranslate
  22. import builtins
  23. fcTranslate.apply_language('strings')
  24. if '_' not in builtins.__dict__:
  25. _ = gettext.gettext
  26. class GeometryObject(FlatCAMObj, Geometry):
  27. """
  28. Geometric object not associated with a specific
  29. format.
  30. """
  31. optionChanged = QtCore.pyqtSignal(str)
  32. ui_type = GeometryObjectUI
  33. def __init__(self, name):
  34. self.decimals = self.app.decimals
  35. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  36. FlatCAMObj.__init__(self, name)
  37. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  38. self.kind = "geometry"
  39. self.options.update({
  40. "plot": True,
  41. "multicolored": False,
  42. "cutz": -0.002,
  43. "vtipdia": 0.1,
  44. "vtipangle": 30,
  45. "travelz": 0.1,
  46. "feedrate": 5.0,
  47. "feedrate_z": 5.0,
  48. "feedrate_rapid": 5.0,
  49. "spindlespeed": 0,
  50. "dwell": True,
  51. "dwelltime": 1000,
  52. "multidepth": False,
  53. "depthperpass": 0.002,
  54. "extracut": False,
  55. "extracut_length": 0.1,
  56. "endz": 2.0,
  57. "endxy": '',
  58. "area_exclusion": False,
  59. "area_shape": "polygon",
  60. "area_strategy": "over",
  61. "area_overz": 1.0,
  62. "startz": None,
  63. "toolchange": False,
  64. "toolchangez": 1.0,
  65. "toolchangexy": "0.0, 0.0",
  66. "ppname_g": 'default',
  67. "z_pdepth": -0.02,
  68. "feedrate_probe": 3.0,
  69. })
  70. if "cnctooldia" not in self.options:
  71. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  72. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  73. else:
  74. try:
  75. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  76. tools_diameters = [eval(a) for a in tools_string if a != '']
  77. self.options["cnctooldia"] = tools_diameters[0] if tools_diameters else 0.0
  78. except Exception as e:
  79. log.debug("FlatCAMObj.GeometryObject.init() --> %s" % str(e))
  80. self.options["startz"] = self.app.defaults["geometry_startz"]
  81. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  82. self.tooluid = 0
  83. '''
  84. self.tools = {}
  85. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  86. tool_id of the tools and the value is another dict that will hold the data under the following form:
  87. {tooluid: {
  88. 'tooldia': 1,
  89. 'offset': 'Path',
  90. 'offset_value': 0.0
  91. 'type': 'Rough',
  92. 'tool_type': 'C1',
  93. 'data': self.default_tool_data
  94. 'solid_geometry': []
  95. }
  96. }
  97. '''
  98. self.tools = {}
  99. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  100. # those elements are the ones used for generating GCode
  101. self.sel_tools = {}
  102. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  103. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  104. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  105. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  106. self.v_tool_type = None
  107. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  108. # the default value is False
  109. self.multigeo = False
  110. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  111. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  112. self.special_group = None
  113. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  114. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  115. self.units_found = self.app.defaults['units']
  116. # this variable can be updated by the Object that generates the geometry
  117. self.tool_type = 'C1'
  118. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  119. self.old_cutz = self.app.defaults["geometry_cutz"]
  120. self.fill_color = self.app.defaults['geometry_plot_line']
  121. self.outline_color = self.app.defaults['geometry_plot_line']
  122. self.alpha_level = 'FF'
  123. self.param_fields = {}
  124. # store here the state of the exclusion checkbox state to be restored after building the UI
  125. # TODO add this in the sel.app.defaults dict and in Preferences
  126. self.exclusion_area_cb_is_checked = False
  127. # Attributes to be included in serialization
  128. # Always append to it because it carries contents
  129. # from predecessors.
  130. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  131. def build_ui(self):
  132. self.ui_disconnect()
  133. FlatCAMObj.build_ui(self)
  134. # Area Exception - exclusion shape added signal
  135. # first disconnect it from any other object
  136. try:
  137. self.app.exc_areas.e_shape_modified.disconnect()
  138. except (TypeError, AttributeError):
  139. pass
  140. # then connect it to the current build_ui() method
  141. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  142. self.units = self.app.defaults['units']
  143. tool_idx = 0
  144. n = len(self.tools)
  145. self.ui.geo_tools_table.setRowCount(n)
  146. for tooluid_key, tooluid_value in self.tools.items():
  147. tool_idx += 1
  148. row_no = tool_idx - 1
  149. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  150. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  151. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  152. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  153. # There are no tool bits in MM with more than 3 decimals diameter.
  154. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  155. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  156. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  157. offset_item = FCComboBox()
  158. for item in self.offset_item_options:
  159. offset_item.addItem(item)
  160. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  161. idx = offset_item.findText(tooluid_value['offset'])
  162. offset_item.setCurrentIndex(idx)
  163. type_item = FCComboBox()
  164. for item in self.type_item_options:
  165. type_item.addItem(item)
  166. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  167. idx = type_item.findText(tooluid_value['type'])
  168. type_item.setCurrentIndex(idx)
  169. tool_type_item = FCComboBox()
  170. for item in self.tool_type_item_options:
  171. tool_type_item.addItem(item)
  172. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  173. idx = tool_type_item.findText(tooluid_value['tool_type'])
  174. tool_type_item.setCurrentIndex(idx)
  175. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  176. plot_item = FCCheckBox()
  177. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  178. if self.ui.plot_cb.isChecked():
  179. plot_item.setChecked(True)
  180. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  181. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  182. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  183. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  184. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  185. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  186. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  187. try:
  188. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  189. except Exception as e:
  190. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  191. # make the diameter column editable
  192. for row in range(tool_idx):
  193. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  194. QtCore.Qt.ItemIsEditable |
  195. QtCore.Qt.ItemIsEnabled)
  196. # sort the tool diameter column
  197. # self.ui.geo_tools_table.sortItems(1)
  198. # all the tools are selected by default
  199. # self.ui.geo_tools_table.selectColumn(0)
  200. self.ui.geo_tools_table.resizeColumnsToContents()
  201. self.ui.geo_tools_table.resizeRowsToContents()
  202. vertical_header = self.ui.geo_tools_table.verticalHeader()
  203. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  204. vertical_header.hide()
  205. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  206. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  207. horizontal_header.setMinimumSectionSize(10)
  208. horizontal_header.setDefaultSectionSize(70)
  209. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  210. horizontal_header.resizeSection(0, 20)
  211. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  212. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  213. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  214. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  215. horizontal_header.resizeSection(4, 40)
  216. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  217. horizontal_header.resizeSection(4, 17)
  218. # horizontal_header.setStretchLastSection(True)
  219. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  220. self.ui.geo_tools_table.setColumnWidth(0, 20)
  221. self.ui.geo_tools_table.setColumnWidth(4, 40)
  222. self.ui.geo_tools_table.setColumnWidth(6, 17)
  223. # self.ui.geo_tools_table.setSortingEnabled(True)
  224. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  225. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  226. # update UI for all rows - useful after units conversion but only if there is at least one row
  227. row_cnt = self.ui.geo_tools_table.rowCount()
  228. if row_cnt > 0:
  229. for r in range(row_cnt):
  230. self.update_ui(r)
  231. # select only the first tool / row
  232. selected_row = 0
  233. try:
  234. self.select_tools_table_row(selected_row, clearsel=True)
  235. # update the Geometry UI
  236. self.update_ui()
  237. except Exception as e:
  238. # when the tools table is empty there will be this error but once the table is populated it will go away
  239. log.debug(str(e))
  240. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  241. # and can create some problems
  242. if self.multigeo is False:
  243. self.ui.geo_tools_table.setColumnHidden(6, True)
  244. else:
  245. self.ui.geo_tools_table.setColumnHidden(6, False)
  246. self.set_tool_offset_visibility(selected_row)
  247. # -----------------------------
  248. # Build Exclusion Areas section
  249. # -----------------------------
  250. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  251. self.ui.exclusion_table.setRowCount(e_len)
  252. area_id = 0
  253. for area in range(e_len):
  254. area_id += 1
  255. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  256. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  257. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  258. self.ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  259. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  260. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  261. self.ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  262. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  263. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  264. self.ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  265. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  266. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  267. self.ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  268. self.ui.exclusion_table.resizeColumnsToContents()
  269. self.ui.exclusion_table.resizeRowsToContents()
  270. area_vheader = self.ui.exclusion_table.verticalHeader()
  271. area_vheader.hide()
  272. self.ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  273. area_hheader = self.ui.exclusion_table.horizontalHeader()
  274. area_hheader.setMinimumSectionSize(10)
  275. area_hheader.setDefaultSectionSize(70)
  276. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  277. area_hheader.resizeSection(0, 20)
  278. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  279. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  280. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  281. # area_hheader.setStretchLastSection(True)
  282. self.ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  283. self.ui.exclusion_table.setColumnWidth(0, 20)
  284. self.ui.exclusion_table.setMinimumHeight(self.ui.exclusion_table.getHeight())
  285. self.ui.exclusion_table.setMaximumHeight(self.ui.exclusion_table.getHeight())
  286. # End Build Exclusion Areas
  287. # -----------------------------
  288. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  289. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  290. self.ui.name_entry.set_value(self.options['name'])
  291. self.ui_connect()
  292. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  293. self.ui.e_cut_entry.setDisabled(True)
  294. # set the text on tool_data_label after loading the object
  295. sel_rows = []
  296. sel_items = self.ui.geo_tools_table.selectedItems()
  297. for it in sel_items:
  298. sel_rows.append(it.row())
  299. if len(sel_rows) > 1:
  300. self.ui.tool_data_label.setText(
  301. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  302. )
  303. def set_ui(self, ui):
  304. FlatCAMObj.set_ui(self, ui)
  305. log.debug("GeometryObject.set_ui()")
  306. assert isinstance(self.ui, GeometryObjectUI), \
  307. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  308. self.units = self.app.defaults['units'].upper()
  309. self.units_found = self.app.defaults['units']
  310. # populate preprocessor names in the combobox
  311. for name in list(self.app.preprocessors.keys()):
  312. self.ui.pp_geometry_name_cb.addItem(name)
  313. self.form_fields.update({
  314. "plot": self.ui.plot_cb,
  315. "multicolored": self.ui.multicolored_cb,
  316. "cutz": self.ui.cutz_entry,
  317. "vtipdia": self.ui.tipdia_entry,
  318. "vtipangle": self.ui.tipangle_entry,
  319. "travelz": self.ui.travelz_entry,
  320. "feedrate": self.ui.cncfeedrate_entry,
  321. "feedrate_z": self.ui.feedrate_z_entry,
  322. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  323. "spindlespeed": self.ui.cncspindlespeed_entry,
  324. "dwell": self.ui.dwell_cb,
  325. "dwelltime": self.ui.dwelltime_entry,
  326. "multidepth": self.ui.mpass_cb,
  327. "ppname_g": self.ui.pp_geometry_name_cb,
  328. "z_pdepth": self.ui.pdepth_entry,
  329. "feedrate_probe": self.ui.feedrate_probe_entry,
  330. "depthperpass": self.ui.maxdepth_entry,
  331. "extracut": self.ui.extracut_cb,
  332. "extracut_length": self.ui.e_cut_entry,
  333. "toolchange": self.ui.toolchangeg_cb,
  334. "toolchangez": self.ui.toolchangez_entry,
  335. "endz": self.ui.endz_entry,
  336. "endxy": self.ui.endxy_entry,
  337. "cnctooldia": self.ui.addtool_entry,
  338. "area_exclusion": self.ui.exclusion_cb,
  339. "area_shape": self.ui.area_shape_radio,
  340. "area_strategy": self.ui.strategy_radio,
  341. "area_overz": self.ui.over_z_entry,
  342. })
  343. self.param_fields.update({
  344. "vtipdia": self.ui.tipdia_entry,
  345. "vtipangle": self.ui.tipangle_entry,
  346. "cutz": self.ui.cutz_entry,
  347. "depthperpass": self.ui.maxdepth_entry,
  348. "multidepth": self.ui.mpass_cb,
  349. "travelz": self.ui.travelz_entry,
  350. "feedrate": self.ui.cncfeedrate_entry,
  351. "feedrate_z": self.ui.feedrate_z_entry,
  352. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  353. "extracut": self.ui.extracut_cb,
  354. "extracut_length": self.ui.e_cut_entry,
  355. "spindlespeed": self.ui.cncspindlespeed_entry,
  356. "dwelltime": self.ui.dwelltime_entry,
  357. "dwell": self.ui.dwell_cb,
  358. "pdepth": self.ui.pdepth_entry,
  359. "pfeedrate": self.ui.feedrate_probe_entry,
  360. })
  361. # Fill form fields only on object create
  362. self.to_form()
  363. # update the changes in UI depending on the selected preprocessor in Preferences
  364. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  365. # self.ui.pp_geometry_name_cb combobox
  366. self.on_pp_changed()
  367. self.ui.tipdialabel.hide()
  368. self.ui.tipdia_entry.hide()
  369. self.ui.tipanglelabel.hide()
  370. self.ui.tipangle_entry.hide()
  371. self.ui.cutz_entry.setDisabled(False)
  372. # store here the default data for Geometry Data
  373. self.default_data = {}
  374. self.default_data.update({
  375. "name": None,
  376. "plot": None,
  377. "cutz": None,
  378. "vtipdia": None,
  379. "vtipangle": None,
  380. "travelz": None,
  381. "feedrate": None,
  382. "feedrate_z": None,
  383. "feedrate_rapid": None,
  384. "dwell": None,
  385. "dwelltime": None,
  386. "multidepth": None,
  387. "ppname_g": None,
  388. "depthperpass": None,
  389. "extracut": None,
  390. "extracut_length": None,
  391. "toolchange": None,
  392. "toolchangez": None,
  393. "endz": None,
  394. "endxy": '',
  395. "area_exclusion": None,
  396. "area_shape": None,
  397. "area_strategy": None,
  398. "area_overz": None,
  399. "spindlespeed": 0,
  400. "toolchangexy": None,
  401. "startz": None
  402. })
  403. # fill in self.default_data values from self.options
  404. for def_key in self.default_data:
  405. for opt_key, opt_val in self.options.items():
  406. if def_key == opt_key:
  407. self.default_data[def_key] = deepcopy(opt_val)
  408. if type(self.options["cnctooldia"]) == float:
  409. tools_list = [self.options["cnctooldia"]]
  410. else:
  411. try:
  412. temp_tools = self.options["cnctooldia"].split(",")
  413. tools_list = [
  414. float(eval(dia)) for dia in temp_tools if dia != ''
  415. ]
  416. except Exception as e:
  417. log.error("GeometryObject.set_ui() -> At least one tool diameter needed. "
  418. "Verify in Edit -> Preferences -> Geometry General -> Tool dia. %s" % str(e))
  419. return
  420. self.tooluid += 1
  421. if not self.tools:
  422. for toold in tools_list:
  423. new_data = deepcopy(self.default_data)
  424. self.tools.update({
  425. self.tooluid: {
  426. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  427. 'offset': 'Path',
  428. 'offset_value': 0.0,
  429. 'type': _('Rough'),
  430. 'tool_type': self.tool_type,
  431. 'data': new_data,
  432. 'solid_geometry': self.solid_geometry
  433. }
  434. })
  435. self.tooluid += 1
  436. else:
  437. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  438. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  439. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  440. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  441. # following convoluted way of changing the keys from string to float type
  442. temp_tools = {}
  443. for tooluid_key in self.tools:
  444. val = deepcopy(self.tools[tooluid_key])
  445. new_key = deepcopy(int(tooluid_key))
  446. temp_tools[new_key] = val
  447. self.tools.clear()
  448. self.tools = deepcopy(temp_tools)
  449. self.ui.tool_offset_entry.hide()
  450. self.ui.tool_offset_lbl.hide()
  451. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  452. self.old_pp_state = self.default_data['multidepth']
  453. self.old_toolchangeg_state = self.default_data['toolchange']
  454. if not isinstance(self.ui, GeometryObjectUI):
  455. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  456. return
  457. self.ui.geo_tools_table.setupContextMenu()
  458. self.ui.geo_tools_table.addContextMenu(
  459. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  460. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  461. self.ui.geo_tools_table.addContextMenu(
  462. _("Copy"), self.on_tool_copy,
  463. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  464. self.ui.geo_tools_table.addContextMenu(
  465. _("Delete"), lambda: self.on_tool_delete(all_tools=None),
  466. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  467. # Show/Hide Advanced Options
  468. if self.app.defaults["global_app_level"] == 'b':
  469. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  470. self.ui.geo_tools_table.setColumnHidden(2, True)
  471. self.ui.geo_tools_table.setColumnHidden(3, True)
  472. # self.ui.geo_tools_table.setColumnHidden(4, True)
  473. self.ui.addtool_entry_lbl.hide()
  474. self.ui.addtool_entry.hide()
  475. self.ui.addtool_btn.hide()
  476. self.ui.copytool_btn.hide()
  477. self.ui.deltool_btn.hide()
  478. # self.ui.endz_label.hide()
  479. # self.ui.endz_entry.hide()
  480. self.ui.fr_rapidlabel.hide()
  481. self.ui.feedrate_rapid_entry.hide()
  482. self.ui.extracut_cb.hide()
  483. self.ui.e_cut_entry.hide()
  484. self.ui.pdepth_label.hide()
  485. self.ui.pdepth_entry.hide()
  486. self.ui.feedrate_probe_label.hide()
  487. self.ui.feedrate_probe_entry.hide()
  488. else:
  489. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  490. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  491. self.ui.e_cut_entry.setDisabled(True)
  492. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  493. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  494. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  495. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  496. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  497. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  498. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  499. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  500. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  501. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  502. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  503. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  504. # Exclusion areas signals
  505. self.ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  506. self.ui.exclusion_table.lost_focus.connect(self.clear_selection)
  507. self.ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  508. self.ui.add_area_button.clicked.connect(self.on_add_area_click)
  509. self.ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  510. self.ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  511. self.ui.strategy_radio.activated_custom.connect(self.on_strategy)
  512. def on_cut_z_changed(self):
  513. self.old_cutz = self.ui.cutz_entry.get_value()
  514. def set_tool_offset_visibility(self, current_row):
  515. if current_row is None:
  516. return
  517. try:
  518. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  519. if tool_offset is not None:
  520. tool_offset_txt = tool_offset.currentText()
  521. if tool_offset_txt == 'Custom':
  522. self.ui.tool_offset_entry.show()
  523. self.ui.tool_offset_lbl.show()
  524. else:
  525. self.ui.tool_offset_entry.hide()
  526. self.ui.tool_offset_lbl.hide()
  527. except Exception as e:
  528. log.debug("set_tool_offset_visibility() --> " + str(e))
  529. return
  530. def on_offset_value_edited(self):
  531. """
  532. This will save the offset_value into self.tools storage whenever the offset value is edited
  533. :return:
  534. """
  535. for current_row in self.ui.geo_tools_table.selectedItems():
  536. # sometime the header get selected and it has row number -1
  537. # we don't want to do anything with the header :)
  538. if current_row.row() < 0:
  539. continue
  540. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  541. self.set_tool_offset_visibility(current_row.row())
  542. for tooluid_key, tooluid_value in self.tools.items():
  543. if int(tooluid_key) == tool_uid:
  544. try:
  545. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  546. except ValueError:
  547. # try to convert comma to decimal point. if it's still not working error message and return
  548. try:
  549. tooluid_value['offset_value'] = float(
  550. self.ui.tool_offset_entry.get_value().replace(',', '.')
  551. )
  552. except ValueError:
  553. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  554. return
  555. def ui_connect(self):
  556. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  557. # changes in geometry UI
  558. for i in self.param_fields:
  559. current_widget = self.param_fields[i]
  560. if isinstance(current_widget, FCCheckBox):
  561. current_widget.stateChanged.connect(self.gui_form_to_storage)
  562. elif isinstance(current_widget, FCComboBox):
  563. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  564. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  565. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  566. current_widget.editingFinished.connect(self.gui_form_to_storage)
  567. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  568. current_widget.returnPressed.connect(self.gui_form_to_storage)
  569. for row in range(self.ui.geo_tools_table.rowCount()):
  570. for col in [2, 3, 4]:
  571. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  572. self.on_tooltable_cellwidget_change)
  573. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  574. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  575. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  576. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  577. # self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  578. self.ui.geo_tools_table.clicked.connect(self.on_row_selection_change)
  579. self.ui.geo_tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  580. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  581. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  582. for row in range(self.ui.geo_tools_table.rowCount()):
  583. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  584. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  585. # common parameters update
  586. self.ui.pp_geometry_name_cb.currentIndexChanged.connect(self.update_common_param_in_storage)
  587. def ui_disconnect(self):
  588. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  589. # changes in geometry UI
  590. for i in self.param_fields:
  591. # current_widget = self.ui.grid3.itemAt(i).widget()
  592. current_widget = self.param_fields[i]
  593. if isinstance(current_widget, FCCheckBox):
  594. try:
  595. current_widget.stateChanged.disconnect(self.gui_form_to_storage)
  596. except (TypeError, AttributeError):
  597. pass
  598. elif isinstance(current_widget, FCComboBox):
  599. try:
  600. current_widget.currentIndexChanged.disconnect(self.gui_form_to_storage)
  601. except (TypeError, AttributeError):
  602. pass
  603. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  604. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  605. try:
  606. current_widget.editingFinished.disconnect(self.gui_form_to_storage)
  607. except (TypeError, AttributeError):
  608. pass
  609. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  610. try:
  611. current_widget.returnPressed.disconnect(self.gui_form_to_storage)
  612. except TypeError:
  613. pass
  614. for row in range(self.ui.geo_tools_table.rowCount()):
  615. for col in [2, 3, 4]:
  616. try:
  617. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  618. except (TypeError, AttributeError):
  619. pass
  620. try:
  621. self.ui.addtool_btn.clicked.disconnect()
  622. except (TypeError, AttributeError):
  623. pass
  624. try:
  625. self.ui.copytool_btn.clicked.disconnect()
  626. except (TypeError, AttributeError):
  627. pass
  628. try:
  629. self.ui.deltool_btn.clicked.disconnect()
  630. except (TypeError, AttributeError):
  631. pass
  632. try:
  633. self.ui.geo_tools_table.clicked.disconnect()
  634. except (TypeError, AttributeError):
  635. pass
  636. try:
  637. self.ui.geo_tools_table.horizontalHeader().sectionClicked.disconnect()
  638. except (TypeError, AttributeError):
  639. pass
  640. try:
  641. self.ui.geo_tools_table.itemChanged.disconnect()
  642. except (TypeError, AttributeError):
  643. pass
  644. try:
  645. self.ui.tool_offset_entry.returnPressed.disconnect()
  646. except (TypeError, AttributeError):
  647. pass
  648. for row in range(self.ui.geo_tools_table.rowCount()):
  649. try:
  650. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  651. except (TypeError, AttributeError):
  652. pass
  653. try:
  654. self.ui.plot_cb.stateChanged.disconnect()
  655. except (TypeError, AttributeError):
  656. pass
  657. def on_row_selection_change(self):
  658. self.update_ui()
  659. def update_ui(self, row=None):
  660. self.ui_disconnect()
  661. if row is None:
  662. sel_rows = []
  663. sel_items = self.ui.geo_tools_table.selectedItems()
  664. for it in sel_items:
  665. sel_rows.append(it.row())
  666. else:
  667. sel_rows = row if type(row) == list else [row]
  668. if not sel_rows:
  669. sel_rows = [0]
  670. for current_row in sel_rows:
  671. self.set_tool_offset_visibility(current_row)
  672. # populate the form with the data from the tool associated with the row parameter
  673. try:
  674. item = self.ui.geo_tools_table.item(current_row, 5)
  675. if type(item) is not None:
  676. tooluid = int(item.text())
  677. else:
  678. self.ui_connect()
  679. return
  680. except Exception as e:
  681. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  682. self.ui_connect()
  683. return
  684. # update the QLabel that shows for which Tool we have the parameters in the UI form
  685. if len(sel_rows) == 1:
  686. self.ui.tool_data_label.setText(
  687. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  688. )
  689. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  690. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  691. try:
  692. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  693. if item is not None:
  694. tool_type_txt = item.currentText()
  695. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  696. else:
  697. self.ui_connect()
  698. return
  699. except Exception as e:
  700. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  701. return
  702. try:
  703. # set the form with data from the newly selected tool
  704. for tooluid_key, tooluid_value in list(self.tools.items()):
  705. if int(tooluid_key) == tooluid:
  706. for key, value in list(tooluid_value.items()):
  707. if key == 'data':
  708. form_value_storage = tooluid_value['data']
  709. self.update_form(form_value_storage)
  710. if key == 'offset_value':
  711. # update the offset value in the entry even if the entry is hidden
  712. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  713. if key == 'tool_type' and value == 'V':
  714. self.update_cutz()
  715. except Exception as e:
  716. log.debug("GeometryObject.update_ui() -> %s " % str(e))
  717. else:
  718. self.ui.tool_data_label.setText(
  719. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  720. )
  721. self.ui_connect()
  722. def on_tool_add(self, dia=None):
  723. self.ui_disconnect()
  724. self.units = self.app.defaults['units'].upper()
  725. if dia is not None:
  726. tooldia = dia
  727. else:
  728. tooldia = float(self.ui.addtool_entry.get_value())
  729. # construct a list of all 'tooluid' in the self.tools
  730. # tool_uid_list = []
  731. # for tooluid_key in self.tools:
  732. # tool_uid_list.append(int(tooluid_key))
  733. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  734. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  735. max_uid = max(tool_uid_list) if tool_uid_list else 0
  736. self.tooluid = max_uid + 1
  737. tooldia = float('%.*f' % (self.decimals, tooldia))
  738. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  739. # otherwise we add a tool with data copied from last tool
  740. if self.tools:
  741. last_data = self.tools[max_uid]['data']
  742. last_offset = self.tools[max_uid]['offset']
  743. last_offset_value = self.tools[max_uid]['offset_value']
  744. last_type = self.tools[max_uid]['type']
  745. last_tool_type = self.tools[max_uid]['tool_type']
  746. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  747. # if previous geometry was empty (it may happen for the first tool added)
  748. # then copy the object.solid_geometry
  749. if not last_solid_geometry:
  750. last_solid_geometry = self.solid_geometry
  751. self.tools.update({
  752. self.tooluid: {
  753. 'tooldia': tooldia,
  754. 'offset': last_offset,
  755. 'offset_value': last_offset_value,
  756. 'type': last_type,
  757. 'tool_type': last_tool_type,
  758. 'data': deepcopy(last_data),
  759. 'solid_geometry': deepcopy(last_solid_geometry)
  760. }
  761. })
  762. else:
  763. self.tools.update({
  764. self.tooluid: {
  765. 'tooldia': tooldia,
  766. 'offset': 'Path',
  767. 'offset_value': 0.0,
  768. 'type': _('Rough'),
  769. 'tool_type': 'C1',
  770. 'data': deepcopy(self.default_data),
  771. 'solid_geometry': self.solid_geometry
  772. }
  773. })
  774. self.tools[self.tooluid]['data']['name'] = self.options['name']
  775. self.ui.tool_offset_entry.hide()
  776. self.ui.tool_offset_lbl.hide()
  777. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  778. try:
  779. self.ser_attrs.remove('tools')
  780. except TypeError:
  781. pass
  782. self.ser_attrs.append('tools')
  783. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  784. self.ui_connect()
  785. self.build_ui()
  786. # if there is no tool left in the Tools Table, enable the parameters appGUI
  787. if self.ui.geo_tools_table.rowCount() != 0:
  788. self.ui.geo_param_frame.setDisabled(False)
  789. def on_tool_add_from_db_clicked(self):
  790. """
  791. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  792. and display the Tools Database tab in the form needed for the Tool adding
  793. :return: None
  794. """
  795. # if the Tools Database is already opened focus on it
  796. for idx in range(self.app.ui.plot_tab_area.count()):
  797. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  798. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  799. break
  800. self.app.on_tools_database()
  801. self.app.tools_db_tab.ok_to_add = True
  802. self.app.tools_db_tab.buttons_frame.hide()
  803. self.app.tools_db_tab.add_tool_from_db.show()
  804. self.app.tools_db_tab.cancel_tool_from_db.show()
  805. def on_tool_from_db_inserted(self, tool):
  806. """
  807. Called from the Tools DB object through a App method when adding a tool from Tools Database
  808. :param tool: a dict with the tool data
  809. :return: None
  810. """
  811. self.ui_disconnect()
  812. self.units = self.app.defaults['units'].upper()
  813. tooldia = float(tool['tooldia'])
  814. # construct a list of all 'tooluid' in the self.tools
  815. tool_uid_list = []
  816. for tooluid_key in self.tools:
  817. tool_uid_item = int(tooluid_key)
  818. tool_uid_list.append(tool_uid_item)
  819. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  820. if not tool_uid_list:
  821. max_uid = 0
  822. else:
  823. max_uid = max(tool_uid_list)
  824. self.tooluid = max_uid + 1
  825. tooldia = float('%.*f' % (self.decimals, tooldia))
  826. self.tools.update({
  827. self.tooluid: {
  828. 'tooldia': tooldia,
  829. 'offset': tool['offset'],
  830. 'offset_value': float(tool['offset_value']),
  831. 'type': tool['type'],
  832. 'tool_type': tool['tool_type'],
  833. 'data': deepcopy(tool['data']),
  834. 'solid_geometry': self.solid_geometry
  835. }
  836. })
  837. self.tools[self.tooluid]['data']['name'] = self.options['name']
  838. self.ui.tool_offset_entry.hide()
  839. self.ui.tool_offset_lbl.hide()
  840. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  841. try:
  842. self.ser_attrs.remove('tools')
  843. except TypeError:
  844. pass
  845. self.ser_attrs.append('tools')
  846. self.ui_connect()
  847. self.build_ui()
  848. # if there is no tool left in the Tools Table, enable the parameters appGUI
  849. if self.ui.geo_tools_table.rowCount() != 0:
  850. self.ui.geo_param_frame.setDisabled(False)
  851. def on_tool_copy(self, all_tools=None):
  852. self.ui_disconnect()
  853. # find the tool_uid maximum value in the self.tools
  854. uid_list = []
  855. for key in self.tools:
  856. uid_list.append(int(key))
  857. try:
  858. max_uid = max(uid_list, key=int)
  859. except ValueError:
  860. max_uid = 0
  861. if all_tools is None:
  862. if self.ui.geo_tools_table.selectedItems():
  863. for current_row in self.ui.geo_tools_table.selectedItems():
  864. # sometime the header get selected and it has row number -1
  865. # we don't want to do anything with the header :)
  866. if current_row.row() < 0:
  867. continue
  868. try:
  869. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  870. self.set_tool_offset_visibility(current_row.row())
  871. max_uid += 1
  872. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  873. except AttributeError:
  874. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  875. self.ui_connect()
  876. self.build_ui()
  877. return
  878. except Exception as e:
  879. log.debug("on_tool_copy() --> " + str(e))
  880. # deselect the table
  881. # self.ui.geo_tools_table.clearSelection()
  882. else:
  883. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  884. self.ui_connect()
  885. self.build_ui()
  886. return
  887. else:
  888. # we copy all tools in geo_tools_table
  889. try:
  890. temp_tools = deepcopy(self.tools)
  891. max_uid += 1
  892. for tooluid in temp_tools:
  893. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  894. temp_tools.clear()
  895. except Exception as e:
  896. log.debug("on_tool_copy() --> " + str(e))
  897. # if there are no more tools in geo tools table then hide the tool offset
  898. if not self.tools:
  899. self.ui.tool_offset_entry.hide()
  900. self.ui.tool_offset_lbl.hide()
  901. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  902. try:
  903. self.ser_attrs.remove('tools')
  904. except ValueError:
  905. pass
  906. self.ser_attrs.append('tools')
  907. self.ui_connect()
  908. self.build_ui()
  909. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  910. def on_tool_edit(self, current_item):
  911. self.ui_disconnect()
  912. current_row = current_item.row()
  913. try:
  914. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  915. except ValueError:
  916. # try to convert comma to decimal point. if it's still not working error message and return
  917. try:
  918. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  919. except ValueError:
  920. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  921. return
  922. tool_dia = float('%.*f' % (self.decimals, d))
  923. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  924. self.tools[tooluid]['tooldia'] = tool_dia
  925. try:
  926. self.ser_attrs.remove('tools')
  927. self.ser_attrs.append('tools')
  928. except (TypeError, ValueError):
  929. pass
  930. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  931. self.ui_connect()
  932. self.build_ui()
  933. def on_tool_delete(self, all_tools=None):
  934. self.ui_disconnect()
  935. if all_tools is None:
  936. if self.ui.geo_tools_table.selectedItems():
  937. for current_row in self.ui.geo_tools_table.selectedItems():
  938. # sometime the header get selected and it has row number -1
  939. # we don't want to do anything with the header :)
  940. if current_row.row() < 0:
  941. continue
  942. try:
  943. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  944. self.set_tool_offset_visibility(current_row.row())
  945. temp_tools = deepcopy(self.tools)
  946. for tooluid_key in self.tools:
  947. if int(tooluid_key) == tooluid_del:
  948. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  949. # as a property of the object otherwise there will be nothing to hold it
  950. if len(self.tools) == 1:
  951. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  952. temp_tools.pop(tooluid_del, None)
  953. self.tools = deepcopy(temp_tools)
  954. temp_tools.clear()
  955. except AttributeError:
  956. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  957. self.ui_connect()
  958. self.build_ui()
  959. return
  960. except Exception as e:
  961. log.debug("on_tool_delete() --> " + str(e))
  962. # deselect the table
  963. # self.ui.geo_tools_table.clearSelection()
  964. else:
  965. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  966. self.ui_connect()
  967. self.build_ui()
  968. return
  969. else:
  970. # we delete all tools in geo_tools_table
  971. self.tools.clear()
  972. self.app.plot_all()
  973. # if there are no more tools in geo tools table then hide the tool offset
  974. if not self.tools:
  975. self.ui.tool_offset_entry.hide()
  976. self.ui.tool_offset_lbl.hide()
  977. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  978. try:
  979. self.ser_attrs.remove('tools')
  980. except TypeError:
  981. pass
  982. self.ser_attrs.append('tools')
  983. self.ui_connect()
  984. self.build_ui()
  985. self.app.inform.emit('[success] %s' % _("Tool was deleted in Tool Table."))
  986. obj_active = self.app.collection.get_active()
  987. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  988. # we make it back SingleGeo
  989. if self.ui.geo_tools_table.rowCount() <= 0:
  990. obj_active.multigeo = False
  991. obj_active.options['xmin'] = 0
  992. obj_active.options['ymin'] = 0
  993. obj_active.options['xmax'] = 0
  994. obj_active.options['ymax'] = 0
  995. if obj_active.multigeo is True:
  996. try:
  997. xmin, ymin, xmax, ymax = obj_active.bounds()
  998. obj_active.options['xmin'] = xmin
  999. obj_active.options['ymin'] = ymin
  1000. obj_active.options['xmax'] = xmax
  1001. obj_active.options['ymax'] = ymax
  1002. except Exception:
  1003. obj_active.options['xmin'] = 0
  1004. obj_active.options['ymin'] = 0
  1005. obj_active.options['xmax'] = 0
  1006. obj_active.options['ymax'] = 0
  1007. # if there is no tool left in the Tools Table, disable the parameters appGUI
  1008. if self.ui.geo_tools_table.rowCount() == 0:
  1009. self.ui.geo_param_frame.setDisabled(True)
  1010. def ui_update_v_shape(self, tool_type_txt):
  1011. if tool_type_txt == 'V':
  1012. self.ui.tipdialabel.show()
  1013. self.ui.tipdia_entry.show()
  1014. self.ui.tipanglelabel.show()
  1015. self.ui.tipangle_entry.show()
  1016. self.ui.cutz_entry.setDisabled(True)
  1017. self.ui.cutzlabel.setToolTip(
  1018. _("Disabled because the tool is V-shape.\n"
  1019. "For V-shape tools the depth of cut is\n"
  1020. "calculated from other parameters like:\n"
  1021. "- 'V-tip Angle' -> angle at the tip of the tool\n"
  1022. "- 'V-tip Dia' -> diameter at the tip of the tool \n"
  1023. "- Tool Dia -> 'Dia' column found in the Tool Table\n"
  1024. "NB: a value of zero means that Tool Dia = 'V-tip Dia'")
  1025. )
  1026. self.ui.cutz_entry.setToolTip(
  1027. _("Disabled because the tool is V-shape.\n"
  1028. "For V-shape tools the depth of cut is\n"
  1029. "calculated from other parameters like:\n"
  1030. "- 'V-tip Angle' -> angle at the tip of the tool\n"
  1031. "- 'V-tip Dia' -> diameter at the tip of the tool \n"
  1032. "- Tool Dia -> 'Dia' column found in the Tool Table\n"
  1033. "NB: a value of zero means that Tool Dia = 'V-tip Dia'")
  1034. )
  1035. self.update_cutz()
  1036. else:
  1037. self.ui.tipdialabel.hide()
  1038. self.ui.tipdia_entry.hide()
  1039. self.ui.tipanglelabel.hide()
  1040. self.ui.tipangle_entry.hide()
  1041. self.ui.cutz_entry.setDisabled(False)
  1042. self.ui.cutzlabel.setToolTip(
  1043. _("Cutting depth (negative)\n"
  1044. "below the copper surface.")
  1045. )
  1046. self.ui.cutz_entry.setToolTip('')
  1047. def update_cutz(self):
  1048. vdia = float(self.ui.tipdia_entry.get_value())
  1049. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  1050. row = self.ui.geo_tools_table.currentRow()
  1051. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  1052. if tool_uid_item is None:
  1053. return
  1054. tool_uid = int(tool_uid_item.text())
  1055. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  1056. if tool_dia_item is None:
  1057. return
  1058. tooldia = float(tool_dia_item.text())
  1059. try:
  1060. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  1061. except ZeroDivisionError:
  1062. new_cutz = self.old_cutz
  1063. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  1064. self.ui.cutz_entry.set_value(new_cutz)
  1065. # store the new CutZ value into storage (self.tools)
  1066. for tooluid_key, tooluid_value in self.tools.items():
  1067. if int(tooluid_key) == tool_uid:
  1068. tooluid_value['data']['cutz'] = new_cutz
  1069. def on_tooltable_cellwidget_change(self):
  1070. cw = self.sender()
  1071. # assert isinstance(cw, FCComboBox) or isinstance(cw, FCCheckBox),\
  1072. # "Expected a FCCombobox or a FCCheckbox got %s" % type(cw)
  1073. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  1074. cw_row = cw_index.row()
  1075. cw_col = cw_index.column()
  1076. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  1077. # store the text of the cellWidget that changed it's index in the self.tools
  1078. for tooluid_key, tooluid_value in self.tools.items():
  1079. if int(tooluid_key) == current_uid:
  1080. cb_txt = cw.currentText()
  1081. if cw_col == 2:
  1082. tooluid_value['offset'] = cb_txt
  1083. if cb_txt == 'Custom':
  1084. self.ui.tool_offset_entry.show()
  1085. self.ui.tool_offset_lbl.show()
  1086. else:
  1087. self.ui.tool_offset_entry.hide()
  1088. self.ui.tool_offset_lbl.hide()
  1089. # reset the offset_value in storage self.tools
  1090. tooluid_value['offset_value'] = 0.0
  1091. elif cw_col == 3:
  1092. # force toolpath type as 'Iso' if the tool type is V-Shape
  1093. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  1094. tooluid_value['type'] = _('Iso')
  1095. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  1096. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  1097. else:
  1098. tooluid_value['type'] = cb_txt
  1099. elif cw_col == 4:
  1100. tooluid_value['tool_type'] = cb_txt
  1101. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  1102. if cb_txt == 'V':
  1103. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  1104. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  1105. else:
  1106. self.ui.cutz_entry.set_value(self.old_cutz)
  1107. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  1108. def update_form(self, dict_storage):
  1109. for form_key in self.form_fields:
  1110. for storage_key in dict_storage:
  1111. if form_key == storage_key:
  1112. try:
  1113. self.form_fields[form_key].set_value(dict_storage[form_key])
  1114. except Exception as e:
  1115. log.debug(str(e))
  1116. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  1117. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  1118. self.ui.ois_dwell_geo.on_cb_change()
  1119. self.ui.ois_mpass_geo.on_cb_change()
  1120. self.ui.ois_tcz_geo.on_cb_change()
  1121. def on_apply_param_to_all_clicked(self):
  1122. if self.ui.geo_tools_table.rowCount() == 0:
  1123. # there is no tool in tool table so we can't save the GUI elements values to storage
  1124. log.debug("GeometryObject.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  1125. return
  1126. self.ui_disconnect()
  1127. row = self.ui.geo_tools_table.currentRow()
  1128. if row < 0:
  1129. row = 0
  1130. # store all the data associated with the row parameter to the self.tools storage
  1131. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  1132. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  1133. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  1134. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  1135. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  1136. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  1137. temp_tools = {}
  1138. temp_dia = {}
  1139. temp_data = {}
  1140. for tooluid_key, tooluid_value in self.tools.items():
  1141. for key, value in tooluid_value.items():
  1142. if key == 'tooldia':
  1143. temp_dia[key] = tooldia_item
  1144. # update the 'offset', 'type' and 'tool_type' sections
  1145. if key == 'offset':
  1146. temp_dia[key] = offset_item
  1147. if key == 'type':
  1148. temp_dia[key] = type_item
  1149. if key == 'tool_type':
  1150. temp_dia[key] = tool_type_item
  1151. if key == 'offset_value':
  1152. temp_dia[key] = offset_value_item
  1153. if key == 'data':
  1154. # update the 'data' section
  1155. for data_key in tooluid_value[key].keys():
  1156. for form_key, form_value in self.form_fields.items():
  1157. if form_key == data_key:
  1158. temp_data[data_key] = form_value.get_value()
  1159. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  1160. # updated from self.app.defaults
  1161. if data_key not in self.form_fields:
  1162. temp_data[data_key] = value[data_key]
  1163. temp_dia[key] = deepcopy(temp_data)
  1164. temp_data.clear()
  1165. if key == 'solid_geometry':
  1166. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  1167. temp_tools[tooluid_key] = deepcopy(temp_dia)
  1168. self.tools.clear()
  1169. self.tools = deepcopy(temp_tools)
  1170. temp_tools.clear()
  1171. self.ui_connect()
  1172. def gui_form_to_storage(self):
  1173. self.ui_disconnect()
  1174. if self.ui.geo_tools_table.rowCount() == 0:
  1175. # there is no tool in tool table so we can't save the GUI elements values to storage
  1176. log.debug("GeometryObject.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  1177. return
  1178. widget_changed = self.sender()
  1179. try:
  1180. widget_idx = self.ui.grid3.indexOf(widget_changed)
  1181. except Exception as e:
  1182. log.debug("GeometryObject.gui_form_to_storage() -- wdg index -> %s" % str(e))
  1183. return
  1184. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  1185. if widget_idx == 1 or widget_idx == 3:
  1186. self.update_cutz()
  1187. # the original connect() function of the OptionalInputSelection is no longer working because of the
  1188. # ui_diconnect() so I use this 'hack'
  1189. if isinstance(widget_changed, FCCheckBox):
  1190. if widget_changed.text() == 'Multi-Depth:':
  1191. self.ui.ois_mpass_geo.on_cb_change()
  1192. if widget_changed.text() == 'Tool change':
  1193. self.ui.ois_tcz_geo.on_cb_change()
  1194. if widget_changed.text() == 'Dwell:':
  1195. self.ui.ois_dwell_geo.on_cb_change()
  1196. row = self.ui.geo_tools_table.currentRow()
  1197. if row < 0:
  1198. row = 0
  1199. # store all the data associated with the row parameter to the self.tools storage
  1200. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  1201. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  1202. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  1203. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  1204. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  1205. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  1206. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  1207. temp_tools = {}
  1208. temp_dia = {}
  1209. temp_data = {}
  1210. for tooluid_key, tooluid_value in self.tools.items():
  1211. if int(tooluid_key) == tooluid_item:
  1212. for key, value in tooluid_value.items():
  1213. if key == 'tooldia':
  1214. temp_dia[key] = tooldia_item
  1215. # update the 'offset', 'type' and 'tool_type' sections
  1216. if key == 'offset':
  1217. temp_dia[key] = offset_item
  1218. if key == 'type':
  1219. temp_dia[key] = type_item
  1220. if key == 'tool_type':
  1221. temp_dia[key] = tool_type_item
  1222. if key == 'offset_value':
  1223. temp_dia[key] = offset_value_item
  1224. if key == 'data':
  1225. # update the 'data' section
  1226. for data_key in tooluid_value[key].keys():
  1227. for form_key, form_value in self.form_fields.items():
  1228. if form_key == data_key:
  1229. temp_data[data_key] = form_value.get_value()
  1230. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  1231. # updated from self.app.defaults
  1232. if data_key not in self.form_fields:
  1233. temp_data[data_key] = value[data_key]
  1234. temp_dia[key] = deepcopy(temp_data)
  1235. temp_data.clear()
  1236. if key == 'solid_geometry':
  1237. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  1238. temp_tools[tooluid_key] = deepcopy(temp_dia)
  1239. else:
  1240. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  1241. self.tools.clear()
  1242. self.tools = deepcopy(temp_tools)
  1243. temp_tools.clear()
  1244. self.ui_connect()
  1245. def update_common_param_in_storage(self):
  1246. for tooluid_value in self.tools.values():
  1247. tooluid_value['data']['ppname_g'] = self.ui.pp_geometry_name_cb.get_value()
  1248. def select_tools_table_row(self, row, clearsel=None):
  1249. if clearsel:
  1250. self.ui.geo_tools_table.clearSelection()
  1251. if self.ui.geo_tools_table.rowCount() > 0:
  1252. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  1253. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  1254. def export_dxf(self):
  1255. dwg = None
  1256. try:
  1257. dwg = ezdxf.new('R2010')
  1258. msp = dwg.modelspace()
  1259. def g2dxf(dxf_space, geo_obj):
  1260. if isinstance(geo_obj, MultiPolygon):
  1261. for poly in geo_obj:
  1262. ext_points = list(poly.exterior.coords)
  1263. dxf_space.add_lwpolyline(ext_points)
  1264. for interior in poly.interiors:
  1265. dxf_space.add_lwpolyline(list(interior.coords))
  1266. if isinstance(geo_obj, Polygon):
  1267. ext_points = list(geo_obj.exterior.coords)
  1268. dxf_space.add_lwpolyline(ext_points)
  1269. for interior in geo_obj.interiors:
  1270. dxf_space.add_lwpolyline(list(interior.coords))
  1271. if isinstance(geo_obj, MultiLineString):
  1272. for line in geo_obj:
  1273. dxf_space.add_lwpolyline(list(line.coords))
  1274. if isinstance(geo_obj, LineString) or isinstance(geo_obj, LinearRing):
  1275. dxf_space.add_lwpolyline(list(geo_obj.coords))
  1276. multigeo_solid_geometry = []
  1277. if self.multigeo:
  1278. for tool in self.tools:
  1279. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  1280. else:
  1281. multigeo_solid_geometry = self.solid_geometry
  1282. for geo in multigeo_solid_geometry:
  1283. if type(geo) == list:
  1284. for g in geo:
  1285. g2dxf(msp, g)
  1286. else:
  1287. g2dxf(msp, geo)
  1288. # points = GeometryObject.get_pts(geo)
  1289. # msp.add_lwpolyline(points)
  1290. except Exception as e:
  1291. log.debug(str(e))
  1292. return dwg
  1293. def get_selected_tools_table_items(self):
  1294. """
  1295. Returns a list of lists, each list in the list is made out of row elements
  1296. :return: List of table_tools items.
  1297. :rtype: list
  1298. """
  1299. table_tools_items = []
  1300. if self.multigeo:
  1301. for x in self.ui.geo_tools_table.selectedItems():
  1302. elem = []
  1303. txt = ''
  1304. for column in range(0, self.ui.geo_tools_table.columnCount()):
  1305. try:
  1306. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  1307. except AttributeError:
  1308. try:
  1309. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  1310. except AttributeError:
  1311. pass
  1312. elem.append(txt)
  1313. table_tools_items.append(deepcopy(elem))
  1314. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  1315. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  1316. else:
  1317. for x in self.ui.geo_tools_table.selectedItems():
  1318. r = []
  1319. txt = ''
  1320. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  1321. # so we don't read them
  1322. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  1323. # the columns have items that have text but also have items that are widgets
  1324. # for which the text they hold has to be read differently
  1325. try:
  1326. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  1327. except AttributeError:
  1328. try:
  1329. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  1330. except AttributeError:
  1331. pass
  1332. r.append(txt)
  1333. table_tools_items.append(r)
  1334. for item in table_tools_items:
  1335. item[0] = str(item[0])
  1336. return table_tools_items
  1337. def on_pp_changed(self):
  1338. current_pp = self.ui.pp_geometry_name_cb.get_value()
  1339. if current_pp == 'hpgl':
  1340. self.old_pp_state = self.ui.mpass_cb.get_value()
  1341. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  1342. self.ui.mpass_cb.set_value(False)
  1343. self.ui.mpass_cb.setDisabled(True)
  1344. self.ui.toolchangeg_cb.set_value(True)
  1345. self.ui.toolchangeg_cb.setDisabled(True)
  1346. else:
  1347. self.ui.mpass_cb.set_value(self.old_pp_state)
  1348. self.ui.mpass_cb.setDisabled(False)
  1349. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  1350. self.ui.toolchangeg_cb.setDisabled(False)
  1351. if "toolchange_probe" in current_pp.lower():
  1352. self.ui.pdepth_entry.setVisible(True)
  1353. self.ui.pdepth_label.show()
  1354. self.ui.feedrate_probe_entry.setVisible(True)
  1355. self.ui.feedrate_probe_label.show()
  1356. else:
  1357. self.ui.pdepth_entry.setVisible(False)
  1358. self.ui.pdepth_label.hide()
  1359. self.ui.feedrate_probe_entry.setVisible(False)
  1360. self.ui.feedrate_probe_label.hide()
  1361. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  1362. self.ui.fr_rapidlabel.show()
  1363. self.ui.feedrate_rapid_entry.show()
  1364. else:
  1365. self.ui.fr_rapidlabel.hide()
  1366. self.ui.feedrate_rapid_entry.hide()
  1367. if 'laser' in current_pp.lower():
  1368. self.ui.cutzlabel.hide()
  1369. self.ui.cutz_entry.hide()
  1370. try:
  1371. self.ui.mpass_cb.hide()
  1372. self.ui.maxdepth_entry.hide()
  1373. except AttributeError:
  1374. pass
  1375. if 'marlin' in current_pp.lower():
  1376. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  1377. self.ui.endz_label.show()
  1378. self.ui.endz_entry.show()
  1379. else:
  1380. self.ui.travelzlabel.hide()
  1381. self.ui.travelz_entry.hide()
  1382. self.ui.endz_label.hide()
  1383. self.ui.endz_entry.hide()
  1384. try:
  1385. self.ui.frzlabel.hide()
  1386. self.ui.feedrate_z_entry.hide()
  1387. except AttributeError:
  1388. pass
  1389. self.ui.dwell_cb.hide()
  1390. self.ui.dwelltime_entry.hide()
  1391. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  1392. try:
  1393. self.ui.tool_offset_label.hide()
  1394. self.ui.offset_entry.hide()
  1395. except AttributeError:
  1396. pass
  1397. else:
  1398. self.ui.cutzlabel.show()
  1399. self.ui.cutz_entry.show()
  1400. try:
  1401. self.ui.mpass_cb.show()
  1402. self.ui.maxdepth_entry.show()
  1403. except AttributeError:
  1404. pass
  1405. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  1406. self.ui.travelzlabel.show()
  1407. self.ui.travelz_entry.show()
  1408. self.ui.endz_label.show()
  1409. self.ui.endz_entry.show()
  1410. try:
  1411. self.ui.frzlabel.show()
  1412. self.ui.feedrate_z_entry.show()
  1413. except AttributeError:
  1414. pass
  1415. self.ui.dwell_cb.show()
  1416. self.ui.dwelltime_entry.show()
  1417. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  1418. try:
  1419. self.ui.tool_offset_lbl.show()
  1420. self.ui.offset_entry.show()
  1421. except AttributeError:
  1422. pass
  1423. def on_generatecnc_button_click(self, *args):
  1424. log.debug("Generating CNCJob from Geometry ...")
  1425. self.app.defaults.report_usage("geometry_on_generatecnc_button")
  1426. # this reads the values in the UI form to the self.options dictionary
  1427. self.read_form()
  1428. self.sel_tools = {}
  1429. try:
  1430. if self.special_group:
  1431. self.app.inform.emit(
  1432. '[WARNING_NOTCL] %s %s %s.' %
  1433. (_("This Geometry can't be processed because it is"), str(self.special_group), _("geometry"))
  1434. )
  1435. return
  1436. except AttributeError:
  1437. pass
  1438. # test to see if we have tools available in the tool table
  1439. if self.ui.geo_tools_table.selectedItems():
  1440. for x in self.ui.geo_tools_table.selectedItems():
  1441. # try:
  1442. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  1443. # except ValueError:
  1444. # # try to convert comma to decimal point. if it's still not working error message and return
  1445. # try:
  1446. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  1447. # except ValueError:
  1448. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  1449. # _("Wrong value format entered, use a number."))
  1450. # return
  1451. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  1452. for tooluid_key, tooluid_value in self.tools.items():
  1453. if int(tooluid_key) == tooluid:
  1454. self.sel_tools.update({
  1455. tooluid: deepcopy(tooluid_value)
  1456. })
  1457. self.mtool_gen_cncjob()
  1458. self.ui.geo_tools_table.clearSelection()
  1459. elif self.ui.geo_tools_table.rowCount() == 1:
  1460. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  1461. for tooluid_key, tooluid_value in self.tools.items():
  1462. if int(tooluid_key) == tooluid:
  1463. self.sel_tools.update({
  1464. tooluid: deepcopy(tooluid_value)
  1465. })
  1466. self.mtool_gen_cncjob()
  1467. self.ui.geo_tools_table.clearSelection()
  1468. else:
  1469. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No tool selected in the tool table ..."))
  1470. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  1471. plot=True, use_thread=True):
  1472. """
  1473. Creates a multi-tool CNCJob out of this Geometry object.
  1474. The actual work is done by the target CNCJobObject object's
  1475. `generate_from_geometry_2()` method.
  1476. :param outname:
  1477. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  1478. (including the solid_geometry)
  1479. :param tools_in_use: the tools that are used, needed by some preprocessors
  1480. :type tools_in_use list of lists, each list in the list is made out of row elements of tools table from appGUI
  1481. :param segx: number of segments on the X axis, for auto-levelling
  1482. :param segy: number of segments on the Y axis, for auto-levelling
  1483. :param plot: if True the generated object will be plotted; if False will not be plotted
  1484. :param use_thread: if True use threading
  1485. :return: None
  1486. """
  1487. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  1488. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  1489. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  1490. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  1491. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  1492. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  1493. try:
  1494. xmin = self.options['xmin']
  1495. ymin = self.options['ymin']
  1496. xmax = self.options['xmax']
  1497. ymax = self.options['ymax']
  1498. except Exception as e:
  1499. log.debug("FlatCAMObj.GeometryObject.mtool_gen_cncjob() --> %s\n" % str(e))
  1500. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  1501. msg += '%s %s' % ('FlatCAMObj.GeometryObject.mtool_gen_cncjob() -->', str(e))
  1502. msg += traceback.format_exc()
  1503. self.app.inform.emit(msg)
  1504. return
  1505. # Object initialization function for app.app_obj.new_object()
  1506. # RUNNING ON SEPARATE THREAD!
  1507. def job_init_single_geometry(job_obj, app_obj):
  1508. log.debug("Creating a CNCJob out of a single-geometry")
  1509. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1510. job_obj.options['xmin'] = xmin
  1511. job_obj.options['ymin'] = ymin
  1512. job_obj.options['xmax'] = xmax
  1513. job_obj.options['ymax'] = ymax
  1514. # count the tools
  1515. tool_cnt = 0
  1516. # dia_cnc_dict = {}
  1517. # this turn on the FlatCAMCNCJob plot for multiple tools
  1518. job_obj.multitool = True
  1519. job_obj.multigeo = False
  1520. job_obj.cnc_tools.clear()
  1521. job_obj.options['Tools_in_use'] = tools_in_use
  1522. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  1523. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  1524. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  1525. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  1526. for tooluid_key in list(tools_dict.keys()):
  1527. tool_cnt += 1
  1528. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  1529. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  1530. dia_cnc_dict.update({
  1531. 'tooldia': tooldia_val
  1532. })
  1533. if dia_cnc_dict['offset'] == 'in':
  1534. tool_offset = -dia_cnc_dict['tooldia'] / 2
  1535. elif dia_cnc_dict['offset'].lower() == 'out':
  1536. tool_offset = dia_cnc_dict['tooldia'] / 2
  1537. elif dia_cnc_dict['offset'].lower() == 'custom':
  1538. try:
  1539. offset_value = float(self.ui.tool_offset_entry.get_value())
  1540. except ValueError:
  1541. # try to convert comma to decimal point. if it's still not working error message and return
  1542. try:
  1543. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  1544. except ValueError:
  1545. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1546. return
  1547. if offset_value:
  1548. tool_offset = float(offset_value)
  1549. else:
  1550. self.app.inform.emit(
  1551. '[WARNING] %s' % _("Tool Offset is selected in Tool Table but no value is provided.\n"
  1552. "Add a Tool Offset or change the Offset Type.")
  1553. )
  1554. return
  1555. else:
  1556. tool_offset = 0.0
  1557. dia_cnc_dict.update({
  1558. 'offset_value': tool_offset
  1559. })
  1560. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  1561. z_move = tools_dict[tooluid_key]['data']["travelz"]
  1562. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  1563. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  1564. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  1565. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  1566. extracut = tools_dict[tooluid_key]['data']["extracut"]
  1567. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  1568. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  1569. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  1570. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  1571. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  1572. startz = tools_dict[tooluid_key]['data']["startz"]
  1573. endz = tools_dict[tooluid_key]['data']["endz"]
  1574. endxy = self.options["endxy"]
  1575. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  1576. dwell = tools_dict[tooluid_key]['data']["dwell"]
  1577. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  1578. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  1579. spindledir = self.app.defaults['geometry_spindledir']
  1580. tool_solid_geometry = self.solid_geometry
  1581. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1582. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1583. # Propagate options
  1584. job_obj.options["tooldia"] = tooldia_val
  1585. job_obj.options['type'] = 'Geometry'
  1586. job_obj.options['tool_dia'] = tooldia_val
  1587. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1588. # to a value of 0.0005 which is 20 times less than 0.01
  1589. tol = float(self.app.defaults['global_tolerance']) / 20
  1590. res = job_obj.generate_from_geometry_2(
  1591. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  1592. z_cut=z_cut, z_move=z_move,
  1593. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1594. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  1595. multidepth=multidepth, depthpercut=depthpercut,
  1596. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1597. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1598. pp_geometry_name=pp_geometry_name,
  1599. tool_no=tool_cnt)
  1600. if res == 'fail':
  1601. log.debug("GeometryObject.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1602. return 'fail'
  1603. else:
  1604. dia_cnc_dict['gcode'] = res
  1605. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1606. # object is the source of gcode
  1607. job_obj.toolchange_xy_type = "geometry"
  1608. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  1609. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1610. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  1611. # TODO this serve for bounding box creation only; should be optimized
  1612. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  1613. # for bounding box values
  1614. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  1615. try:
  1616. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  1617. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  1618. except Exception as er:
  1619. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(er)))
  1620. job_obj.cnc_tools.update({
  1621. tooluid_key: deepcopy(dia_cnc_dict)
  1622. })
  1623. dia_cnc_dict.clear()
  1624. # Object initialization function for app.app_obj.new_object()
  1625. # RUNNING ON SEPARATE THREAD!
  1626. def job_init_multi_geometry(job_obj, app_obj):
  1627. log.debug("Creating a CNCJob out of a multi-geometry")
  1628. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1629. job_obj.options['xmin'] = xmin
  1630. job_obj.options['ymin'] = ymin
  1631. job_obj.options['xmax'] = xmax
  1632. job_obj.options['ymax'] = ymax
  1633. # count the tools
  1634. tool_cnt = 0
  1635. # dia_cnc_dict = {}
  1636. # this turn on the FlatCAMCNCJob plot for multiple tools
  1637. job_obj.multitool = True
  1638. job_obj.multigeo = True
  1639. job_obj.cnc_tools.clear()
  1640. job_obj.options['Tools_in_use'] = tools_in_use
  1641. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  1642. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  1643. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  1644. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  1645. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  1646. if not self.solid_geometry:
  1647. a = 0
  1648. for tooluid_key in self.tools:
  1649. if self.tools[tooluid_key]['solid_geometry'] is None:
  1650. a += 1
  1651. if a == len(self.tools):
  1652. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  1653. return 'fail'
  1654. for tooluid_key in list(tools_dict.keys()):
  1655. tool_cnt += 1
  1656. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  1657. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  1658. dia_cnc_dict.update({
  1659. 'tooldia': tooldia_val
  1660. })
  1661. # find the tool_dia associated with the tooluid_key
  1662. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  1663. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  1664. # for k, v in self.tools.items():
  1665. # if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  1666. # current_uid = int(k)
  1667. # break
  1668. if dia_cnc_dict['offset'] == 'in':
  1669. tool_offset = -tooldia_val / 2
  1670. elif dia_cnc_dict['offset'].lower() == 'out':
  1671. tool_offset = tooldia_val / 2
  1672. elif dia_cnc_dict['offset'].lower() == 'custom':
  1673. offset_value = float(self.ui.tool_offset_entry.get_value())
  1674. if offset_value:
  1675. tool_offset = float(offset_value)
  1676. else:
  1677. self.app.inform.emit('[WARNING] %s' %
  1678. _("Tool Offset is selected in Tool Table but "
  1679. "no value is provided.\n"
  1680. "Add a Tool Offset or change the Offset Type."))
  1681. return
  1682. else:
  1683. tool_offset = 0.0
  1684. dia_cnc_dict.update({
  1685. 'offset_value': tool_offset
  1686. })
  1687. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  1688. z_move = tools_dict[tooluid_key]['data']["travelz"]
  1689. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  1690. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  1691. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  1692. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  1693. extracut = tools_dict[tooluid_key]['data']["extracut"]
  1694. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  1695. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  1696. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  1697. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  1698. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  1699. startz = tools_dict[tooluid_key]['data']["startz"]
  1700. endz = tools_dict[tooluid_key]['data']["endz"]
  1701. endxy = self.options["endxy"]
  1702. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  1703. dwell = tools_dict[tooluid_key]['data']["dwell"]
  1704. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  1705. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  1706. spindledir = self.app.defaults['geometry_spindledir']
  1707. tool_solid_geometry = self.tools[tooluid_key]['solid_geometry']
  1708. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1709. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1710. # Propagate options
  1711. job_obj.options["tooldia"] = tooldia_val
  1712. job_obj.options['type'] = 'Geometry'
  1713. job_obj.options['tool_dia'] = tooldia_val
  1714. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1715. # to a value of 0.0005 which is 20 times less than 0.01
  1716. tol = float(self.app.defaults['global_tolerance']) / 20
  1717. res = job_obj.generate_from_multitool_geometry(
  1718. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  1719. tolerance=tol, z_cut=z_cut, z_move=z_move,
  1720. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1721. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  1722. multidepth=multidepth, depthpercut=depthpercut,
  1723. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1724. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1725. pp_geometry_name=pp_geometry_name,
  1726. tool_no=tool_cnt)
  1727. if res == 'fail':
  1728. log.debug("GeometryObject.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1729. return 'fail'
  1730. else:
  1731. dia_cnc_dict['gcode'] = res
  1732. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  1733. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1734. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  1735. # TODO this serve for bounding box creation only; should be optimized
  1736. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  1737. # for bounding box values
  1738. # geo_for_bound_values = cascaded_union([
  1739. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  1740. # ])
  1741. try:
  1742. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  1743. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  1744. except Exception as ee:
  1745. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(ee)))
  1746. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1747. # object is the source of gcode
  1748. job_obj.toolchange_xy_type = "geometry"
  1749. job_obj.cnc_tools.update({
  1750. tooluid_key: deepcopy(dia_cnc_dict)
  1751. })
  1752. dia_cnc_dict.clear()
  1753. if use_thread:
  1754. # To be run in separate thread
  1755. def job_thread(a_obj):
  1756. if self.multigeo is False:
  1757. with self.app.proc_container.new(_("Generating CNC Code")):
  1758. if a_obj.app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  1759. a_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  1760. else:
  1761. with self.app.proc_container.new(_("Generating CNC Code")):
  1762. if a_obj.app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  1763. a_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  1764. # Create a promise with the name
  1765. self.app.collection.promise(outname)
  1766. # Send to worker
  1767. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1768. else:
  1769. if self.solid_geometry:
  1770. self.app.app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  1771. else:
  1772. self.app.app_obj.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  1773. def generatecncjob(self, outname=None, dia=None, offset=None, z_cut=None, z_move=None,
  1774. feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None, dwell=None, dwelltime=None,
  1775. multidepth=None, dpp=None, toolchange=None, toolchangez=None, toolchangexy=None,
  1776. extracut=None, extracut_length=None, startz=None, endz=None, endxy=None, pp=None, segx=None, segy=None,
  1777. use_thread=True, plot=True):
  1778. """
  1779. Only used by the TCL Command Cncjob.
  1780. Creates a CNCJob out of this Geometry object. The actual
  1781. work is done by the target camlib.CNCjob
  1782. `generate_from_geometry_2()` method.
  1783. :param outname: Name of the new object
  1784. :param dia: Tool diameter
  1785. :param offset:
  1786. :param z_cut: Cut depth (negative value)
  1787. :param z_move: Height of the tool when travelling (not cutting)
  1788. :param feedrate: Feed rate while cutting on X - Y plane
  1789. :param feedrate_z: Feed rate while cutting on Z plane
  1790. :param feedrate_rapid: Feed rate while moving with rapids
  1791. :param spindlespeed: Spindle speed (RPM)
  1792. :param dwell:
  1793. :param dwelltime:
  1794. :param multidepth:
  1795. :param dpp: Depth for each pass when multidepth parameter is True
  1796. :param toolchange:
  1797. :param toolchangez:
  1798. :param toolchangexy: A sequence ox X,Y coordinates: a 2-length tuple or a string.
  1799. Coordinates in X,Y plane for the Toolchange event
  1800. :param extracut:
  1801. :param extracut_length:
  1802. :param startz:
  1803. :param endz:
  1804. :param endxy: A sequence ox X,Y coordinates: a 2-length tuple or a string.
  1805. Coordinates in X, Y plane for the last move after ending the job.
  1806. :param pp: Name of the preprocessor
  1807. :param segx:
  1808. :param segy:
  1809. :param use_thread:
  1810. :param plot:
  1811. :return: None
  1812. """
  1813. tooldia = dia if dia else float(self.options["cnctooldia"])
  1814. outname = outname if outname is not None else self.options["name"]
  1815. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  1816. z_move = z_move if z_move is not None else float(self.options["travelz"])
  1817. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  1818. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  1819. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  1820. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  1821. depthperpass = dpp if dpp is not None else float(self.options["depthperpass"])
  1822. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  1823. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  1824. extracut = extracut if extracut is not None else float(self.options["extracut"])
  1825. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  1826. startz = startz if startz is not None else self.options["startz"]
  1827. endz = endz if endz is not None else float(self.options["endz"])
  1828. endxy = endxy if endxy else self.options["endxy"]
  1829. if isinstance(endxy, str):
  1830. endxy = re.sub('[()\[\]]', '', endxy)
  1831. if endxy and endxy != '':
  1832. endxy = [float(eval(a)) for a in endxy.split(",")]
  1833. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  1834. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  1835. if isinstance(toolchangexy, str):
  1836. toolchangexy = re.sub('[()\[\]]', '', toolchangexy)
  1837. if toolchangexy and toolchangexy != '':
  1838. toolchangexy = [float(eval(a)) for a in toolchangexy.split(",")]
  1839. toolchange = toolchange if toolchange else self.options["toolchange"]
  1840. offset = offset if offset else 0.0
  1841. # int or None.
  1842. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  1843. dwell = dwell if dwell else self.options["dwell"]
  1844. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  1845. ppname_g = pp if pp else self.options["ppname_g"]
  1846. # Object initialization function for app.app_obj.new_object()
  1847. # RUNNING ON SEPARATE THREAD!
  1848. def job_init(job_obj, app_obj):
  1849. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1850. # Propagate options
  1851. job_obj.options["tooldia"] = tooldia
  1852. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1853. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1854. job_obj.options['type'] = 'Geometry'
  1855. job_obj.options['tool_dia'] = tooldia
  1856. job_obj.segx = segx
  1857. job_obj.segy = segy
  1858. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1859. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1860. job_obj.options['xmin'] = self.options['xmin']
  1861. job_obj.options['ymin'] = self.options['ymin']
  1862. job_obj.options['xmax'] = self.options['xmax']
  1863. job_obj.options['ymax'] = self.options['ymax']
  1864. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1865. # to a value of 0.0005 which is 20 times less than 0.01
  1866. tol = float(self.app.defaults['global_tolerance']) / 20
  1867. job_obj.generate_from_geometry_2(
  1868. self, tooldia=tooldia, offset=offset, tolerance=tol,
  1869. z_cut=z_cut, z_move=z_move,
  1870. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1871. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  1872. multidepth=multidepth, depthpercut=depthperpass,
  1873. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1874. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1875. pp_geometry_name=ppname_g
  1876. )
  1877. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  1878. # source of gcode
  1879. job_obj.toolchange_xy_type = "geometry"
  1880. job_obj.gcode_parse()
  1881. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  1882. if use_thread:
  1883. # To be run in separate thread
  1884. def job_thread(app_obj):
  1885. with self.app.proc_container.new(_("Generating CNC Code")):
  1886. app_obj.app_obj.new_object("cncjob", outname, job_init, plot=plot)
  1887. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created")), outname)
  1888. # Create a promise with the name
  1889. self.app.collection.promise(outname)
  1890. # Send to worker
  1891. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1892. else:
  1893. self.app.app_obj.new_object("cncjob", outname, job_init, plot=plot)
  1894. # def on_plot_cb_click(self, *args):
  1895. # if self.muted_ui:
  1896. # return
  1897. # self.read_form_item('plot')
  1898. def scale(self, xfactor, yfactor=None, point=None):
  1899. """
  1900. Scales all geometry by a given factor.
  1901. :param xfactor: Factor by which to scale the object's geometry/
  1902. :type xfactor: float
  1903. :param yfactor: Factor by which to scale the object's geometry/
  1904. :type yfactor: float
  1905. :param point: Point around which to scale
  1906. :return: None
  1907. :rtype: None
  1908. """
  1909. log.debug("FlatCAMObj.GeometryObject.scale()")
  1910. try:
  1911. xfactor = float(xfactor)
  1912. except Exception:
  1913. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  1914. return
  1915. if yfactor is None:
  1916. yfactor = xfactor
  1917. else:
  1918. try:
  1919. yfactor = float(yfactor)
  1920. except Exception:
  1921. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  1922. return
  1923. if xfactor == 1 and yfactor == 1:
  1924. return
  1925. if point is None:
  1926. px = 0
  1927. py = 0
  1928. else:
  1929. px, py = point
  1930. self.geo_len = 0
  1931. self.old_disp_number = 0
  1932. self.el_count = 0
  1933. def scale_recursion(geom):
  1934. if type(geom) is list:
  1935. geoms = []
  1936. for local_geom in geom:
  1937. geoms.append(scale_recursion(local_geom))
  1938. return geoms
  1939. else:
  1940. try:
  1941. self.el_count += 1
  1942. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1943. if self.old_disp_number < disp_number <= 100:
  1944. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1945. self.old_disp_number = disp_number
  1946. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1947. except AttributeError:
  1948. return geom
  1949. if self.multigeo is True:
  1950. for tool in self.tools:
  1951. # variables to display the percentage of work done
  1952. self.geo_len = 0
  1953. try:
  1954. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1955. except TypeError:
  1956. self.geo_len = 1
  1957. self.old_disp_number = 0
  1958. self.el_count = 0
  1959. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  1960. try:
  1961. # variables to display the percentage of work done
  1962. self.geo_len = 0
  1963. try:
  1964. self.geo_len = len(self.solid_geometry)
  1965. except TypeError:
  1966. self.geo_len = 1
  1967. self.old_disp_number = 0
  1968. self.el_count = 0
  1969. self.solid_geometry = scale_recursion(self.solid_geometry)
  1970. except AttributeError:
  1971. self.solid_geometry = []
  1972. return
  1973. self.app.proc_container.new_text = ''
  1974. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  1975. def offset(self, vect):
  1976. """
  1977. Offsets all geometry by a given vector/
  1978. :param vect: (x, y) vector by which to offset the object's geometry.
  1979. :type vect: tuple
  1980. :return: None
  1981. :rtype: None
  1982. """
  1983. log.debug("FlatCAMObj.GeometryObject.offset()")
  1984. try:
  1985. dx, dy = vect
  1986. except TypeError:
  1987. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1988. _("An (x,y) pair of values are needed. "
  1989. "Probable you entered only one value in the Offset field.")
  1990. )
  1991. return
  1992. if dx == 0 and dy == 0:
  1993. return
  1994. self.geo_len = 0
  1995. self.old_disp_number = 0
  1996. self.el_count = 0
  1997. def translate_recursion(geom):
  1998. if type(geom) is list:
  1999. geoms = []
  2000. for local_geom in geom:
  2001. geoms.append(translate_recursion(local_geom))
  2002. return geoms
  2003. else:
  2004. try:
  2005. self.el_count += 1
  2006. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  2007. if self.old_disp_number < disp_number <= 100:
  2008. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2009. self.old_disp_number = disp_number
  2010. return affinity.translate(geom, xoff=dx, yoff=dy)
  2011. except AttributeError:
  2012. return geom
  2013. if self.multigeo is True:
  2014. for tool in self.tools:
  2015. # variables to display the percentage of work done
  2016. self.geo_len = 0
  2017. try:
  2018. self.geo_len = len(self.tools[tool]['solid_geometry'])
  2019. except TypeError:
  2020. self.geo_len = 1
  2021. self.old_disp_number = 0
  2022. self.el_count = 0
  2023. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  2024. # variables to display the percentage of work done
  2025. self.geo_len = 0
  2026. try:
  2027. self.geo_len = len(self.solid_geometry)
  2028. except TypeError:
  2029. self.geo_len = 1
  2030. self.old_disp_number = 0
  2031. self.el_count = 0
  2032. self.solid_geometry = translate_recursion(self.solid_geometry)
  2033. self.app.proc_container.new_text = ''
  2034. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  2035. def convert_units(self, units):
  2036. log.debug("FlatCAMObj.GeometryObject.convert_units()")
  2037. self.ui_disconnect()
  2038. factor = Geometry.convert_units(self, units)
  2039. self.options['cutz'] = float(self.options['cutz']) * factor
  2040. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  2041. self.options['travelz'] = float(self.options['travelz']) * factor
  2042. self.options['feedrate'] = float(self.options['feedrate']) * factor
  2043. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  2044. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  2045. self.options['endz'] = float(self.options['endz']) * factor
  2046. # self.options['cnctooldia'] *= factor
  2047. # self.options['painttooldia'] *= factor
  2048. # self.options['paintmargin'] *= factor
  2049. # self.options['paintoverlap'] *= factor
  2050. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  2051. if self.app.defaults["geometry_toolchangexy"] == '':
  2052. self.options['toolchangexy'] = "0.0, 0.0"
  2053. else:
  2054. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  2055. if len(coords_xy) < 2:
  2056. self.app.inform.emit('[ERROR] %s' %
  2057. _("The Toolchange X,Y field in Edit -> Preferences "
  2058. "has to be in the format (x, y)\n"
  2059. "but now there is only one value, not two.")
  2060. )
  2061. return 'fail'
  2062. coords_xy[0] *= factor
  2063. coords_xy[1] *= factor
  2064. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2065. if self.options['startz'] is not None:
  2066. self.options['startz'] = float(self.options['startz']) * factor
  2067. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2068. 'endz', 'toolchangez']
  2069. if isinstance(self, GeometryObject):
  2070. temp_tools_dict = {}
  2071. tool_dia_copy = {}
  2072. data_copy = {}
  2073. for tooluid_key, tooluid_value in self.tools.items():
  2074. for dia_key, dia_value in tooluid_value.items():
  2075. if dia_key == 'tooldia':
  2076. dia_value *= factor
  2077. dia_value = float('%.*f' % (self.decimals, dia_value))
  2078. tool_dia_copy[dia_key] = dia_value
  2079. if dia_key == 'offset':
  2080. tool_dia_copy[dia_key] = dia_value
  2081. if dia_key == 'offset_value':
  2082. dia_value *= factor
  2083. tool_dia_copy[dia_key] = dia_value
  2084. # convert the value in the Custom Tool Offset entry in UI
  2085. custom_offset = None
  2086. try:
  2087. custom_offset = float(self.ui.tool_offset_entry.get_value())
  2088. except ValueError:
  2089. # try to convert comma to decimal point. if it's still not working error message and return
  2090. try:
  2091. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  2092. except ValueError:
  2093. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2094. _("Wrong value format entered, use a number."))
  2095. return
  2096. except TypeError:
  2097. pass
  2098. if custom_offset:
  2099. custom_offset *= factor
  2100. self.ui.tool_offset_entry.set_value(custom_offset)
  2101. if dia_key == 'type':
  2102. tool_dia_copy[dia_key] = dia_value
  2103. if dia_key == 'tool_type':
  2104. tool_dia_copy[dia_key] = dia_value
  2105. if dia_key == 'data':
  2106. for data_key, data_value in dia_value.items():
  2107. # convert the form fields that are convertible
  2108. for param in param_list:
  2109. if data_key == param and data_value is not None:
  2110. data_copy[data_key] = data_value * factor
  2111. # copy the other dict entries that are not convertible
  2112. if data_key not in param_list:
  2113. data_copy[data_key] = data_value
  2114. tool_dia_copy[dia_key] = deepcopy(data_copy)
  2115. data_copy.clear()
  2116. temp_tools_dict.update({
  2117. tooluid_key: deepcopy(tool_dia_copy)
  2118. })
  2119. tool_dia_copy.clear()
  2120. self.tools.clear()
  2121. self.tools = deepcopy(temp_tools_dict)
  2122. # if there is a value in the new tool field then convert that one too
  2123. try:
  2124. self.ui.addtool_entry.returnPressed.disconnect()
  2125. except TypeError:
  2126. pass
  2127. tooldia = self.ui.addtool_entry.get_value()
  2128. if tooldia:
  2129. tooldia *= factor
  2130. tooldia = float('%.*f' % (self.decimals, tooldia))
  2131. self.ui.addtool_entry.set_value(tooldia)
  2132. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  2133. return factor
  2134. def on_add_area_click(self):
  2135. shape_button = self.ui.area_shape_radio
  2136. overz_button = self.ui.over_z_entry
  2137. strategy_radio = self.ui.strategy_radio
  2138. cnc_button = self.ui.generate_cnc_button
  2139. solid_geo = self.solid_geometry
  2140. obj_type = self.kind
  2141. self.app.exc_areas.on_add_area_click(
  2142. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  2143. solid_geo=solid_geo, obj_type=obj_type)
  2144. def on_clear_area_click(self):
  2145. if not self.app.exc_areas.exclusion_areas_storage:
  2146. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  2147. return
  2148. self.app.exc_areas.on_clear_area_click()
  2149. self.app.exc_areas.e_shape_modified.emit()
  2150. def on_delete_sel_areas(self):
  2151. sel_model = self.ui.exclusion_table.selectionModel()
  2152. sel_indexes = sel_model.selectedIndexes()
  2153. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  2154. # so the duplicate rows will not be added
  2155. sel_rows = set()
  2156. for idx in sel_indexes:
  2157. sel_rows.add(idx.row())
  2158. if not sel_rows:
  2159. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  2160. return
  2161. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  2162. self.app.exc_areas.e_shape_modified.emit()
  2163. def draw_sel_shape(self):
  2164. sel_model = self.ui.exclusion_table.selectionModel()
  2165. sel_indexes = sel_model.selectedIndexes()
  2166. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  2167. sel_rows = set()
  2168. for idx in sel_indexes:
  2169. sel_rows.add(idx.row())
  2170. self.delete_sel_shape()
  2171. if self.app.is_legacy is False:
  2172. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  2173. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  2174. else:
  2175. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  2176. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  2177. for row in sel_rows:
  2178. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  2179. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  2180. tolerance=None)
  2181. if self.app.is_legacy is True:
  2182. self.app.move_tool.sel_shapes.redraw()
  2183. def clear_selection(self):
  2184. self.app.delete_selection_shape()
  2185. # self.ui.exclusion_table.clearSelection()
  2186. def delete_sel_shape(self):
  2187. self.app.delete_selection_shape()
  2188. def update_exclusion_table(self):
  2189. self.exclusion_area_cb_is_checked = True if self.ui.exclusion_cb.isChecked() else False
  2190. self.build_ui()
  2191. self.ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  2192. def on_strategy(self, val):
  2193. if val == 'around':
  2194. self.ui.over_z_label.setDisabled(True)
  2195. self.ui.over_z_entry.setDisabled(True)
  2196. else:
  2197. self.ui.over_z_label.setDisabled(False)
  2198. self.ui.over_z_entry.setDisabled(False)
  2199. def exclusion_table_toggle_all(self):
  2200. """
  2201. will toggle the selection of all rows in Exclusion Areas table
  2202. :return:
  2203. """
  2204. sel_model = self.ui.exclusion_table.selectionModel()
  2205. sel_indexes = sel_model.selectedIndexes()
  2206. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  2207. sel_rows = set()
  2208. for idx in sel_indexes:
  2209. sel_rows.add(idx.row())
  2210. if sel_rows:
  2211. self.ui.exclusion_table.clearSelection()
  2212. self.delete_sel_shape()
  2213. else:
  2214. self.ui.exclusion_table.selectAll()
  2215. self.draw_sel_shape()
  2216. def plot_element(self, element, color=None, visible=None):
  2217. if color is None:
  2218. color = '#FF0000FF'
  2219. visible = visible if visible else self.options['plot']
  2220. try:
  2221. for sub_el in element:
  2222. self.plot_element(sub_el, color=color)
  2223. except TypeError: # Element is not iterable...
  2224. # if self.app.is_legacy is False:
  2225. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2226. def plot(self, visible=None, kind=None):
  2227. """
  2228. Plot the object.
  2229. :param visible: Controls if the added shape is visible of not
  2230. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  2231. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  2232. :return:
  2233. """
  2234. # Does all the required setup and returns False
  2235. # if the 'ptint' option is set to False.
  2236. if not FlatCAMObj.plot(self):
  2237. return
  2238. if self.app.is_legacy is False:
  2239. def random_color():
  2240. r_color = np.random.rand(4)
  2241. r_color[3] = 1
  2242. return r_color
  2243. else:
  2244. def random_color():
  2245. while True:
  2246. r_color = np.random.rand(4)
  2247. r_color[3] = 1
  2248. new_color = '#'
  2249. for idx in range(len(r_color)):
  2250. new_color += '%x' % int(r_color[idx] * 255)
  2251. # do it until a valid color is generated
  2252. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  2253. # for a total of 9 chars
  2254. if len(new_color) == 9:
  2255. break
  2256. return new_color
  2257. try:
  2258. # plot solid geometries found as members of self.tools attribute dict
  2259. # for MultiGeo
  2260. if self.multigeo is True: # geo multi tool usage
  2261. for tooluid_key in self.tools:
  2262. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2263. self.plot_element(solid_geometry, visible=visible,
  2264. color=random_color() if self.options['multicolored']
  2265. else self.app.defaults["geometry_plot_line"])
  2266. else:
  2267. # plot solid geometry that may be an direct attribute of the geometry object
  2268. # for SingleGeo
  2269. if self.solid_geometry:
  2270. self.plot_element(self.solid_geometry, visible=visible,
  2271. color=self.app.defaults["geometry_plot_line"])
  2272. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  2273. self.shapes.redraw()
  2274. except (ObjectDeleted, AttributeError):
  2275. self.shapes.clear(update=True)
  2276. def on_plot_cb_click(self, *args):
  2277. if self.muted_ui:
  2278. return
  2279. self.read_form_item('plot')
  2280. self.plot()
  2281. self.ui_disconnect()
  2282. cb_flag = self.ui.plot_cb.isChecked()
  2283. for row in range(self.ui.geo_tools_table.rowCount()):
  2284. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  2285. if cb_flag:
  2286. table_cb.setChecked(True)
  2287. else:
  2288. table_cb.setChecked(False)
  2289. self.ui_connect()
  2290. def on_plot_cb_click_table(self):
  2291. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2292. self.ui_disconnect()
  2293. # cw = self.sender()
  2294. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2295. # cw_row = cw_index.row()
  2296. check_row = 0
  2297. self.shapes.clear(update=True)
  2298. for tooluid_key in self.tools:
  2299. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2300. # find the geo_tool_table row associated with the tooluid_key
  2301. for row in range(self.ui.geo_tools_table.rowCount()):
  2302. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2303. if tooluid_item == int(tooluid_key):
  2304. check_row = row
  2305. break
  2306. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  2307. self.plot_element(element=solid_geometry, visible=True)
  2308. self.shapes.redraw()
  2309. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2310. # if all the row plot's are enabled also enable the general plot checkbox
  2311. cb_cnt = 0
  2312. total_row = self.ui.geo_tools_table.rowCount()
  2313. for row in range(total_row):
  2314. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  2315. cb_cnt += 1
  2316. else:
  2317. cb_cnt -= 1
  2318. if cb_cnt < total_row:
  2319. self.ui.plot_cb.setChecked(False)
  2320. else:
  2321. self.ui.plot_cb.setChecked(True)
  2322. self.ui_connect()
  2323. def on_multicolored_cb_click(self, *args):
  2324. if self.muted_ui:
  2325. return
  2326. self.read_form_item('multicolored')
  2327. self.plot()
  2328. @staticmethod
  2329. def merge(geo_list, geo_final, multigeo=None):
  2330. """
  2331. Merges the geometry of objects in grb_list into the geometry of geo_final.
  2332. :param geo_list: List of GerberObject Objects to join.
  2333. :param geo_final: Destination GerberObject object.
  2334. :param multigeo: if the merged geometry objects are of type MultiGeo
  2335. :return: None
  2336. """
  2337. if geo_final.solid_geometry is None:
  2338. geo_final.solid_geometry = []
  2339. try:
  2340. __ = iter(geo_final.solid_geometry)
  2341. except TypeError:
  2342. geo_final.solid_geometry = [geo_final.solid_geometry]
  2343. new_solid_geometry = []
  2344. new_options = {}
  2345. new_tools = {}
  2346. for geo_obj in geo_list:
  2347. for option in geo_obj.options:
  2348. if option != 'name':
  2349. try:
  2350. new_options[option] = deepcopy(geo_obj.options[option])
  2351. except Exception as e:
  2352. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  2353. # Expand lists
  2354. if type(geo_obj) is list:
  2355. GeometryObject.merge(geo_list=geo_obj, geo_final=geo_final)
  2356. # If not list, just append
  2357. else:
  2358. if multigeo is None or multigeo is False:
  2359. geo_final.multigeo = False
  2360. else:
  2361. geo_final.multigeo = True
  2362. try:
  2363. new_solid_geometry += deepcopy(geo_obj.solid_geometry)
  2364. except Exception as e:
  2365. log.debug("GeometryObject.merge() --> %s" % str(e))
  2366. # find the tool_uid maximum value in the geo_final
  2367. try:
  2368. max_uid = max([int(i) for i in new_tools.keys()])
  2369. except ValueError:
  2370. max_uid = 0
  2371. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2372. # to merge the obj.tools as it is likely there is none to merge.
  2373. if geo_obj.kind != 'gerber' and geo_obj.kind != 'excellon':
  2374. for tool_uid in geo_obj.tools:
  2375. max_uid += 1
  2376. new_tools[max_uid] = deepcopy(geo_obj.tools[tool_uid])
  2377. geo_final.options.update(new_options)
  2378. geo_final.solid_geometry = new_solid_geometry
  2379. geo_final.tools = new_tools
  2380. @staticmethod
  2381. def get_pts(o):
  2382. """
  2383. Returns a list of all points in the object, where
  2384. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2385. of such. Search is done recursively.
  2386. :param: geometric object
  2387. :return: List of points
  2388. :rtype: list
  2389. """
  2390. pts = []
  2391. # Iterable: descend into each item.
  2392. try:
  2393. for subo in o:
  2394. pts += GeometryObject.get_pts(subo)
  2395. # Non-iterable
  2396. except TypeError:
  2397. if o is not None:
  2398. if type(o) == MultiPolygon:
  2399. for poly in o:
  2400. pts += GeometryObject.get_pts(poly)
  2401. # ## Descend into .exerior and .interiors
  2402. elif type(o) == Polygon:
  2403. pts += GeometryObject.get_pts(o.exterior)
  2404. for i in o.interiors:
  2405. pts += GeometryObject.get_pts(i)
  2406. elif type(o) == MultiLineString:
  2407. for line in o:
  2408. pts += GeometryObject.get_pts(line)
  2409. # ## Has .coords: list them.
  2410. else:
  2411. pts += list(o.coords)
  2412. else:
  2413. return
  2414. return pts