FlatCAMGeometry.py 128 KB

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