FlatCAMGeometry.py 127 KB

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