FlatCAMGeometry.py 138 KB

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