FlatCAMGeometry.py 128 KB

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