FlatCAMGeometry.py 126 KB

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