FlatCAMGeometry.py 125 KB

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