FlatCAMGeometry.py 121 KB

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