FlatCAMGeometry.py 138 KB

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