FlatCAMGeometry.py 133 KB

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