FlatCAMGeometry.py 133 KB

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