FlatCAMGeometry.py 124 KB

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