FlatCAMGeometry.py 126 KB

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