FlatCAMGeometry.py 129 KB

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