FlatCAMGeometry.py 137 KB

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