FlatCAMGeometry.py 129 KB

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