appDatabase.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from appGUI.GUIElements import FCTable, FCEntry, FCButton, FCDoubleSpinner, FCComboBox, FCCheckBox, FCSpinner, \
  3. FCTree, RadioSet, FCFileSaveDialog
  4. from camlib import to_dict
  5. import sys
  6. import json
  7. from copy import deepcopy
  8. from datetime import datetime
  9. import math
  10. import gettext
  11. import appTranslation as fcTranslate
  12. import builtins
  13. fcTranslate.apply_language('strings')
  14. if '_' not in builtins.__dict__:
  15. _ = gettext.gettext
  16. class ToolsDB(QtWidgets.QWidget):
  17. mark_tools_rows = QtCore.pyqtSignal()
  18. def __init__(self, app, callback_on_edited, callback_on_tool_request, parent=None):
  19. super(ToolsDB, self).__init__(parent)
  20. self.app = app
  21. self.decimals = 4
  22. self.callback_app = callback_on_edited
  23. self.on_tool_request = callback_on_tool_request
  24. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  25. self.type_item_options = ["Iso", "Rough", "Finish"]
  26. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  27. '''
  28. dict to hold all the tools in the Tools DB
  29. format:
  30. {
  31. tool_id: {
  32. 'name': 'new_tool'
  33. 'tooldia': self.app.defaults["geometry_cnctooldia"]
  34. 'offset': 'Path'
  35. 'offset_value': 0.0
  36. 'type': _('Rough'),
  37. 'tool_type': 'C1'
  38. 'data': dict()
  39. }
  40. }
  41. '''
  42. self.db_tool_dict = {}
  43. # layouts
  44. layout = QtWidgets.QVBoxLayout()
  45. self.setLayout(layout)
  46. table_hlay = QtWidgets.QHBoxLayout()
  47. layout.addLayout(table_hlay)
  48. self.table_widget = FCTable(drag_drop=True)
  49. self.table_widget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  50. table_hlay.addWidget(self.table_widget)
  51. # set the number of columns and the headers tool tips
  52. self.configure_table()
  53. # pal = QtGui.QPalette()
  54. # pal.setColor(QtGui.QPalette.Background, Qt.white)
  55. # New Bookmark
  56. new_vlay = QtWidgets.QVBoxLayout()
  57. layout.addLayout(new_vlay)
  58. # new_tool_lbl = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  59. # new_vlay.addWidget(new_tool_lbl, alignment=QtCore.Qt.AlignBottom)
  60. self.buttons_frame = QtWidgets.QFrame()
  61. self.buttons_frame.setContentsMargins(0, 0, 0, 0)
  62. layout.addWidget(self.buttons_frame)
  63. self.buttons_box = QtWidgets.QHBoxLayout()
  64. self.buttons_box.setContentsMargins(0, 0, 0, 0)
  65. self.buttons_frame.setLayout(self.buttons_box)
  66. self.buttons_frame.show()
  67. add_entry_btn = FCButton(_("Add Geometry Tool in DB"))
  68. add_entry_btn.setToolTip(
  69. _("Add a new tool in the Tools Database.\n"
  70. "It will be used in the Geometry UI.\n"
  71. "You can edit it after it is added.")
  72. )
  73. self.buttons_box.addWidget(add_entry_btn)
  74. # add_fct_entry_btn = FCButton(_("Add Paint/NCC Tool in DB"))
  75. # add_fct_entry_btn.setToolTip(
  76. # _("Add a new tool in the Tools Database.\n"
  77. # "It will be used in the Paint/NCC Tools UI.\n"
  78. # "You can edit it after it is added.")
  79. # )
  80. # self.buttons_box.addWidget(add_fct_entry_btn)
  81. remove_entry_btn = FCButton(_("Delete Tool from DB"))
  82. remove_entry_btn.setToolTip(
  83. _("Remove a selection of tools in the Tools Database.")
  84. )
  85. self.buttons_box.addWidget(remove_entry_btn)
  86. export_db_btn = FCButton(_("Export DB"))
  87. export_db_btn.setToolTip(
  88. _("Save the Tools Database to a custom text file.")
  89. )
  90. self.buttons_box.addWidget(export_db_btn)
  91. import_db_btn = FCButton(_("Import DB"))
  92. import_db_btn.setToolTip(
  93. _("Load the Tools Database information's from a custom text file.")
  94. )
  95. self.buttons_box.addWidget(import_db_btn)
  96. self.add_tool_from_db = FCButton(_("Transfer the Tool"))
  97. self.add_tool_from_db.setToolTip(
  98. _("Add a new tool in the Tools Table of the\n"
  99. "active Geometry object after selecting a tool\n"
  100. "in the Tools Database.")
  101. )
  102. self.add_tool_from_db.hide()
  103. self.cancel_tool_from_db = FCButton(_("Cancel"))
  104. self.cancel_tool_from_db.hide()
  105. hlay = QtWidgets.QHBoxLayout()
  106. layout.addLayout(hlay)
  107. hlay.addWidget(self.add_tool_from_db)
  108. hlay.addWidget(self.cancel_tool_from_db)
  109. hlay.addStretch()
  110. # ##############################################################################
  111. # ######################## SIGNALS #############################################
  112. # ##############################################################################
  113. add_entry_btn.clicked.connect(self.on_tool_add)
  114. remove_entry_btn.clicked.connect(self.on_tool_delete)
  115. export_db_btn.clicked.connect(self.on_export_tools_db_file)
  116. import_db_btn.clicked.connect(self.on_import_tools_db_file)
  117. # closebtn.clicked.connect(self.accept)
  118. self.add_tool_from_db.clicked.connect(self.on_tool_requested_from_app)
  119. self.cancel_tool_from_db.clicked.connect(self.on_cancel_tool)
  120. self.setup_db_ui()
  121. def configure_table(self):
  122. self.table_widget.setColumnCount(27)
  123. # self.table_widget.setColumnWidth(0, 20)
  124. self.table_widget.setHorizontalHeaderLabels(
  125. [
  126. '#',
  127. _("Tool Name"),
  128. _("Tool Dia"),
  129. _("Tool Offset"),
  130. _("Custom Offset"),
  131. _("Tool Type"),
  132. _("Tool Shape"),
  133. _("Cut Z"),
  134. _("MultiDepth"),
  135. _("DPP"),
  136. _("V-Dia"),
  137. _("V-Angle"),
  138. _("Travel Z"),
  139. _("FR"),
  140. _("FR Z"),
  141. _("FR Rapids"),
  142. _("Spindle Speed"),
  143. _("Dwell"),
  144. _("Dwelltime"),
  145. _("Preprocessor"),
  146. _("ExtraCut"),
  147. _("E-Cut Length"),
  148. _("Toolchange"),
  149. _("Toolchange XY"),
  150. _("Toolchange Z"),
  151. _("Start Z"),
  152. _("End Z"),
  153. ]
  154. )
  155. self.table_widget.horizontalHeaderItem(0).setToolTip(
  156. _("Tool Index."))
  157. self.table_widget.horizontalHeaderItem(1).setToolTip(
  158. _("Tool name.\n"
  159. "This is not used in the app, it's function\n"
  160. "is to serve as a note for the user."))
  161. self.table_widget.horizontalHeaderItem(2).setToolTip(
  162. _("Tool Diameter."))
  163. self.table_widget.horizontalHeaderItem(3).setToolTip(
  164. _("Tool Offset.\n"
  165. "Can be of a few types:\n"
  166. "Path = zero offset\n"
  167. "In = offset inside by half of tool diameter\n"
  168. "Out = offset outside by half of tool diameter\n"
  169. "Custom = custom offset using the Custom Offset value"))
  170. self.table_widget.horizontalHeaderItem(4).setToolTip(
  171. _("Custom Offset.\n"
  172. "A value to be used as offset from the current path."))
  173. self.table_widget.horizontalHeaderItem(5).setToolTip(
  174. _("Tool Type.\n"
  175. "Can be:\n"
  176. "Iso = isolation cut\n"
  177. "Rough = rough cut, low feedrate, multiple passes\n"
  178. "Finish = finishing cut, high feedrate"))
  179. self.table_widget.horizontalHeaderItem(6).setToolTip(
  180. _("Tool Shape. \n"
  181. "Can be:\n"
  182. "C1 ... C4 = circular tool with x flutes\n"
  183. "B = ball tip milling tool\n"
  184. "V = v-shape milling tool"))
  185. self.table_widget.horizontalHeaderItem(7).setToolTip(
  186. _("Cutting Depth.\n"
  187. "The depth at which to cut into material."))
  188. self.table_widget.horizontalHeaderItem(8).setToolTip(
  189. _("Multi Depth.\n"
  190. "Selecting this will allow cutting in multiple passes,\n"
  191. "each pass adding a DPP parameter depth."))
  192. self.table_widget.horizontalHeaderItem(9).setToolTip(
  193. _("DPP. Depth per Pass.\n"
  194. "The value used to cut into material on each pass."))
  195. self.table_widget.horizontalHeaderItem(10).setToolTip(
  196. _("V-Dia.\n"
  197. "Diameter of the tip for V-Shape Tools."))
  198. self.table_widget.horizontalHeaderItem(11).setToolTip(
  199. _("V-Agle.\n"
  200. "Angle at the tip for the V-Shape Tools."))
  201. self.table_widget.horizontalHeaderItem(12).setToolTip(
  202. _("Clearance Height.\n"
  203. "Height at which the milling bit will travel between cuts,\n"
  204. "above the surface of the material, avoiding all fixtures."))
  205. self.table_widget.horizontalHeaderItem(13).setToolTip(
  206. _("FR. Feedrate\n"
  207. "The speed on XY plane used while cutting into material."))
  208. self.table_widget.horizontalHeaderItem(14).setToolTip(
  209. _("FR Z. Feedrate Z\n"
  210. "The speed on Z plane."))
  211. self.table_widget.horizontalHeaderItem(15).setToolTip(
  212. _("FR Rapids. Feedrate Rapids\n"
  213. "Speed used while moving as fast as possible.\n"
  214. "This is used only by some devices that can't use\n"
  215. "the G0 g-code command. Mostly 3D printers."))
  216. self.table_widget.horizontalHeaderItem(16).setToolTip(
  217. _("Spindle Speed.\n"
  218. "If it's left empty it will not be used.\n"
  219. "The speed of the spindle in RPM."))
  220. self.table_widget.horizontalHeaderItem(17).setToolTip(
  221. _("Dwell.\n"
  222. "Check this if a delay is needed to allow\n"
  223. "the spindle motor to reach its set speed."))
  224. self.table_widget.horizontalHeaderItem(18).setToolTip(
  225. _("Dwell Time.\n"
  226. "A delay used to allow the motor spindle reach its set speed."))
  227. self.table_widget.horizontalHeaderItem(19).setToolTip(
  228. _("Preprocessor.\n"
  229. "A selection of files that will alter the generated G-code\n"
  230. "to fit for a number of use cases."))
  231. self.table_widget.horizontalHeaderItem(20).setToolTip(
  232. _("Extra Cut.\n"
  233. "If checked, after a isolation is finished an extra cut\n"
  234. "will be added where the start and end of isolation meet\n"
  235. "such as that this point is covered by this extra cut to\n"
  236. "ensure a complete isolation."))
  237. self.table_widget.horizontalHeaderItem(21).setToolTip(
  238. _("Extra Cut length.\n"
  239. "If checked, after a isolation is finished an extra cut\n"
  240. "will be added where the start and end of isolation meet\n"
  241. "such as that this point is covered by this extra cut to\n"
  242. "ensure a complete isolation. This is the length of\n"
  243. "the extra cut."))
  244. self.table_widget.horizontalHeaderItem(22).setToolTip(
  245. _("Toolchange.\n"
  246. "It will create a toolchange event.\n"
  247. "The kind of toolchange is determined by\n"
  248. "the preprocessor file."))
  249. self.table_widget.horizontalHeaderItem(23).setToolTip(
  250. _("Toolchange XY.\n"
  251. "A set of coordinates in the format (x, y).\n"
  252. "Will determine the cartesian position of the point\n"
  253. "where the tool change event take place."))
  254. self.table_widget.horizontalHeaderItem(24).setToolTip(
  255. _("Toolchange Z.\n"
  256. "The position on Z plane where the tool change event take place."))
  257. self.table_widget.horizontalHeaderItem(25).setToolTip(
  258. _("Start Z.\n"
  259. "If it's left empty it will not be used.\n"
  260. "A position on Z plane to move immediately after job start."))
  261. self.table_widget.horizontalHeaderItem(26).setToolTip(
  262. _("End Z.\n"
  263. "A position on Z plane to move immediately after job stop."))
  264. def setup_db_ui(self):
  265. filename = self.app.data_path + '/geo_tools_db.FlatDB'
  266. # load the database tools from the file
  267. try:
  268. with open(filename) as f:
  269. tools = f.read()
  270. except IOError:
  271. self.app.log.error("Could not load tools DB file.")
  272. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  273. return
  274. try:
  275. self.db_tool_dict = json.loads(tools)
  276. except Exception:
  277. e = sys.exc_info()[0]
  278. self.app.log.error(str(e))
  279. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  280. return
  281. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  282. self.build_db_ui()
  283. self.table_widget.setupContextMenu()
  284. self.table_widget.addContextMenu(
  285. _("Add to DB"), self.on_tool_add, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  286. self.table_widget.addContextMenu(
  287. _("Copy from DB"), self.on_tool_copy, icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  288. self.table_widget.addContextMenu(
  289. _("Delete from DB"), self.on_tool_delete, icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  290. def build_db_ui(self):
  291. self.ui_disconnect()
  292. self.table_widget.setRowCount(len(self.db_tool_dict))
  293. nr_crt = 0
  294. for toolid, dict_val in self.db_tool_dict.items():
  295. row = nr_crt
  296. nr_crt += 1
  297. t_name = dict_val['name']
  298. try:
  299. self.add_tool_table_line(row, name=t_name, widget=self.table_widget, tooldict=dict_val)
  300. except Exception as e:
  301. self.app.log.debug("ToolDB.build_db_ui.add_tool_table_line() --> %s" % str(e))
  302. vertical_header = self.table_widget.verticalHeader()
  303. vertical_header.hide()
  304. horizontal_header = self.table_widget.horizontalHeader()
  305. horizontal_header.setMinimumSectionSize(10)
  306. horizontal_header.setDefaultSectionSize(70)
  307. self.table_widget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  308. for x in range(27):
  309. self.table_widget.resizeColumnToContents(x)
  310. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  311. # horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  312. # horizontal_header.setSectionResizeMode(13, QtWidgets.QHeaderView.Fixed)
  313. horizontal_header.resizeSection(0, 20)
  314. # horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  315. # horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  316. self.ui_connect()
  317. def add_tool_table_line(self, row, name, widget, tooldict):
  318. data = tooldict['data']
  319. nr_crt = row + 1
  320. id_item = QtWidgets.QTableWidgetItem('%d' % int(nr_crt))
  321. # id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  322. flags = id_item.flags() & ~QtCore.Qt.ItemIsEditable
  323. id_item.setFlags(flags)
  324. widget.setItem(row, 0, id_item) # Tool name/id
  325. tool_name_item = QtWidgets.QTableWidgetItem(name)
  326. widget.setItem(row, 1, tool_name_item)
  327. dia_item = FCDoubleSpinner()
  328. dia_item.set_precision(self.decimals)
  329. dia_item.setSingleStep(0.1)
  330. dia_item.set_range(0.0, 9999.9999)
  331. dia_item.set_value(float(tooldict['tooldia']))
  332. widget.setCellWidget(row, 2, dia_item)
  333. tool_offset_item = FCComboBox()
  334. for item in self.offset_item_options:
  335. tool_offset_item.addItem(item)
  336. tool_offset_item.set_value(tooldict['offset'])
  337. widget.setCellWidget(row, 3, tool_offset_item)
  338. c_offset_item = FCDoubleSpinner()
  339. c_offset_item.set_precision(self.decimals)
  340. c_offset_item.setSingleStep(0.1)
  341. c_offset_item.set_range(-9999.9999, 9999.9999)
  342. c_offset_item.set_value(float(tooldict['offset_value']))
  343. widget.setCellWidget(row, 4, c_offset_item)
  344. tt_item = FCComboBox()
  345. for item in self.type_item_options:
  346. tt_item.addItem(item)
  347. tt_item.set_value(tooldict['type'])
  348. widget.setCellWidget(row, 5, tt_item)
  349. tshape_item = FCComboBox()
  350. for item in self.tool_type_item_options:
  351. tshape_item.addItem(item)
  352. tshape_item.set_value(tooldict['tool_type'])
  353. widget.setCellWidget(row, 6, tshape_item)
  354. cutz_item = FCDoubleSpinner()
  355. cutz_item.set_precision(self.decimals)
  356. cutz_item.setSingleStep(0.1)
  357. if self.app.defaults['global_machinist_setting']:
  358. cutz_item.set_range(-9999.9999, 9999.9999)
  359. else:
  360. cutz_item.set_range(-9999.9999, -0.0000)
  361. cutz_item.set_value(float(data['cutz']))
  362. widget.setCellWidget(row, 7, cutz_item)
  363. multidepth_item = FCCheckBox()
  364. multidepth_item.set_value(data['multidepth'])
  365. widget.setCellWidget(row, 8, multidepth_item)
  366. # to make the checkbox centered but it can no longer have it's value accessed - needs a fix using findchild()
  367. # multidepth_item = QtWidgets.QWidget()
  368. # cb = FCCheckBox()
  369. # cb.set_value(data['multidepth'])
  370. # qhboxlayout = QtWidgets.QHBoxLayout(multidepth_item)
  371. # qhboxlayout.addWidget(cb)
  372. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  373. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  374. # widget.setCellWidget(row, 8, multidepth_item)
  375. depth_per_pass_item = FCDoubleSpinner()
  376. depth_per_pass_item.set_precision(self.decimals)
  377. depth_per_pass_item.setSingleStep(0.1)
  378. depth_per_pass_item.set_range(0.0, 9999.9999)
  379. depth_per_pass_item.set_value(float(data['depthperpass']))
  380. widget.setCellWidget(row, 9, depth_per_pass_item)
  381. vtip_dia_item = FCDoubleSpinner()
  382. vtip_dia_item.set_precision(self.decimals)
  383. vtip_dia_item.setSingleStep(0.1)
  384. vtip_dia_item.set_range(0.0, 9999.9999)
  385. vtip_dia_item.set_value(float(data['vtipdia']))
  386. widget.setCellWidget(row, 10, vtip_dia_item)
  387. vtip_angle_item = FCDoubleSpinner()
  388. vtip_angle_item.set_precision(self.decimals)
  389. vtip_angle_item.setSingleStep(0.1)
  390. vtip_angle_item.set_range(-360.0, 360.0)
  391. vtip_angle_item.set_value(float(data['vtipangle']))
  392. widget.setCellWidget(row, 11, vtip_angle_item)
  393. travelz_item = FCDoubleSpinner()
  394. travelz_item.set_precision(self.decimals)
  395. travelz_item.setSingleStep(0.1)
  396. if self.app.defaults['global_machinist_setting']:
  397. travelz_item.set_range(-9999.9999, 9999.9999)
  398. else:
  399. travelz_item.set_range(0.0000, 9999.9999)
  400. travelz_item.set_value(float(data['travelz']))
  401. widget.setCellWidget(row, 12, travelz_item)
  402. fr_item = FCDoubleSpinner()
  403. fr_item.set_precision(self.decimals)
  404. fr_item.set_range(0.0, 9999.9999)
  405. fr_item.set_value(float(data['feedrate']))
  406. widget.setCellWidget(row, 13, fr_item)
  407. frz_item = FCDoubleSpinner()
  408. frz_item.set_precision(self.decimals)
  409. frz_item.set_range(0.0, 9999.9999)
  410. frz_item.set_value(float(data['feedrate_z']))
  411. widget.setCellWidget(row, 14, frz_item)
  412. frrapids_item = FCDoubleSpinner()
  413. frrapids_item.set_precision(self.decimals)
  414. frrapids_item.set_range(0.0, 9999.9999)
  415. frrapids_item.set_value(float(data['feedrate_rapid']))
  416. widget.setCellWidget(row, 15, frrapids_item)
  417. spindlespeed_item = FCSpinner()
  418. spindlespeed_item.set_range(0, 1000000)
  419. spindlespeed_item.set_value(int(data['spindlespeed']))
  420. spindlespeed_item.set_step(100)
  421. widget.setCellWidget(row, 16, spindlespeed_item)
  422. dwell_item = FCCheckBox()
  423. dwell_item.set_value(data['dwell'])
  424. widget.setCellWidget(row, 17, dwell_item)
  425. dwelltime_item = FCDoubleSpinner()
  426. dwelltime_item.set_precision(self.decimals)
  427. dwelltime_item.set_range(0.0000, 9999.9999)
  428. dwelltime_item.set_value(float(data['dwelltime']))
  429. widget.setCellWidget(row, 18, dwelltime_item)
  430. pp_item = FCComboBox()
  431. for item in self.app.preprocessors:
  432. pp_item.addItem(item)
  433. pp_item.set_value(data['ppname_g'])
  434. widget.setCellWidget(row, 19, pp_item)
  435. ecut_item = FCCheckBox()
  436. ecut_item.set_value(data['extracut'])
  437. widget.setCellWidget(row, 20, ecut_item)
  438. ecut_length_item = FCDoubleSpinner()
  439. ecut_length_item.set_precision(self.decimals)
  440. ecut_length_item.set_range(0.0000, 9999.9999)
  441. ecut_length_item.set_value(data['extracut_length'])
  442. widget.setCellWidget(row, 21, ecut_length_item)
  443. toolchange_item = FCCheckBox()
  444. toolchange_item.set_value(data['toolchange'])
  445. widget.setCellWidget(row, 22, toolchange_item)
  446. toolchangexy_item = QtWidgets.QTableWidgetItem(str(data['toolchangexy']) if data['toolchangexy'] else '')
  447. widget.setItem(row, 23, toolchangexy_item)
  448. toolchangez_item = FCDoubleSpinner()
  449. toolchangez_item.set_precision(self.decimals)
  450. toolchangez_item.setSingleStep(0.1)
  451. if self.app.defaults['global_machinist_setting']:
  452. toolchangez_item.set_range(-9999.9999, 9999.9999)
  453. else:
  454. toolchangez_item.set_range(0.0000, 9999.9999)
  455. toolchangez_item.set_value(float(data['toolchangez']))
  456. widget.setCellWidget(row, 24, toolchangez_item)
  457. startz_item = QtWidgets.QTableWidgetItem(str(data['startz']) if data['startz'] else '')
  458. widget.setItem(row, 25, startz_item)
  459. endz_item = FCDoubleSpinner()
  460. endz_item.set_precision(self.decimals)
  461. endz_item.setSingleStep(0.1)
  462. if self.app.defaults['global_machinist_setting']:
  463. endz_item.set_range(-9999.9999, 9999.9999)
  464. else:
  465. endz_item.set_range(0.0000, 9999.9999)
  466. endz_item.set_value(float(data['endz']))
  467. widget.setCellWidget(row, 26, endz_item)
  468. def on_tool_add(self):
  469. """
  470. Add a tool in the DB Tool Table
  471. :return: None
  472. """
  473. default_data = {}
  474. default_data.update({
  475. "cutz": float(self.app.defaults["geometry_cutz"]),
  476. "multidepth": self.app.defaults["geometry_multidepth"],
  477. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  478. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  479. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  480. "travelz": float(self.app.defaults["geometry_travelz"]),
  481. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  482. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  483. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  484. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  485. "dwell": self.app.defaults["geometry_dwell"],
  486. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  487. "ppname_g": self.app.defaults["geometry_ppname_g"],
  488. "extracut": self.app.defaults["geometry_extracut"],
  489. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  490. "toolchange": self.app.defaults["geometry_toolchange"],
  491. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  492. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  493. "startz": self.app.defaults["geometry_startz"],
  494. "endz": float(self.app.defaults["geometry_endz"])
  495. })
  496. dict_elem = {}
  497. dict_elem['name'] = 'new_tool'
  498. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  499. dict_elem['tooldia'] = self.app.defaults["geometry_cnctooldia"]
  500. else:
  501. try:
  502. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  503. tools_diameters = [eval(a) for a in tools_string if a != '']
  504. dict_elem['tooldia'] = tools_diameters[0] if tools_diameters else 0.0
  505. except Exception as e:
  506. self.app.log.debug("ToolDB.on_tool_add() --> %s" % str(e))
  507. return
  508. dict_elem['offset'] = 'Path'
  509. dict_elem['offset_value'] = 0.0
  510. dict_elem['type'] = 'Rough'
  511. dict_elem['tool_type'] = 'C1'
  512. dict_elem['data'] = default_data
  513. new_toolid = len(self.db_tool_dict) + 1
  514. self.db_tool_dict[new_toolid] = deepcopy(dict_elem)
  515. # add the new entry to the Tools DB table
  516. self.build_db_ui()
  517. self.callback_on_edited()
  518. self.app.inform.emit('[success] %s' % _("Tool added to DB."))
  519. def on_tool_copy(self):
  520. """
  521. Copy a selection of Tools in the Tools DB table
  522. :return:
  523. """
  524. new_tool_id = self.table_widget.rowCount() + 1
  525. for model_index in self.table_widget.selectionModel().selectedRows():
  526. # index = QtCore.QPersistentModelIndex(model_index)
  527. old_tool_id = self.table_widget.item(model_index.row(), 0).text()
  528. new_tool_id += 1
  529. for toolid, dict_val in list(self.db_tool_dict.items()):
  530. if int(old_tool_id) == int(toolid):
  531. self.db_tool_dict.update({
  532. new_tool_id: deepcopy(dict_val)
  533. })
  534. self.build_db_ui()
  535. self.callback_on_edited()
  536. self.app.inform.emit('[success] %s' % _("Tool copied from Tools DB."))
  537. def on_tool_delete(self):
  538. """
  539. Delete a selection of Tools in the Tools DB table
  540. :return:
  541. """
  542. for model_index in self.table_widget.selectionModel().selectedRows():
  543. # index = QtCore.QPersistentModelIndex(model_index)
  544. toolname_to_remove = self.table_widget.item(model_index.row(), 0).text()
  545. for toolid, dict_val in list(self.db_tool_dict.items()):
  546. if int(toolname_to_remove) == int(toolid):
  547. # remove from the storage
  548. self.db_tool_dict.pop(toolid, None)
  549. self.build_db_ui()
  550. self.callback_on_edited()
  551. self.app.inform.emit('[success] %s' % _("Tool removed from Tools DB."))
  552. def on_export_tools_db_file(self):
  553. self.app.defaults.report_usage("on_export_tools_db_file")
  554. self.app.log.debug("on_export_tools_db_file()")
  555. date = str(datetime.today()).rpartition('.')[0]
  556. date = ''.join(c for c in date if c not in ':-')
  557. date = date.replace(' ', '_')
  558. filter__ = "Text File (*.TXT);;All Files (*.*)"
  559. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Tools Database"),
  560. directory='{l_save}/FlatCAM_{n}_{date}'.format(
  561. l_save=str(self.app.get_last_save_folder()),
  562. n=_("Tools_Database"),
  563. date=date),
  564. ext_filter=filter__)
  565. filename = str(filename)
  566. if filename == "":
  567. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  568. return
  569. else:
  570. try:
  571. f = open(filename, 'w')
  572. f.close()
  573. except PermissionError:
  574. self.app.inform.emit('[WARNING] %s' %
  575. _("Permission denied, saving not possible.\n"
  576. "Most likely another app is holding the file open and not accessible."))
  577. return
  578. except IOError:
  579. self.app.log.debug('Creating a new Tools DB file ...')
  580. f = open(filename, 'w')
  581. f.close()
  582. except Exception:
  583. e = sys.exc_info()[0]
  584. self.app.log.error("Could not load Tools DB file.")
  585. self.app.log.error(str(e))
  586. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  587. return
  588. # Save update options
  589. try:
  590. # Save Tools DB in a file
  591. try:
  592. with open(filename, "w") as f:
  593. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  594. except Exception as e:
  595. self.app.log.debug("App.on_save_tools_db() --> %s" % str(e))
  596. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  597. return
  598. except Exception:
  599. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  600. return
  601. self.app.inform.emit('[success] %s: %s' % (_("Exported Tools DB to"), filename))
  602. def on_import_tools_db_file(self):
  603. self.app.defaults.report_usage("on_import_tools_db_file")
  604. self.app.log.debug("on_import_tools_db_file()")
  605. filter__ = "Text File (*.TXT);;All Files (*.*)"
  606. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Tools DB"), filter=filter__)
  607. if filename == "":
  608. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  609. else:
  610. try:
  611. with open(filename) as f:
  612. tools_in_db = f.read()
  613. except IOError:
  614. self.app.log.error("Could not load Tools DB file.")
  615. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  616. return
  617. try:
  618. self.db_tool_dict = json.loads(tools_in_db)
  619. except Exception:
  620. e = sys.exc_info()[0]
  621. self.app.log.error(str(e))
  622. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  623. return
  624. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  625. self.build_db_ui()
  626. self.callback_on_edited()
  627. def on_save_tools_db(self, silent=False):
  628. self.app.log.debug("ToolsDB.on_save_button() --> Saving Tools Database to file.")
  629. filename = self.app.data_path + "/geo_tools_db.FlatDB"
  630. # Preferences save, update the color of the Tools DB Tab text
  631. for idx in range(self.app_ui.plot_tab_area.count()):
  632. if self.app_ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  633. self.app_ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  634. # Save Tools DB in a file
  635. try:
  636. f = open(filename, "w")
  637. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  638. f.close()
  639. except Exception as e:
  640. self.app.log.debug("ToolsDB.on_save_tools_db() --> %s" % str(e))
  641. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  642. return
  643. if not silent:
  644. self.app.inform.emit('[success] %s' % _("Saved Tools DB."))
  645. def ui_connect(self):
  646. try:
  647. try:
  648. self.table_widget.itemChanged.disconnect(self.callback_on_edited)
  649. except (TypeError, AttributeError):
  650. pass
  651. self.table_widget.itemChanged.connect(self.callback_on_edited)
  652. except AttributeError:
  653. pass
  654. for row in range(self.table_widget.rowCount()):
  655. for col in range(self.table_widget.columnCount()):
  656. # ComboBox
  657. try:
  658. try:
  659. self.table_widget.cellWidget(row, col).currentIndexChanged.disconnect(self.callback_on_edited)
  660. except (TypeError, AttributeError):
  661. pass
  662. self.table_widget.cellWidget(row, col).currentIndexChanged.connect(self.callback_on_edited)
  663. except AttributeError:
  664. pass
  665. # CheckBox
  666. try:
  667. try:
  668. self.table_widget.cellWidget(row, col).toggled.disconnect(self.callback_on_edited)
  669. except (TypeError, AttributeError):
  670. pass
  671. self.table_widget.cellWidget(row, col).toggled.connect(self.callback_on_edited)
  672. except AttributeError:
  673. pass
  674. # SpinBox, DoubleSpinBox
  675. try:
  676. try:
  677. self.table_widget.cellWidget(row, col).valueChanged.disconnect(self.callback_on_edited)
  678. except (TypeError, AttributeError):
  679. pass
  680. self.table_widget.cellWidget(row, col).valueChanged.connect(self.callback_on_edited)
  681. except AttributeError:
  682. pass
  683. def ui_disconnect(self):
  684. try:
  685. self.table_widget.itemChanged.disconnect(self.callback_on_edited)
  686. except (TypeError, AttributeError):
  687. pass
  688. for row in range(self.table_widget.rowCount()):
  689. for col in range(self.table_widget.columnCount()):
  690. # ComboBox
  691. try:
  692. self.table_widget.cellWidget(row, col).currentIndexChanged.disconnect(self.callback_on_edited)
  693. except (TypeError, AttributeError):
  694. pass
  695. # CheckBox
  696. try:
  697. self.table_widget.cellWidget(row, col).toggled.disconnect(self.callback_on_edited)
  698. except (TypeError, AttributeError):
  699. pass
  700. # SpinBox, DoubleSpinBox
  701. try:
  702. self.table_widget.cellWidget(row, col).valueChanged.disconnect(self.callback_on_edited)
  703. except (TypeError, AttributeError):
  704. pass
  705. def callback_on_edited(self):
  706. # update the dictionary storage self.db_tool_dict
  707. self.db_tool_dict.clear()
  708. dict_elem = {}
  709. default_data = {}
  710. for row in range(self.table_widget.rowCount()):
  711. new_toolid = row + 1
  712. for col in range(self.table_widget.columnCount()):
  713. column_header_text = self.table_widget.horizontalHeaderItem(col).text()
  714. if column_header_text == _('Tool Name'):
  715. dict_elem['name'] = self.table_widget.item(row, col).text()
  716. elif column_header_text == _('Tool Dia'):
  717. dict_elem['tooldia'] = self.table_widget.cellWidget(row, col).get_value()
  718. elif column_header_text == _('Tool Offset'):
  719. dict_elem['offset'] = self.table_widget.cellWidget(row, col).get_value()
  720. elif column_header_text == _('Custom Offset'):
  721. dict_elem['offset_value'] = self.table_widget.cellWidget(row, col).get_value()
  722. elif column_header_text == _('Tool Type'):
  723. dict_elem['type'] = self.table_widget.cellWidget(row, col).get_value()
  724. elif column_header_text == _('Tool Shape'):
  725. dict_elem['tool_type'] = self.table_widget.cellWidget(row, col).get_value()
  726. else:
  727. if column_header_text == _('Cut Z'):
  728. default_data['cutz'] = self.table_widget.cellWidget(row, col).get_value()
  729. elif column_header_text == _('MultiDepth'):
  730. default_data['multidepth'] = self.table_widget.cellWidget(row, col).get_value()
  731. elif column_header_text == _('DPP'):
  732. default_data['depthperpass'] = self.table_widget.cellWidget(row, col).get_value()
  733. elif column_header_text == _('V-Dia'):
  734. default_data['vtipdia'] = self.table_widget.cellWidget(row, col).get_value()
  735. elif column_header_text == _('V-Angle'):
  736. default_data['vtipangle'] = self.table_widget.cellWidget(row, col).get_value()
  737. elif column_header_text == _('Travel Z'):
  738. default_data['travelz'] = self.table_widget.cellWidget(row, col).get_value()
  739. elif column_header_text == _('FR'):
  740. default_data['feedrate'] = self.table_widget.cellWidget(row, col).get_value()
  741. elif column_header_text == _('FR Z'):
  742. default_data['feedrate_z'] = self.table_widget.cellWidget(row, col).get_value()
  743. elif column_header_text == _('FR Rapids'):
  744. default_data['feedrate_rapid'] = self.table_widget.cellWidget(row, col).get_value()
  745. elif column_header_text == _('Spindle Speed'):
  746. default_data['spindlespeed'] = self.table_widget.cellWidget(row, col).get_value()
  747. elif column_header_text == _('Dwell'):
  748. default_data['dwell'] = self.table_widget.cellWidget(row, col).get_value()
  749. elif column_header_text == _('Dwelltime'):
  750. default_data['dwelltime'] = self.table_widget.cellWidget(row, col).get_value()
  751. elif column_header_text == _('Preprocessor'):
  752. default_data['ppname_g'] = self.table_widget.cellWidget(row, col).get_value()
  753. elif column_header_text == _('ExtraCut'):
  754. default_data['extracut'] = self.table_widget.cellWidget(row, col).get_value()
  755. elif column_header_text == _("E-Cut Length"):
  756. default_data['extracut_length'] = self.table_widget.cellWidget(row, col).get_value()
  757. elif column_header_text == _('Toolchange'):
  758. default_data['toolchange'] = self.table_widget.cellWidget(row, col).get_value()
  759. elif column_header_text == _('Toolchange XY'):
  760. default_data['toolchangexy'] = self.table_widget.item(row, col).text()
  761. elif column_header_text == _('Toolchange Z'):
  762. default_data['toolchangez'] = self.table_widget.cellWidget(row, col).get_value()
  763. elif column_header_text == _('Start Z'):
  764. default_data['startz'] = float(self.table_widget.item(row, col).text()) \
  765. if self.table_widget.item(row, col).text() != '' else None
  766. elif column_header_text == _('End Z'):
  767. default_data['endz'] = self.table_widget.cellWidget(row, col).get_value()
  768. dict_elem['data'] = default_data
  769. self.db_tool_dict.update(
  770. {
  771. new_toolid: deepcopy(dict_elem)
  772. }
  773. )
  774. self.callback_app()
  775. def on_tool_requested_from_app(self):
  776. if not self.table_widget.selectionModel().selectedRows():
  777. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("No Tool/row selected in the Tools Database table"))
  778. return
  779. model_index_list = self.table_widget.selectionModel().selectedRows()
  780. for model_index in model_index_list:
  781. selected_row = model_index.row()
  782. tool_uid = selected_row + 1
  783. for key in self.db_tool_dict.keys():
  784. if str(key) == str(tool_uid):
  785. selected_tool = self.db_tool_dict[key]
  786. self.on_tool_request(tool=selected_tool)
  787. def on_cancel_tool(self):
  788. for idx in range(self.app_ui.plot_tab_area.count()):
  789. if self.app_ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  790. wdg = self.app_ui.plot_tab_area.widget(idx)
  791. wdg.deleteLater()
  792. self.app_ui.plot_tab_area.removeTab(idx)
  793. self.app.inform.emit('%s' % _("Cancelled adding tool from DB."))
  794. # def resize_new_tool_table_widget(self, min_size, max_size):
  795. # """
  796. # Resize the table widget responsible for adding new tool in the Tool Database
  797. #
  798. # :param min_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  799. # :param max_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  800. # :return:
  801. # """
  802. # t_height = self.t_height
  803. # if max_size > min_size:
  804. # t_height = self.t_height + self.new_tool_table_widget.verticalScrollBar().height()
  805. #
  806. # self.new_tool_table_widget.setMaximumHeight(t_height)
  807. def closeEvent(self, QCloseEvent):
  808. super().closeEvent(QCloseEvent)
  809. class ToolsDB2UI:
  810. def __init__(self, app, grid_layout):
  811. self.app = app
  812. self.decimals = self.app.decimals
  813. settings = QtCore.QSettings("Open Source", "FlatCAM")
  814. if settings.contains("machinist"):
  815. self.machinist_setting = settings.value('machinist', type=int)
  816. else:
  817. self.machinist_setting = 0
  818. self.g_lay = grid_layout
  819. tree_layout = QtWidgets.QVBoxLayout()
  820. self.g_lay.addLayout(tree_layout, 0, 0)
  821. self.tree_widget = FCTree(columns=2, header_hidden=False, protected_column=[0])
  822. self.tree_widget.setHeaderLabels(["ID", "Tool Name"])
  823. self.tree_widget.setIndentation(0)
  824. self.tree_widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
  825. self.tree_widget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  826. # set alternating colors
  827. # self.tree_widget.setAlternatingRowColors(True)
  828. # p = QtGui.QPalette()
  829. # p.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(226, 237, 253) )
  830. # self.tree_widget.setPalette(p)
  831. self.tree_widget.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
  832. tree_layout.addWidget(self.tree_widget)
  833. param_hlay = QtWidgets.QHBoxLayout()
  834. param_area = QtWidgets.QScrollArea()
  835. param_widget = QtWidgets.QWidget()
  836. param_widget.setLayout(param_hlay)
  837. param_area.setWidget(param_widget)
  838. param_area.setWidgetResizable(True)
  839. self.g_lay.addWidget(param_area, 0, 1)
  840. # ###########################################################################
  841. # ############## The UI form ################################################
  842. # ###########################################################################
  843. # Tool description box
  844. self.tool_description_box = QtWidgets.QGroupBox()
  845. self.tool_description_box.setStyleSheet("""
  846. QGroupBox
  847. {
  848. font-size: 16px;
  849. font-weight: bold;
  850. }
  851. """)
  852. self.description_vlay = QtWidgets.QVBoxLayout()
  853. self.tool_description_box.setTitle(_("Tool Description"))
  854. self.tool_description_box.setFixedWidth(250)
  855. # Milling box
  856. self.milling_box = QtWidgets.QGroupBox()
  857. self.milling_box.setStyleSheet("""
  858. QGroupBox
  859. {
  860. font-size: 16px;
  861. font-weight: bold;
  862. }
  863. """)
  864. self.milling_vlay = QtWidgets.QVBoxLayout()
  865. self.milling_box.setTitle(_("Milling Parameters"))
  866. self.milling_box.setFixedWidth(250)
  867. # NCC TOOL BOX
  868. self.ncc_box = QtWidgets.QGroupBox()
  869. self.ncc_box.setStyleSheet("""
  870. QGroupBox
  871. {
  872. font-size: 16px;
  873. font-weight: bold;
  874. }
  875. """)
  876. self.ncc_vlay = QtWidgets.QVBoxLayout()
  877. self.ncc_box.setTitle(_("NCC Parameters"))
  878. self.ncc_box.setFixedWidth(250)
  879. # PAINT TOOL BOX
  880. self.paint_box = QtWidgets.QGroupBox()
  881. self.paint_box.setStyleSheet("""
  882. QGroupBox
  883. {
  884. font-size: 16px;
  885. font-weight: bold;
  886. }
  887. """)
  888. self.paint_vlay = QtWidgets.QVBoxLayout()
  889. self.paint_box.setTitle(_("Paint Parameters"))
  890. self.paint_box.setFixedWidth(250)
  891. # ISOLATION TOOL BOX
  892. self.iso_box = QtWidgets.QGroupBox()
  893. self.iso_box.setStyleSheet("""
  894. QGroupBox
  895. {
  896. font-size: 16px;
  897. font-weight: bold;
  898. }
  899. """)
  900. self.iso_vlay = QtWidgets.QVBoxLayout()
  901. self.iso_box.setTitle(_("Isolation Parameters"))
  902. self.iso_box.setFixedWidth(250)
  903. # DRILLING TOOL BOX
  904. self.drill_box = QtWidgets.QGroupBox()
  905. self.drill_box.setStyleSheet("""
  906. QGroupBox
  907. {
  908. font-size: 16px;
  909. font-weight: bold;
  910. }
  911. """)
  912. self.drill_vlay = QtWidgets.QVBoxLayout()
  913. self.drill_box.setTitle(_("Drilling Parameters"))
  914. self.drill_box.setFixedWidth(250)
  915. # Layout Constructor
  916. self.tool_description_box.setLayout(self.description_vlay)
  917. self.milling_box.setLayout(self.milling_vlay)
  918. self.ncc_box.setLayout(self.ncc_vlay)
  919. self.paint_box.setLayout(self.paint_vlay)
  920. self.iso_box.setLayout(self.iso_vlay)
  921. self.drill_box.setLayout(self.drill_vlay)
  922. descript_vlay = QtWidgets.QVBoxLayout()
  923. descript_vlay.addWidget(self.tool_description_box)
  924. descript_vlay.addStretch()
  925. milling_vlay = QtWidgets.QVBoxLayout()
  926. milling_vlay.addWidget(self.milling_box)
  927. milling_vlay.addStretch()
  928. tools1_vlay = QtWidgets.QVBoxLayout()
  929. tools1_vlay.addWidget(self.drill_box)
  930. tools1_vlay.addWidget(self.iso_box)
  931. tools1_vlay.addStretch()
  932. tools2_vlay = QtWidgets.QVBoxLayout()
  933. tools2_vlay.addWidget(self.paint_box)
  934. tools2_vlay.addWidget(self.ncc_box)
  935. tools2_vlay.addStretch()
  936. param_hlay.addLayout(descript_vlay)
  937. param_hlay.addLayout(tools1_vlay)
  938. param_hlay.addLayout(tools2_vlay)
  939. # always visible, always to be included last
  940. param_hlay.addLayout(milling_vlay)
  941. param_hlay.addStretch()
  942. # ###########################################################################
  943. # ################ Tool UI form #############################################
  944. # ###########################################################################
  945. self.grid_tool = QtWidgets.QGridLayout()
  946. self.description_vlay.addLayout(self.grid_tool)
  947. self.grid_tool.setColumnStretch(0, 0)
  948. self.grid_tool.setColumnStretch(1, 1)
  949. self.description_vlay.addStretch()
  950. # Tool Name
  951. self.name_label = QtWidgets.QLabel('<span style="color:red;"><b>%s:</b></span>' % _('Name'))
  952. self.name_label.setToolTip(
  953. _("Tool name.\n"
  954. "This is not used in the app, it's function\n"
  955. "is to serve as a note for the user."))
  956. self.name_entry = FCEntry()
  957. self.name_entry.setObjectName('gdb_name')
  958. self.grid_tool.addWidget(self.name_label, 0, 0)
  959. self.grid_tool.addWidget(self.name_entry, 0, 1)
  960. # Tool Dia
  961. self.dia_label = QtWidgets.QLabel('%s:' % _('Diameter'))
  962. self.dia_label.setToolTip(
  963. _("Tool Diameter."))
  964. self.dia_entry = FCDoubleSpinner()
  965. self.dia_entry.set_range(-9999.9999, 9999.9999)
  966. self.dia_entry.set_precision(self.decimals)
  967. self.dia_entry.setObjectName('gdb_dia')
  968. self.grid_tool.addWidget(self.dia_label, 1, 0)
  969. self.grid_tool.addWidget(self.dia_entry, 1, 1)
  970. # Tool Tolerance
  971. self.tol_label = QtWidgets.QLabel("<b>%s:</b>" % _("Diameter Tolerance"))
  972. self.tol_label.setToolTip(
  973. _("Tool tolerance. If there is a tool in the targeted tools table with\n"
  974. "the value within the limits then this tool from DB will be used.")
  975. )
  976. self.grid_tool.addWidget(self.tol_label, 2, 0, 1, 2)
  977. # Tolerance Min Limit
  978. self.min_limit_label = QtWidgets.QLabel('%s:' % _("Min"))
  979. self.min_limit_label.setToolTip(
  980. _("Set the tool tolerance minimum.")
  981. )
  982. self.tol_min_entry = FCDoubleSpinner(callback=self.confirmation_message)
  983. self.tol_min_entry.set_precision(self.decimals)
  984. self.tol_min_entry.set_range(0, 9999.9999)
  985. self.tol_min_entry.setSingleStep(0.1)
  986. self.tol_min_entry.setObjectName("gdb_tol_min")
  987. self.grid_tool.addWidget(self.min_limit_label, 4, 0)
  988. self.grid_tool.addWidget(self.tol_min_entry, 4, 1)
  989. # Tolerance Min Limit
  990. self.max_limit_label = QtWidgets.QLabel('%s:' % _("Max"))
  991. self.max_limit_label.setToolTip(
  992. _("Set the tool tolerance maximum.")
  993. )
  994. self.tol_max_entry = FCDoubleSpinner(callback=self.confirmation_message)
  995. self.tol_max_entry.set_precision(self.decimals)
  996. self.tol_max_entry.set_range(0, 9999.9999)
  997. self.tol_max_entry.setSingleStep(0.1)
  998. self.tol_max_entry.setObjectName("gdb_tol_max")
  999. self.grid_tool.addWidget(self.max_limit_label, 6, 0)
  1000. self.grid_tool.addWidget(self.tol_max_entry, 6, 1)
  1001. # Tool Object Type
  1002. self.tool_op_label = QtWidgets.QLabel('<b>%s:</b>' % _('Operation'))
  1003. self.tool_op_label.setToolTip(
  1004. _("The kind of Application Tool where this tool is to be used."))
  1005. self.tool_op_combo = FCComboBox()
  1006. self.tool_op_combo.addItems([_("General"), _("Milling"), _("Drilling"), _('Isolation'), _('Paint'), _('NCC')])
  1007. self.tool_op_combo.setObjectName('gdb_tool_target')
  1008. self.grid_tool.addWidget(self.tool_op_label, 8, 0)
  1009. self.grid_tool.addWidget(self.tool_op_combo, 8, 1)
  1010. # ###########################################################################
  1011. # ############### MILLING UI form ###########################################
  1012. # ###########################################################################
  1013. self.grid0 = QtWidgets.QGridLayout()
  1014. self.milling_vlay.addLayout(self.grid0)
  1015. self.grid0.setColumnStretch(0, 0)
  1016. self.grid0.setColumnStretch(1, 1)
  1017. self.milling_vlay.addStretch()
  1018. # Tool Shape
  1019. self.shape_label = QtWidgets.QLabel('%s:' % _('Shape'))
  1020. self.shape_label.setToolTip(
  1021. _("Tool Shape. \n"
  1022. "Can be:\n"
  1023. "C1 ... C4 = circular tool with x flutes\n"
  1024. "B = ball tip milling tool\n"
  1025. "V = v-shape milling tool"))
  1026. self.shape_combo = FCComboBox()
  1027. self.shape_combo.addItems(["C1", "C2", "C3", "C4", "B", "V"])
  1028. self.shape_combo.setObjectName('gdb_shape')
  1029. self.grid0.addWidget(self.shape_label, 2, 0)
  1030. self.grid0.addWidget(self.shape_combo, 2, 1)
  1031. # V-Dia
  1032. self.vdia_label = QtWidgets.QLabel('%s:' % _("V-Dia"))
  1033. self.vdia_label.setToolTip(
  1034. _("V-Dia.\n"
  1035. "Diameter of the tip for V-Shape Tools."))
  1036. self.vdia_entry = FCDoubleSpinner()
  1037. self.vdia_entry.set_range(0.0000, 9999.9999)
  1038. self.vdia_entry.set_precision(self.decimals)
  1039. self.vdia_entry.setObjectName('gdb_vdia')
  1040. self.grid0.addWidget(self.vdia_label, 4, 0)
  1041. self.grid0.addWidget(self.vdia_entry, 4, 1)
  1042. # V-Angle
  1043. self.vangle_label = QtWidgets.QLabel('%s:' % _("V-Angle"))
  1044. self.vangle_label.setToolTip(
  1045. _("V-Agle.\n"
  1046. "Angle at the tip for the V-Shape Tools."))
  1047. self.vangle_entry = FCDoubleSpinner()
  1048. self.vangle_entry.set_range(-360.0, 360.0)
  1049. self.vangle_entry.set_precision(self.decimals)
  1050. self.vangle_entry.setObjectName('gdb_vangle')
  1051. self.grid0.addWidget(self.vangle_label, 6, 0)
  1052. self.grid0.addWidget(self.vangle_entry, 6, 1)
  1053. separator_line = QtWidgets.QFrame()
  1054. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1055. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1056. self.grid0.addWidget(separator_line, 8, 0, 1, 2)
  1057. # Tool Type
  1058. self.type_label = QtWidgets.QLabel('%s:' % _("Tool Type"))
  1059. self.type_label.setToolTip(
  1060. _("Tool Type.\n"
  1061. "Can be:\n"
  1062. "Iso = isolation cut\n"
  1063. "Rough = rough cut, low feedrate, multiple passes\n"
  1064. "Finish = finishing cut, high feedrate"))
  1065. self.type_combo = FCComboBox()
  1066. self.type_combo.addItems(["Iso", "Rough", "Finish"])
  1067. self.type_combo.setObjectName('gdb_type')
  1068. self.grid0.addWidget(self.type_label, 10, 0)
  1069. self.grid0.addWidget(self.type_combo, 10, 1)
  1070. # Tool Offset
  1071. self.tooloffset_label = QtWidgets.QLabel('%s:' % _('Tool Offset'))
  1072. self.tooloffset_label.setToolTip(
  1073. _("Tool Offset.\n"
  1074. "Can be of a few types:\n"
  1075. "Path = zero offset\n"
  1076. "In = offset inside by half of tool diameter\n"
  1077. "Out = offset outside by half of tool diameter\n"
  1078. "Custom = custom offset using the Custom Offset value"))
  1079. self.tooloffset_combo = FCComboBox()
  1080. self.tooloffset_combo.addItems(["Path", "In", "Out", "Custom"])
  1081. self.tooloffset_combo.setObjectName('gdb_tool_offset')
  1082. self.grid0.addWidget(self.tooloffset_label, 12, 0)
  1083. self.grid0.addWidget(self.tooloffset_combo, 12, 1)
  1084. # Custom Offset
  1085. self.custom_offset_label = QtWidgets.QLabel('%s:' % _("Custom Offset"))
  1086. self.custom_offset_label.setToolTip(
  1087. _("Custom Offset.\n"
  1088. "A value to be used as offset from the current path."))
  1089. self.custom_offset_entry = FCDoubleSpinner()
  1090. self.custom_offset_entry.set_range(-9999.9999, 9999.9999)
  1091. self.custom_offset_entry.set_precision(self.decimals)
  1092. self.custom_offset_entry.setObjectName('gdb_custom_offset')
  1093. self.grid0.addWidget(self.custom_offset_label, 14, 0)
  1094. self.grid0.addWidget(self.custom_offset_entry, 14, 1)
  1095. separator_line = QtWidgets.QFrame()
  1096. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1097. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1098. self.grid0.addWidget(separator_line, 16, 0, 1, 2)
  1099. # Cut Z
  1100. self.cutz_label = QtWidgets.QLabel('%s:' % _("Cut Z"))
  1101. self.cutz_label.setToolTip(
  1102. _("Cutting Depth.\n"
  1103. "The depth at which to cut into material."))
  1104. self.cutz_entry = FCDoubleSpinner()
  1105. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  1106. self.cutz_entry.set_precision(self.decimals)
  1107. self.cutz_entry.setObjectName('gdb_cutz')
  1108. self.grid0.addWidget(self.cutz_label, 18, 0)
  1109. self.grid0.addWidget(self.cutz_entry, 18, 1)
  1110. # Multi Depth
  1111. self.multidepth_label = QtWidgets.QLabel('%s:' % _("MultiDepth"))
  1112. self.multidepth_label.setToolTip(
  1113. _("Multi Depth.\n"
  1114. "Selecting this will allow cutting in multiple passes,\n"
  1115. "each pass adding a DPP parameter depth."))
  1116. self.multidepth_cb = FCCheckBox()
  1117. self.multidepth_cb.setObjectName('gdb_multidepth')
  1118. self.grid0.addWidget(self.multidepth_label, 20, 0)
  1119. self.grid0.addWidget(self.multidepth_cb, 20, 1)
  1120. # Depth Per Pass
  1121. self.dpp_label = QtWidgets.QLabel('%s:' % _("DPP"))
  1122. self.dpp_label.setToolTip(
  1123. _("DPP. Depth per Pass.\n"
  1124. "The value used to cut into material on each pass."))
  1125. self.multidepth_entry = FCDoubleSpinner()
  1126. self.multidepth_entry.set_range(-9999.9999, 9999.9999)
  1127. self.multidepth_entry.set_precision(self.decimals)
  1128. self.multidepth_entry.setObjectName('gdb_multidepth_entry')
  1129. self.grid0.addWidget(self.dpp_label, 22, 0)
  1130. self.grid0.addWidget(self.multidepth_entry, 22, 1)
  1131. # Travel Z
  1132. self.travelz_label = QtWidgets.QLabel('%s:' % _("Travel Z"))
  1133. self.travelz_label.setToolTip(
  1134. _("Clearance Height.\n"
  1135. "Height at which the milling bit will travel between cuts,\n"
  1136. "above the surface of the material, avoiding all fixtures."))
  1137. self.travelz_entry = FCDoubleSpinner()
  1138. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  1139. self.travelz_entry.set_precision(self.decimals)
  1140. self.travelz_entry.setObjectName('gdb_travelz')
  1141. self.grid0.addWidget(self.travelz_label, 24, 0)
  1142. self.grid0.addWidget(self.travelz_entry, 24, 1)
  1143. # Extra Cut
  1144. self.ecut_label = QtWidgets.QLabel('%s:' % _("ExtraCut"))
  1145. self.ecut_label.setToolTip(
  1146. _("Extra Cut.\n"
  1147. "If checked, after a isolation is finished an extra cut\n"
  1148. "will be added where the start and end of isolation meet\n"
  1149. "such as that this point is covered by this extra cut to\n"
  1150. "ensure a complete isolation."))
  1151. self.ecut_cb = FCCheckBox()
  1152. self.ecut_cb.setObjectName('gdb_ecut')
  1153. self.grid0.addWidget(self.ecut_label, 26, 0)
  1154. self.grid0.addWidget(self.ecut_cb, 26, 1)
  1155. # Extra Cut Length
  1156. self.ecut_length_label = QtWidgets.QLabel('%s:' % _("E-Cut Length"))
  1157. self.ecut_length_label.setToolTip(
  1158. _("Extra Cut length.\n"
  1159. "If checked, after a isolation is finished an extra cut\n"
  1160. "will be added where the start and end of isolation meet\n"
  1161. "such as that this point is covered by this extra cut to\n"
  1162. "ensure a complete isolation. This is the length of\n"
  1163. "the extra cut."))
  1164. self.ecut_length_entry = FCDoubleSpinner()
  1165. self.ecut_length_entry.set_range(0.0000, 9999.9999)
  1166. self.ecut_length_entry.set_precision(self.decimals)
  1167. self.ecut_length_entry.setObjectName('gdb_ecut_length')
  1168. self.grid0.addWidget(self.ecut_length_label, 28, 0)
  1169. self.grid0.addWidget(self.ecut_length_entry, 28, 1)
  1170. separator_line = QtWidgets.QFrame()
  1171. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1172. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1173. self.grid0.addWidget(separator_line, 30, 0, 1, 2)
  1174. # Feedrate X-Y
  1175. self.frxy_label = QtWidgets.QLabel('%s:' % _("Feedrate X-Y"))
  1176. self.frxy_label.setToolTip(
  1177. _("Feedrate X-Y. Feedrate\n"
  1178. "The speed on XY plane used while cutting into material."))
  1179. self.frxy_entry = FCDoubleSpinner()
  1180. self.frxy_entry.set_range(-999999.9999, 999999.9999)
  1181. self.frxy_entry.set_precision(self.decimals)
  1182. self.frxy_entry.setObjectName('gdb_frxy')
  1183. self.grid0.addWidget(self.frxy_label, 32, 0)
  1184. self.grid0.addWidget(self.frxy_entry, 32, 1)
  1185. # Feedrate Z
  1186. self.frz_label = QtWidgets.QLabel('%s:' % _("Feedrate Z"))
  1187. self.frz_label.setToolTip(
  1188. _("Feedrate Z\n"
  1189. "The speed on Z plane."))
  1190. self.frz_entry = FCDoubleSpinner()
  1191. self.frz_entry.set_range(-999999.9999, 999999.9999)
  1192. self.frz_entry.set_precision(self.decimals)
  1193. self.frz_entry.setObjectName('gdb_frz')
  1194. self.grid0.addWidget(self.frz_label, 34, 0)
  1195. self.grid0.addWidget(self.frz_entry, 34, 1)
  1196. # Feedrate Rapids
  1197. self.frapids_label = QtWidgets.QLabel('%s:' % _("FR Rapids"))
  1198. self.frapids_label.setToolTip(
  1199. _("FR Rapids. Feedrate Rapids\n"
  1200. "Speed used while moving as fast as possible.\n"
  1201. "This is used only by some devices that can't use\n"
  1202. "the G0 g-code command. Mostly 3D printers."))
  1203. self.frapids_entry = FCDoubleSpinner()
  1204. self.frapids_entry.set_range(0.0000, 9999.9999)
  1205. self.frapids_entry.set_precision(self.decimals)
  1206. self.frapids_entry.setObjectName('gdb_frapids')
  1207. self.grid0.addWidget(self.frapids_label, 36, 0)
  1208. self.grid0.addWidget(self.frapids_entry, 36, 1)
  1209. separator_line = QtWidgets.QFrame()
  1210. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1211. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1212. self.grid0.addWidget(separator_line, 38, 0, 1, 2)
  1213. # Spindle Spped
  1214. self.spindle_label = QtWidgets.QLabel('%s:' % _("Spindle Speed"))
  1215. self.spindle_label.setToolTip(
  1216. _("Spindle Speed.\n"
  1217. "If it's left empty it will not be used.\n"
  1218. "The speed of the spindle in RPM."))
  1219. self.spindle_entry = FCDoubleSpinner()
  1220. self.spindle_entry.set_range(-999999.9999, 999999.9999)
  1221. self.spindle_entry.set_precision(self.decimals)
  1222. self.spindle_entry.setObjectName('gdb_spindle')
  1223. self.grid0.addWidget(self.spindle_label, 40, 0)
  1224. self.grid0.addWidget(self.spindle_entry, 40, 1)
  1225. # Dwell
  1226. self.dwell_label = QtWidgets.QLabel('%s:' % _("Dwell"))
  1227. self.dwell_label.setToolTip(
  1228. _("Dwell.\n"
  1229. "Check this if a delay is needed to allow\n"
  1230. "the spindle motor to reach its set speed."))
  1231. self.dwell_cb = FCCheckBox()
  1232. self.dwell_cb.setObjectName('gdb_dwell')
  1233. self.grid0.addWidget(self.dwell_label, 42, 0)
  1234. self.grid0.addWidget(self.dwell_cb, 42, 1)
  1235. # Dwell Time
  1236. self.dwelltime_label = QtWidgets.QLabel('%s:' % _("Dwelltime"))
  1237. self.dwelltime_label.setToolTip(
  1238. _("Dwell Time.\n"
  1239. "A delay used to allow the motor spindle reach its set speed."))
  1240. self.dwelltime_entry = FCDoubleSpinner()
  1241. self.dwelltime_entry.set_range(0.0000, 9999.9999)
  1242. self.dwelltime_entry.set_precision(self.decimals)
  1243. self.dwelltime_entry.setObjectName('gdb_dwelltime')
  1244. self.grid0.addWidget(self.dwelltime_label, 44, 0)
  1245. self.grid0.addWidget(self.dwelltime_entry, 44, 1)
  1246. # ###########################################################################
  1247. # ############### NCC UI form ###############################################
  1248. # ###########################################################################
  1249. self.grid2 = QtWidgets.QGridLayout()
  1250. self.ncc_vlay.addLayout(self.grid2)
  1251. self.grid2.setColumnStretch(0, 0)
  1252. self.grid2.setColumnStretch(1, 1)
  1253. self.ncc_vlay.addStretch()
  1254. # Operation
  1255. op_label = QtWidgets.QLabel('%s:' % _('Operation'))
  1256. op_label.setToolTip(
  1257. _("The 'Operation' can be:\n"
  1258. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  1259. "If it's not successful then the non-copper clearing will fail, too.\n"
  1260. "- Clear -> the regular non-copper clearing.")
  1261. )
  1262. self.op_radio = RadioSet([
  1263. {"label": _("Clear"), "value": "clear"},
  1264. {"label": _("Isolation"), "value": "iso"}
  1265. ], orientation='horizontal', stretch=False)
  1266. self.op_radio.setObjectName("gdb_n_operation")
  1267. self.grid2.addWidget(op_label, 13, 0)
  1268. self.grid2.addWidget(self.op_radio, 13, 1)
  1269. # Milling Type Radio Button
  1270. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  1271. self.milling_type_label.setToolTip(
  1272. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1273. "- climb / best for precision milling and to reduce tool usage\n"
  1274. "- conventional / useful when there is no backlash compensation")
  1275. )
  1276. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  1277. {'label': _('Conventional'), 'value': 'cv'}])
  1278. self.milling_type_radio.setToolTip(
  1279. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1280. "- climb / best for precision milling and to reduce tool usage\n"
  1281. "- conventional / useful when there is no backlash compensation")
  1282. )
  1283. self.milling_type_radio.setObjectName("gdb_n_milling_type")
  1284. self.grid2.addWidget(self.milling_type_label, 14, 0)
  1285. self.grid2.addWidget(self.milling_type_radio, 14, 1)
  1286. # Overlap Entry
  1287. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1288. nccoverlabel.setToolTip(
  1289. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  1290. "Adjust the value starting with lower values\n"
  1291. "and increasing it if areas that should be cleared are still \n"
  1292. "not cleared.\n"
  1293. "Lower values = faster processing, faster execution on CNC.\n"
  1294. "Higher values = slow processing and slow execution on CNC\n"
  1295. "due of too many paths.")
  1296. )
  1297. self.ncc_overlap_entry = FCDoubleSpinner(suffix='%')
  1298. self.ncc_overlap_entry.set_precision(self.decimals)
  1299. self.ncc_overlap_entry.setWrapping(True)
  1300. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  1301. self.ncc_overlap_entry.setSingleStep(0.1)
  1302. self.ncc_overlap_entry.setObjectName("gdb_n_overlap")
  1303. self.grid2.addWidget(nccoverlabel, 15, 0)
  1304. self.grid2.addWidget(self.ncc_overlap_entry, 15, 1)
  1305. # Margin
  1306. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  1307. nccmarginlabel.setToolTip(
  1308. _("Bounding box margin.")
  1309. )
  1310. self.ncc_margin_entry = FCDoubleSpinner()
  1311. self.ncc_margin_entry.set_precision(self.decimals)
  1312. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  1313. self.ncc_margin_entry.setObjectName("gdb_n_margin")
  1314. self.grid2.addWidget(nccmarginlabel, 16, 0)
  1315. self.grid2.addWidget(self.ncc_margin_entry, 16, 1)
  1316. # Method
  1317. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  1318. methodlabel.setToolTip(
  1319. _("Algorithm for copper clearing:\n"
  1320. "- Standard: Fixed step inwards.\n"
  1321. "- Seed-based: Outwards from seed.\n"
  1322. "- Line-based: Parallel lines.")
  1323. )
  1324. self.ncc_method_combo = FCComboBox()
  1325. self.ncc_method_combo.addItems(
  1326. [_("Standard"), _("Seed"), _("Lines"), _("Combo")]
  1327. )
  1328. self.ncc_method_combo.setObjectName("gdb_n_method")
  1329. self.grid2.addWidget(methodlabel, 17, 0)
  1330. self.grid2.addWidget(self.ncc_method_combo, 17, 1)
  1331. # Connect lines
  1332. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  1333. self.ncc_connect_cb.setObjectName("gdb_n_connect")
  1334. self.ncc_connect_cb.setToolTip(
  1335. _("Draw lines between resulting\n"
  1336. "segments to minimize tool lifts.")
  1337. )
  1338. self.grid2.addWidget(self.ncc_connect_cb, 18, 0)
  1339. # Contour
  1340. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  1341. self.ncc_contour_cb.setObjectName("gdb_n_contour")
  1342. self.ncc_contour_cb.setToolTip(
  1343. _("Cut around the perimeter of the polygon\n"
  1344. "to trim rough edges.")
  1345. )
  1346. self.grid2.addWidget(self.ncc_contour_cb, 18, 1)
  1347. # ## NCC Offset choice
  1348. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  1349. self.ncc_choice_offset_cb.setObjectName("gdb_n_offset")
  1350. self.ncc_choice_offset_cb.setToolTip(
  1351. _("If used, it will add an offset to the copper features.\n"
  1352. "The copper clearing will finish to a distance\n"
  1353. "from the copper features.\n"
  1354. "The value can be between 0 and 10 FlatCAM units.")
  1355. )
  1356. self.grid2.addWidget(self.ncc_choice_offset_cb, 19, 0)
  1357. # ## NCC Offset Entry
  1358. self.ncc_offset_spinner = FCDoubleSpinner()
  1359. self.ncc_offset_spinner.set_range(0.00, 10.00)
  1360. self.ncc_offset_spinner.set_precision(4)
  1361. self.ncc_offset_spinner.setWrapping(True)
  1362. self.ncc_offset_spinner.setObjectName("gdb_n_offset_value")
  1363. units = self.app.defaults['units'].upper()
  1364. if units == 'MM':
  1365. self.ncc_offset_spinner.setSingleStep(0.1)
  1366. else:
  1367. self.ncc_offset_spinner.setSingleStep(0.01)
  1368. self.grid2.addWidget(self.ncc_offset_spinner, 19, 1)
  1369. # ###########################################################################
  1370. # ############### Paint UI form #############################################
  1371. # ###########################################################################
  1372. self.grid3 = QtWidgets.QGridLayout()
  1373. self.paint_vlay.addLayout(self.grid3)
  1374. self.grid3.setColumnStretch(0, 0)
  1375. self.grid3.setColumnStretch(1, 1)
  1376. self.paint_vlay.addStretch()
  1377. # Overlap
  1378. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1379. ovlabel.setToolTip(
  1380. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  1381. "Adjust the value starting with lower values\n"
  1382. "and increasing it if areas that should be painted are still \n"
  1383. "not painted.\n"
  1384. "Lower values = faster processing, faster execution on CNC.\n"
  1385. "Higher values = slow processing and slow execution on CNC\n"
  1386. "due of too many paths.")
  1387. )
  1388. self.paintoverlap_entry = FCDoubleSpinner(suffix='%')
  1389. self.paintoverlap_entry.set_precision(3)
  1390. self.paintoverlap_entry.setWrapping(True)
  1391. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  1392. self.paintoverlap_entry.setSingleStep(0.1)
  1393. self.paintoverlap_entry.setObjectName('gdb_p_overlap')
  1394. self.grid3.addWidget(ovlabel, 1, 0)
  1395. self.grid3.addWidget(self.paintoverlap_entry, 1, 1)
  1396. # Margin
  1397. marginlabel = QtWidgets.QLabel('%s:' % _('Offset'))
  1398. marginlabel.setToolTip(
  1399. _("Distance by which to avoid\n"
  1400. "the edges of the polygon to\n"
  1401. "be painted.")
  1402. )
  1403. self.paint_offset_entry = FCDoubleSpinner()
  1404. self.paint_offset_entry.set_precision(self.decimals)
  1405. self.paint_offset_entry.set_range(-9999.9999, 9999.9999)
  1406. self.paint_offset_entry.setObjectName('gdb_p_offset')
  1407. self.grid3.addWidget(marginlabel, 2, 0)
  1408. self.grid3.addWidget(self.paint_offset_entry, 2, 1)
  1409. # Method
  1410. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  1411. methodlabel.setToolTip(
  1412. _("Algorithm for painting:\n"
  1413. "- Standard: Fixed step inwards.\n"
  1414. "- Seed-based: Outwards from seed.\n"
  1415. "- Line-based: Parallel lines.\n"
  1416. "- Laser-lines: Active only for Gerber objects.\n"
  1417. "Will create lines that follow the traces.\n"
  1418. "- Combo: In case of failure a new method will be picked from the above\n"
  1419. "in the order specified.")
  1420. )
  1421. self.paintmethod_combo = FCComboBox()
  1422. self.paintmethod_combo.addItems(
  1423. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  1424. )
  1425. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  1426. self.paintmethod_combo.model().item(idx).setEnabled(False)
  1427. self.paintmethod_combo.setObjectName('gdb_p_method')
  1428. self.grid3.addWidget(methodlabel, 7, 0)
  1429. self.grid3.addWidget(self.paintmethod_combo, 7, 1)
  1430. # Connect lines
  1431. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  1432. self.pathconnect_cb.setObjectName('gdb_p_connect')
  1433. self.pathconnect_cb.setToolTip(
  1434. _("Draw lines between resulting\n"
  1435. "segments to minimize tool lifts.")
  1436. )
  1437. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  1438. self.paintcontour_cb.setObjectName('gdb_p_contour')
  1439. self.paintcontour_cb.setToolTip(
  1440. _("Cut around the perimeter of the polygon\n"
  1441. "to trim rough edges.")
  1442. )
  1443. self.grid3.addWidget(self.pathconnect_cb, 10, 0)
  1444. self.grid3.addWidget(self.paintcontour_cb, 10, 1)
  1445. # ###########################################################################
  1446. # ############### Isolation UI form #########################################
  1447. # ###########################################################################
  1448. self.grid4 = QtWidgets.QGridLayout()
  1449. self.iso_vlay.addLayout(self.grid4)
  1450. self.grid4.setColumnStretch(0, 0)
  1451. self.grid4.setColumnStretch(1, 1)
  1452. self.iso_vlay.addStretch()
  1453. # Passes
  1454. passlabel = QtWidgets.QLabel('%s:' % _('Passes'))
  1455. passlabel.setToolTip(
  1456. _("Width of the isolation gap in\n"
  1457. "number (integer) of tool widths.")
  1458. )
  1459. self.passes_entry = FCSpinner()
  1460. self.passes_entry.set_range(1, 999)
  1461. self.passes_entry.setObjectName("gdb_i_passes")
  1462. self.grid4.addWidget(passlabel, 0, 0)
  1463. self.grid4.addWidget(self.passes_entry, 0, 1)
  1464. # Overlap Entry
  1465. overlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1466. overlabel.setToolTip(
  1467. _("How much (percentage) of the tool width to overlap each tool pass.")
  1468. )
  1469. self.iso_overlap_entry = FCDoubleSpinner(suffix='%')
  1470. self.iso_overlap_entry.set_precision(self.decimals)
  1471. self.iso_overlap_entry.setWrapping(True)
  1472. self.iso_overlap_entry.set_range(0.0000, 99.9999)
  1473. self.iso_overlap_entry.setSingleStep(0.1)
  1474. self.iso_overlap_entry.setObjectName("gdb_i_overlap")
  1475. self.grid4.addWidget(overlabel, 2, 0)
  1476. self.grid4.addWidget(self.iso_overlap_entry, 2, 1)
  1477. # Milling Type Radio Button
  1478. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  1479. self.milling_type_label.setToolTip(
  1480. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1481. "- climb / best for precision milling and to reduce tool usage\n"
  1482. "- conventional / useful when there is no backlash compensation")
  1483. )
  1484. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  1485. {'label': _('Conventional'), 'value': 'cv'}])
  1486. self.milling_type_radio.setToolTip(
  1487. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1488. "- climb / best for precision milling and to reduce tool usage\n"
  1489. "- conventional / useful when there is no backlash compensation")
  1490. )
  1491. self.milling_type_radio.setObjectName("gdb_i_milling_type")
  1492. self.grid4.addWidget(self.milling_type_label, 4, 0)
  1493. self.grid4.addWidget(self.milling_type_radio, 4, 1)
  1494. # Follow
  1495. self.follow_label = QtWidgets.QLabel('%s:' % _('Follow'))
  1496. self.follow_label.setToolTip(
  1497. _("Generate a 'Follow' geometry.\n"
  1498. "This means that it will cut through\n"
  1499. "the middle of the trace.")
  1500. )
  1501. self.follow_cb = FCCheckBox()
  1502. self.follow_cb.setToolTip(_("Generate a 'Follow' geometry.\n"
  1503. "This means that it will cut through\n"
  1504. "the middle of the trace."))
  1505. self.follow_cb.setObjectName("gdb_i_follow")
  1506. self.grid4.addWidget(self.follow_label, 6, 0)
  1507. self.grid4.addWidget(self.follow_cb, 6, 1)
  1508. # Isolation Type
  1509. self.iso_type_label = QtWidgets.QLabel('%s:' % _('Isolation Type'))
  1510. self.iso_type_label.setToolTip(
  1511. _("Choose how the isolation will be executed:\n"
  1512. "- 'Full' -> complete isolation of polygons\n"
  1513. "- 'Ext' -> will isolate only on the outside\n"
  1514. "- 'Int' -> will isolate only on the inside\n"
  1515. "'Exterior' isolation is almost always possible\n"
  1516. "(with the right tool) but 'Interior'\n"
  1517. "isolation can be done only when there is an opening\n"
  1518. "inside of the polygon (e.g polygon is a 'doughnut' shape).")
  1519. )
  1520. self.iso_type_radio = RadioSet([{'label': _('Full'), 'value': 'full'},
  1521. {'label': _('Ext'), 'value': 'ext'},
  1522. {'label': _('Int'), 'value': 'int'}])
  1523. self.iso_type_radio.setObjectName("gdb_i_iso_type")
  1524. self.grid4.addWidget(self.iso_type_label, 8, 0)
  1525. self.grid4.addWidget(self.iso_type_radio, 8, 1)
  1526. # ###########################################################################
  1527. # ################ DRILLING UI form #########################################
  1528. # ###########################################################################
  1529. self.grid5 = QtWidgets.QGridLayout()
  1530. self.drill_vlay.addLayout(self.grid5)
  1531. self.grid5.setColumnStretch(0, 0)
  1532. self.grid5.setColumnStretch(1, 1)
  1533. self.drill_vlay.addStretch()
  1534. # Cut Z
  1535. self.cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1536. self.cutzlabel.setToolTip(
  1537. _("Drill depth (negative)\n"
  1538. "below the copper surface.")
  1539. )
  1540. self.cutz_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1541. self.cutz_drill_entry.set_precision(self.decimals)
  1542. if self.machinist_setting == 0:
  1543. self.cutz_drill_entry.set_range(-9999.9999, 0.0000)
  1544. else:
  1545. self.cutz_drill_entry.set_range(-9999.9999, 9999.9999)
  1546. self.cutz_drill_entry.setSingleStep(0.1)
  1547. self.cutz_drill_entry.setObjectName("gdb_e_cutz")
  1548. self.grid5.addWidget(self.cutzlabel, 4, 0)
  1549. self.grid5.addWidget(self.cutz_drill_entry, 4, 1)
  1550. # Tool Offset
  1551. self.tool_offset_label = QtWidgets.QLabel('%s:' % _('Offset Z'))
  1552. self.tool_offset_label.setToolTip(
  1553. _("Some drill bits (the larger ones) need to drill deeper\n"
  1554. "to create the desired exit hole diameter due of the tip shape.\n"
  1555. "The value here can compensate the Cut Z parameter.")
  1556. )
  1557. self.offset_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1558. self.offset_drill_entry.set_precision(self.decimals)
  1559. self.offset_drill_entry.set_range(-9999.9999, 9999.9999)
  1560. self.offset_drill_entry.setObjectName("gdb_e_offset")
  1561. self.grid5.addWidget(self.tool_offset_label, 6, 0)
  1562. self.grid5.addWidget(self.offset_drill_entry, 6, 1)
  1563. # Multi-Depth
  1564. self.multidepth_drill_label = QtWidgets.QLabel('%s:' % _("MultiDepth"))
  1565. self.multidepth_drill_label.setToolTip(
  1566. _(
  1567. "Use multiple passes to limit\n"
  1568. "the cut depth in each pass. Will\n"
  1569. "cut multiple times until Cut Z is\n"
  1570. "reached."
  1571. )
  1572. )
  1573. self.mpass_drill_cb = FCCheckBox()
  1574. self.mpass_drill_cb.setObjectName("gdb_e_multidepth")
  1575. self.grid5.addWidget(self.multidepth_drill_label, 7, 0)
  1576. self.grid5.addWidget(self.mpass_drill_cb, 7, 1)
  1577. # Depth Per Pass
  1578. self.dpp_drill_label = QtWidgets.QLabel('%s:' % _("DPP"))
  1579. self.dpp_drill_label.setToolTip(
  1580. _("DPP. Depth per Pass.\n"
  1581. "The value used to cut into material on each pass."))
  1582. self.maxdepth_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1583. self.maxdepth_drill_entry.set_precision(self.decimals)
  1584. self.maxdepth_drill_entry.set_range(0, 9999.9999)
  1585. self.maxdepth_drill_entry.setSingleStep(0.1)
  1586. self.maxdepth_drill_entry.setToolTip(_("Depth of each pass (positive)."))
  1587. self.maxdepth_drill_entry.setObjectName("gdb_e_depthperpass")
  1588. self.grid5.addWidget(self.dpp_drill_label, 8, 0)
  1589. self.grid5.addWidget(self.maxdepth_drill_entry, 8, 1)
  1590. # Travel Z (z_move)
  1591. self.travelzlabel = QtWidgets.QLabel('%s:' % _('Travel Z'))
  1592. self.travelzlabel.setToolTip(
  1593. _("Tool height when travelling\n"
  1594. "across the XY plane.")
  1595. )
  1596. self.travelz_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1597. self.travelz_drill_entry.set_precision(self.decimals)
  1598. if self.machinist_setting == 0:
  1599. self.travelz_drill_entry.set_range(0.00001, 9999.9999)
  1600. else:
  1601. self.travelz_drill_entry.set_range(-9999.9999, 9999.9999)
  1602. self.travelz_drill_entry.setSingleStep(0.1)
  1603. self.travelz_drill_entry.setObjectName("gdb_e_travelz")
  1604. self.grid5.addWidget(self.travelzlabel, 10, 0)
  1605. self.grid5.addWidget(self.travelz_drill_entry, 10, 1)
  1606. separator_line = QtWidgets.QFrame()
  1607. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1608. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1609. self.grid5.addWidget(separator_line, 12, 0, 1, 2)
  1610. # Excellon Feedrate Z
  1611. self.frzlabel = QtWidgets.QLabel('%s:' % _('Feedrate Z'))
  1612. self.frzlabel.setToolTip(
  1613. _("Tool speed while drilling\n"
  1614. "(in units per minute).\n"
  1615. "So called 'Plunge' feedrate.\n"
  1616. "This is for linear move G01.")
  1617. )
  1618. self.feedrate_z_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1619. self.feedrate_z_drill_entry.set_precision(self.decimals)
  1620. self.feedrate_z_drill_entry.set_range(0.0, 99999.9999)
  1621. self.feedrate_z_drill_entry.setSingleStep(0.1)
  1622. self.feedrate_z_drill_entry.setObjectName("gdb_e_feedratez")
  1623. self.grid5.addWidget(self.frzlabel, 14, 0)
  1624. self.grid5.addWidget(self.feedrate_z_drill_entry, 14, 1)
  1625. # Excellon Rapid Feedrate
  1626. self.feedrate_rapid_label = QtWidgets.QLabel('%s:' % _('Feedrate Rapids'))
  1627. self.feedrate_rapid_label.setToolTip(
  1628. _("Tool speed while drilling\n"
  1629. "(in units per minute).\n"
  1630. "This is for the rapid move G00.\n"
  1631. "It is useful only for Marlin,\n"
  1632. "ignore for any other cases.")
  1633. )
  1634. self.feedrate_rapid_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1635. self.feedrate_rapid_drill_entry.set_precision(self.decimals)
  1636. self.feedrate_rapid_drill_entry.set_range(0.0, 99999.9999)
  1637. self.feedrate_rapid_drill_entry.setSingleStep(0.1)
  1638. self.feedrate_rapid_drill_entry.setObjectName("gdb_e_fr_rapid")
  1639. self.grid5.addWidget(self.feedrate_rapid_label, 16, 0)
  1640. self.grid5.addWidget(self.feedrate_rapid_drill_entry, 16, 1)
  1641. separator_line = QtWidgets.QFrame()
  1642. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1643. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1644. self.grid5.addWidget(separator_line, 18, 0, 1, 2)
  1645. # Spindlespeed
  1646. self.spindle_label = QtWidgets.QLabel('%s:' % _('Spindle speed'))
  1647. self.spindle_label.setToolTip(
  1648. _("Speed of the spindle\n"
  1649. "in RPM (optional)")
  1650. )
  1651. self.spindlespeed_drill_entry = FCSpinner(callback=self.confirmation_message_int)
  1652. self.spindlespeed_drill_entry.set_range(0, 1000000)
  1653. self.spindlespeed_drill_entry.set_step(100)
  1654. self.spindlespeed_drill_entry.setObjectName("gdb_e_spindlespeed")
  1655. self.grid5.addWidget(self.spindle_label, 20, 0)
  1656. self.grid5.addWidget(self.spindlespeed_drill_entry, 20, 1)
  1657. # Dwell
  1658. self.dwell_drill_label = QtWidgets.QLabel('%s:' % _("Dwell"))
  1659. self.dwell_drill_label.setToolTip(
  1660. _("Dwell.\n"
  1661. "Check this if a delay is needed to allow\n"
  1662. "the spindle motor to reach its set speed."))
  1663. self.dwell_drill_cb = FCCheckBox()
  1664. self.dwell_drill_cb.setObjectName("gdb_e_dwell")
  1665. self.grid5.addWidget(self.dwell_drill_label, 21, 0)
  1666. self.grid5.addWidget(self.dwell_drill_cb, 21, 1)
  1667. # Dwelltime
  1668. self.dwelltime_drill_lbl = QtWidgets.QLabel('%s:' % _('Dwelltime'))
  1669. self.dwelltime_drill_lbl.setToolTip(
  1670. _("Dwell Time.\n"
  1671. "A delay used to allow the motor spindle reach its set speed."))
  1672. self.dwelltime_drill_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1673. self.dwelltime_drill_entry.set_precision(self.decimals)
  1674. self.dwelltime_drill_entry.set_range(0.0, 9999.9999)
  1675. self.dwelltime_drill_entry.setSingleStep(0.1)
  1676. self.dwelltime_drill_entry.setObjectName("gdb_e_dwelltime")
  1677. self.grid5.addWidget(self.dwelltime_drill_lbl, 22, 0)
  1678. self.grid5.addWidget(self.dwelltime_drill_entry, 22, 1)
  1679. separator_line = QtWidgets.QFrame()
  1680. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1681. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1682. self.grid5.addWidget(separator_line, 24, 0, 1, 2)
  1683. # Drill slots
  1684. self.drill_slots_drill_lbl = QtWidgets.QLabel('%s:' % _('Drill slots'))
  1685. self.drill_slots_drill_lbl.setToolTip(
  1686. _("If the selected tool has slots then they will be drilled.")
  1687. )
  1688. self.drill_slots_drill_cb = FCCheckBox()
  1689. self.drill_slots_drill_cb.setObjectName("gdb_e_drill_slots")
  1690. self.grid5.addWidget(self.drill_slots_drill_lbl, 26, 0,)
  1691. self.grid5.addWidget(self.drill_slots_drill_cb, 26, 1)
  1692. # Drill Overlap
  1693. self.drill_overlap_label = QtWidgets.QLabel('%s:' % _('Overlap'))
  1694. self.drill_overlap_label.setToolTip(
  1695. _("How much (percentage) of the tool diameter to overlap previous drill hole.")
  1696. )
  1697. self.drill_overlap_drill_entry = FCDoubleSpinner(suffix='%', callback=self.confirmation_message)
  1698. self.drill_overlap_drill_entry.set_precision(self.decimals)
  1699. self.drill_overlap_drill_entry.set_range(0.0, 100.0000)
  1700. self.drill_overlap_drill_entry.setSingleStep(0.1)
  1701. self.drill_overlap_drill_entry.setObjectName("gdb_e_drill_slots_over")
  1702. self.grid5.addWidget(self.drill_overlap_label, 28, 0)
  1703. self.grid5.addWidget(self.drill_overlap_drill_entry, 28, 1)
  1704. # Last drill in slot
  1705. self.last_drill_drill_lbl = QtWidgets.QLabel('%s:' % _('Last drill'))
  1706. self.last_drill_drill_lbl.setToolTip(
  1707. _("If the slot length is not completely covered by drill holes,\n"
  1708. "add a drill hole on the slot end point.")
  1709. )
  1710. self.last_drill_drill_cb = FCCheckBox()
  1711. self.last_drill_drill_cb.setObjectName("gdb_e_drill_last_drill")
  1712. self.grid5.addWidget(self.last_drill_drill_lbl, 30, 0, 1, 2)
  1713. self.grid5.addWidget(self.last_drill_drill_cb, 30, 1)
  1714. # ####################################################################
  1715. # ####################################################################
  1716. # GUI for the lower part of the window
  1717. # ####################################################################
  1718. # ####################################################################
  1719. new_vlay = QtWidgets.QVBoxLayout()
  1720. self.g_lay.addLayout(new_vlay, 1, 0, 1, 2)
  1721. self.buttons_frame = QtWidgets.QFrame()
  1722. self.buttons_frame.setContentsMargins(0, 0, 0, 0)
  1723. new_vlay.addWidget(self.buttons_frame)
  1724. self.buttons_box = QtWidgets.QHBoxLayout()
  1725. self.buttons_box.setContentsMargins(0, 0, 0, 0)
  1726. self.buttons_frame.setLayout(self.buttons_box)
  1727. self.buttons_frame.show()
  1728. self.add_entry_btn = FCButton(_("Add Tool in DB"))
  1729. self.add_entry_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  1730. self.add_entry_btn.setToolTip(
  1731. _("Add a new tool in the Tools Database.\n"
  1732. "It will be used in the Geometry UI.\n"
  1733. "You can edit it after it is added.")
  1734. )
  1735. self.buttons_box.addWidget(self.add_entry_btn)
  1736. # add_fct_entry_btn = FCButton(_("Add Paint/NCC Tool in DB"))
  1737. # add_fct_entry_btn.setToolTip(
  1738. # _("Add a new tool in the Tools Database.\n"
  1739. # "It will be used in the Paint/NCC Tools UI.\n"
  1740. # "You can edit it after it is added.")
  1741. # )
  1742. # self.buttons_box.addWidget(add_fct_entry_btn)
  1743. self.remove_entry_btn = FCButton(_("Delete Tool from DB"))
  1744. self.remove_entry_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/trash16.png'))
  1745. self.remove_entry_btn.setToolTip(
  1746. _("Remove a selection of tools in the Tools Database.")
  1747. )
  1748. self.buttons_box.addWidget(self.remove_entry_btn)
  1749. self.export_db_btn = FCButton(_("Export DB"))
  1750. self.export_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/export.png'))
  1751. self.export_db_btn.setToolTip(
  1752. _("Save the Tools Database to a custom text file.")
  1753. )
  1754. self.buttons_box.addWidget(self.export_db_btn)
  1755. self.import_db_btn = FCButton(_("Import DB"))
  1756. self.import_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/import.png'))
  1757. self.import_db_btn.setToolTip(
  1758. _("Load the Tools Database information's from a custom text file.")
  1759. )
  1760. self.buttons_box.addWidget(self.import_db_btn)
  1761. self.save_db_btn = FCButton(_("Save DB"))
  1762. self.save_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  1763. self.save_db_btn.setToolTip(
  1764. _("Save the Tools Database information's.")
  1765. )
  1766. self.buttons_box.addWidget(self.save_db_btn)
  1767. self.add_tool_from_db = FCButton(_("Transfer the Tool"))
  1768. self.add_tool_from_db.setToolTip(
  1769. _("Insert a new tool in the Tools Table of the\n"
  1770. "object/application tool after selecting a tool\n"
  1771. "in the Tools Database.")
  1772. )
  1773. self.add_tool_from_db.setStyleSheet("""
  1774. QPushButton
  1775. {
  1776. font-weight: bold;
  1777. color: green;
  1778. }
  1779. """)
  1780. self.add_tool_from_db.hide()
  1781. self.cancel_tool_from_db = FCButton(_("Cancel"))
  1782. self.cancel_tool_from_db.hide()
  1783. hlay = QtWidgets.QHBoxLayout()
  1784. tree_layout.addLayout(hlay)
  1785. hlay.addWidget(self.add_tool_from_db)
  1786. hlay.addWidget(self.cancel_tool_from_db)
  1787. # hlay.addStretch()
  1788. # ############################ FINSIHED GUI ###################################
  1789. # #############################################################################
  1790. def confirmation_message(self, accepted, minval, maxval):
  1791. if accepted is False:
  1792. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1793. self.decimals,
  1794. minval,
  1795. self.decimals,
  1796. maxval), False)
  1797. else:
  1798. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1799. def confirmation_message_int(self, accepted, minval, maxval):
  1800. if accepted is False:
  1801. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1802. (_("Edited value is out of range"), minval, maxval), False)
  1803. else:
  1804. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1805. class ToolsDB2(QtWidgets.QWidget):
  1806. mark_tools_rows = QtCore.pyqtSignal()
  1807. def __init__(self, app, callback_on_edited, callback_on_tool_request, parent=None):
  1808. super(ToolsDB2, self).__init__(parent)
  1809. self.app = app
  1810. self.app_ui = self.app.ui
  1811. self.decimals = self.app.decimals
  1812. self.callback_app = callback_on_edited
  1813. self.on_tool_request = callback_on_tool_request
  1814. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  1815. self.type_item_options = ["Iso", "Rough", "Finish"]
  1816. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  1817. '''
  1818. dict to hold all the tools in the Tools DB
  1819. format:
  1820. {
  1821. tool_id: {
  1822. 'name': 'new_tool'
  1823. 'tooldia': self.app.defaults["geometry_cnctooldia"]
  1824. 'offset': 'Path'
  1825. 'offset_value': 0.0
  1826. 'type': _('Rough'),
  1827. 'tool_type': 'C1'
  1828. 'data': dict()
  1829. }
  1830. }
  1831. '''
  1832. self.db_tool_dict = {}
  1833. # ##############################################################################
  1834. # ##############################################################################
  1835. # TOOLS DATABASE UI
  1836. # ##############################################################################
  1837. # ##############################################################################
  1838. layout = QtWidgets.QGridLayout()
  1839. layout.setColumnStretch(0, 0)
  1840. layout.setColumnStretch(1, 1)
  1841. self.setLayout(layout)
  1842. self.ui = ToolsDB2UI(app=self.app, grid_layout=layout)
  1843. # ##############################################################################
  1844. # ##############################################################################
  1845. # ########## SETUP THE DICTIONARIES THAT HOLD THE WIDGETS #####################
  1846. # ##############################################################################
  1847. # ##############################################################################
  1848. self.form_fields = {
  1849. "tool_target": self.ui.tool_op_combo,
  1850. "tol_min": self.ui.tol_min_entry,
  1851. "tol_max": self.ui.tol_max_entry,
  1852. "name": self.ui.name_entry,
  1853. "tooldia": self.ui.dia_entry,
  1854. # Milling
  1855. "tool_type": self.ui.shape_combo,
  1856. "cutz": self.ui.cutz_entry,
  1857. "multidepth": self.ui.multidepth_cb,
  1858. "depthperpass": self.ui.multidepth_entry,
  1859. "travelz": self.ui.travelz_entry,
  1860. "feedrate": self.ui.frxy_entry,
  1861. "feedrate_z": self.ui.frz_entry,
  1862. "spindlespeed": self.ui.spindle_entry,
  1863. "dwell": self.ui.dwell_cb,
  1864. "dwelltime": self.ui.dwelltime_entry,
  1865. "type": self.ui.type_combo,
  1866. "offset": self.ui.tooloffset_combo,
  1867. "offset_value": self.ui.custom_offset_entry,
  1868. "vtipdia": self.ui.vdia_entry,
  1869. "vtipangle": self.ui.vangle_entry,
  1870. "feedrate_rapid": self.ui.frapids_entry,
  1871. "extracut": self.ui.ecut_cb,
  1872. "extracut_length": self.ui.ecut_length_entry,
  1873. # NCC
  1874. "tools_nccoperation": self.ui.op_radio,
  1875. "tools_nccmilling_type": self.ui.milling_type_radio,
  1876. "tools_nccoverlap": self.ui.ncc_overlap_entry,
  1877. "tools_nccmargin": self.ui.ncc_margin_entry,
  1878. "tools_nccmethod": self.ui.ncc_method_combo,
  1879. "tools_nccconnect": self.ui.ncc_connect_cb,
  1880. "tools_ncccontour": self.ui.ncc_contour_cb,
  1881. "tools_ncc_offset_choice": self.ui.ncc_choice_offset_cb,
  1882. "tools_ncc_offset_value": self.ui.ncc_offset_spinner,
  1883. # Paint
  1884. "tools_paintoverlap": self.ui.paintoverlap_entry,
  1885. "tools_paintoffset": self.ui.paint_offset_entry,
  1886. "tools_paintmethod": self.ui.paintmethod_combo,
  1887. "tools_pathconnect": self.ui.pathconnect_cb,
  1888. "tools_paintcontour": self.ui.paintcontour_cb,
  1889. # Isolation
  1890. "tools_iso_passes": self.ui.passes_entry,
  1891. "tools_iso_overlap": self.ui.iso_overlap_entry,
  1892. "tools_iso_milling_type": self.ui.milling_type_radio,
  1893. "tools_iso_follow": self.ui.follow_cb,
  1894. "tools_iso_isotype": self.ui.iso_type_radio,
  1895. # Drilling
  1896. "tools_drill_cutz": self.ui.cutz_drill_entry,
  1897. "tools_drill_multidepth": self.ui.mpass_drill_cb,
  1898. "tools_drill_depthperpass": self.ui.maxdepth_drill_entry,
  1899. "tools_drill_travelz": self.ui.travelz_drill_entry,
  1900. "tools_drill_feedrate_z": self.ui.feedrate_z_drill_entry,
  1901. "tools_drill_feedrate_rapid": self.ui.feedrate_rapid_drill_entry,
  1902. "tools_drill_spindlespeed": self.ui.spindlespeed_drill_entry,
  1903. "tools_drill_dwell": self.ui.dwell_drill_cb,
  1904. "tools_drill_dwelltime": self.ui.dwelltime_drill_entry,
  1905. "tools_drill_offset": self.ui.offset_drill_entry,
  1906. "tools_drill_drill_slots": self.ui.drill_slots_drill_cb,
  1907. "tools_drill_drill_overlap": self.ui.drill_overlap_drill_entry,
  1908. "tools_drill_last_drill": self.ui.last_drill_drill_cb,
  1909. }
  1910. self.name2option = {
  1911. "gdb_tool_target": "tool_target",
  1912. "gdb_tol_min": "tol_min",
  1913. "gdb_tol_max": "tol_max",
  1914. "gdb_name": "name",
  1915. "gdb_dia": "tooldia",
  1916. # Milling
  1917. "gdb_shape": "tool_type",
  1918. "gdb_cutz": "cutz",
  1919. "gdb_multidepth": "multidepth",
  1920. "gdb_multidepth_entry": "depthperpass",
  1921. "gdb_travelz": "travelz",
  1922. "gdb_frxy": "feedrate",
  1923. "gdb_frz": "feedrate_z",
  1924. "gdb_spindle": "spindlespeed",
  1925. "gdb_dwell": "dwell",
  1926. "gdb_dwelltime": "dwelltime",
  1927. "gdb_type": "type",
  1928. "gdb_tool_offset": "offset",
  1929. "gdb_custom_offset": "offset_value",
  1930. "gdb_vdia": "vtipdia",
  1931. "gdb_vangle": "vtipangle",
  1932. "gdb_frapids": "feedrate_rapid",
  1933. "gdb_ecut": "extracut",
  1934. "gdb_ecut_length": "extracut_length",
  1935. # NCC
  1936. "gdb_n_operation": "tools_nccoperation",
  1937. "gdb_n_overlap": "tools_nccoverlap",
  1938. "gdb_n_margin": "tools_nccmargin",
  1939. "gdb_n_method": "tools_nccmethod",
  1940. "gdb_n_connect": "tools_nccconnect",
  1941. "gdb_n_contour": "tools_ncccontour",
  1942. "gdb_n_offset": "tools_ncc_offset_choice",
  1943. "gdb_n_offset_value": "tools_ncc_offset_value",
  1944. "gdb_n_milling_type": "tools_nccmilling_type",
  1945. # Paint
  1946. 'gdb_p_overlap': "tools_paintoverlap",
  1947. 'gdb_p_offset': "tools_paintoffset",
  1948. 'gdb_p_method': "tools_paintmethod",
  1949. 'gdb_p_connect': "tools_pathconnect",
  1950. 'gdb_p_contour': "tools_paintcontour",
  1951. # Isolation
  1952. "gdb_i_passes": "tools_iso_passes",
  1953. "gdb_i_overlap": "tools_iso_overlap",
  1954. "gdb_i_milling_type": "tools_iso_milling_type",
  1955. "gdb_i_follow": "tools_iso_follow",
  1956. "gdb_i_iso_type": "tools_iso_isotype",
  1957. # Drilling
  1958. "gdb_e_cutz": "tools_drill_cutz",
  1959. "gdb_e_multidepth": "tools_drill_multidepth",
  1960. "gdb_e_depthperpass": "tools_drill_depthperpass",
  1961. "gdb_e_travelz": "tools_drill_travelz",
  1962. "gdb_e_feedratez": "tools_drill_feedrate_z",
  1963. "gdb_e_fr_rapid": "tools_drill_feedrate_rapid",
  1964. "gdb_e_spindlespeed": "tools_drill_spindlespeed",
  1965. "gdb_e_dwell": "tools_drill_dwell",
  1966. "gdb_e_dwelltime": "tools_drill_dwelltime",
  1967. "gdb_e_offset": "tools_drill_offset",
  1968. "gdb_e_drill_slots": "tools_drill_drill_slots",
  1969. "gdb_e_drill_slots_over": "tools_drill_drill_overlap",
  1970. "gdb_e_drill_last_drill": "tools_drill_last_drill",
  1971. }
  1972. self.current_toolid = None
  1973. # variable to show if double clicking and item will trigger adding a tool from DB
  1974. self.ok_to_add = False
  1975. # ##############################################################################
  1976. # ######################## SIGNALS #############################################
  1977. # ##############################################################################
  1978. self.ui.add_entry_btn.clicked.connect(self.on_tool_add)
  1979. self.ui.remove_entry_btn.clicked.connect(self.on_tool_delete)
  1980. self.ui.export_db_btn.clicked.connect(self.on_export_tools_db_file)
  1981. self.ui.import_db_btn.clicked.connect(self.on_import_tools_db_file)
  1982. self.ui.save_db_btn.clicked.connect(self.on_save_db_btn_click)
  1983. # closebtn.clicked.connect(self.accept)
  1984. self.ui.add_tool_from_db.clicked.connect(self.on_tool_requested_from_app)
  1985. self.ui.cancel_tool_from_db.clicked.connect(self.on_cancel_tool)
  1986. # self.ui.tree_widget.selectionModel().selectionChanged.connect(self.on_list_selection_change)
  1987. self.ui.tree_widget.currentItemChanged.connect(self.on_list_selection_change)
  1988. self.ui.tree_widget.itemChanged.connect(self.on_list_item_edited)
  1989. self.ui.tree_widget.customContextMenuRequested.connect(self.on_menu_request)
  1990. self.ui.tree_widget.itemDoubleClicked.connect(self.on_item_double_clicked)
  1991. self.ui.tool_op_combo.currentIndexChanged.connect(self.on_tool_target_changed)
  1992. self.setup_db_ui()
  1993. def on_menu_request(self, pos):
  1994. menu = QtWidgets.QMenu()
  1995. add_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/plus16.png'), _("Add to DB"))
  1996. add_tool.triggered.connect(self.on_tool_add)
  1997. copy_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/copy16.png'), _("Copy from DB"))
  1998. copy_tool.triggered.connect(self.on_tool_copy)
  1999. delete_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/delete32.png'), _("Delete from DB"))
  2000. delete_tool.triggered.connect(self.on_tool_delete)
  2001. # sep = menu.addSeparator()
  2002. save_changes = menu.addAction(QtGui.QIcon(self.app.resource_location + '/save_as.png'), _("Save changes"))
  2003. save_changes.triggered.connect(self.on_save_changes)
  2004. # tree_item = self.ui.tree_widget.itemAt(pos)
  2005. menu.exec(self.ui.tree_widget.viewport().mapToGlobal(pos))
  2006. def on_save_changes(self):
  2007. widget_name = self.app_ui.plot_tab_area.currentWidget().objectName()
  2008. if widget_name == 'database_tab':
  2009. # Tools DB saved, update flag
  2010. self.app.tools_db_changed_flag = False
  2011. self.app.tools_db_tab.on_save_tools_db()
  2012. def on_item_double_clicked(self, item, column):
  2013. if column == 0 and self.ok_to_add is True:
  2014. self.ok_to_add = False
  2015. self.on_tool_requested_from_app()
  2016. def on_list_selection_change(self, current, previous):
  2017. self.ui_disconnect()
  2018. self.current_toolid = int(current.text(0))
  2019. self.storage_to_form(self.db_tool_dict[current.text(0)])
  2020. self.ui_connect()
  2021. def on_list_item_edited(self, item, column):
  2022. if column == 0:
  2023. return
  2024. self.ui.name_entry.set_value(item.text(1))
  2025. def storage_to_form(self, dict_storage):
  2026. self.ui_disconnect()
  2027. for form_key in self.form_fields:
  2028. for storage_key in dict_storage:
  2029. if form_key == storage_key:
  2030. try:
  2031. self.form_fields[form_key].set_value(dict_storage[form_key])
  2032. except Exception as e:
  2033. print(str(e))
  2034. if storage_key == 'data':
  2035. for data_key in dict_storage[storage_key]:
  2036. if form_key == data_key:
  2037. try:
  2038. self.form_fields[form_key].set_value(dict_storage['data'][data_key])
  2039. except Exception as e:
  2040. print(str(e))
  2041. self.ui_connect()
  2042. def form_to_storage(self, tool):
  2043. self.ui_disconnect()
  2044. widget_changed = self.sender()
  2045. wdg_objname = widget_changed.objectName()
  2046. option_changed = self.name2option[wdg_objname]
  2047. tooluid_item = int(tool)
  2048. for tooluid_key, tooluid_val in self.db_tool_dict.items():
  2049. if int(tooluid_key) == tooluid_item:
  2050. new_option_value = self.form_fields[option_changed].get_value()
  2051. if option_changed in tooluid_val:
  2052. tooluid_val[option_changed] = new_option_value
  2053. if option_changed in tooluid_val['data']:
  2054. tooluid_val['data'][option_changed] = new_option_value
  2055. self.ui_connect()
  2056. def setup_db_ui(self):
  2057. filename = self.app.data_path + '\\geo_tools_db.FlatDB'
  2058. # load the database tools from the file
  2059. try:
  2060. with open(filename) as f:
  2061. tools = f.read()
  2062. except IOError:
  2063. self.app.log.error("Could not load tools DB file.")
  2064. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  2065. return
  2066. try:
  2067. self.db_tool_dict = json.loads(tools)
  2068. except Exception:
  2069. e = sys.exc_info()[0]
  2070. self.app.log.error(str(e))
  2071. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  2072. return
  2073. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  2074. self.build_db_ui()
  2075. def build_db_ui(self):
  2076. self.ui_disconnect()
  2077. nr_crt = 0
  2078. parent = self.ui.tree_widget
  2079. self.ui.tree_widget.blockSignals(True)
  2080. self.ui.tree_widget.clear()
  2081. self.ui.tree_widget.blockSignals(False)
  2082. for toolid, dict_val in self.db_tool_dict.items():
  2083. row = nr_crt
  2084. nr_crt += 1
  2085. t_name = dict_val['name']
  2086. try:
  2087. # self.add_tool_table_line(row, name=t_name, tooldict=dict_val)
  2088. self.ui.tree_widget.blockSignals(True)
  2089. try:
  2090. self.ui.tree_widget.addParentEditable(parent=parent, title=[str(row+1), t_name], editable=True)
  2091. except Exception as e:
  2092. print('FlatCAMCoomn.ToolDB2.build_db_ui() -> ', str(e))
  2093. self.ui.tree_widget.blockSignals(False)
  2094. except Exception as e:
  2095. self.app.log.debug("ToolDB.build_db_ui.add_tool_table_line() --> %s" % str(e))
  2096. if self.current_toolid is None or self.current_toolid < 1:
  2097. if self.db_tool_dict:
  2098. self.storage_to_form(self.db_tool_dict['1'])
  2099. # Enable appGUI
  2100. try:
  2101. self.on_tool_target_changed(val=self.db_tool_dict['1']['data']['tool_target'])
  2102. except KeyError:
  2103. self.on_tool_target_changed(val=_("General"))
  2104. self.ui.tree_widget.setCurrentItem(self.ui.tree_widget.topLevelItem(0))
  2105. # self.ui.tree_widget.setFocus()
  2106. else:
  2107. # Disable appGUI
  2108. self.ui.tool_description_box.show()
  2109. self.ui.milling_box.show()
  2110. self.ui.ncc_box.show()
  2111. self.ui.paint_box.show()
  2112. self.ui.iso_box.show()
  2113. self.ui.drill_box.show()
  2114. self.ui.tool_description_box.setEnabled(False)
  2115. self.ui.milling_box.setEnabled(False)
  2116. self.ui.ncc_box.setEnabled(False)
  2117. self.ui.paint_box.setEnabled(False)
  2118. self.ui.iso_box.setEnabled(False)
  2119. self.ui.drill_box.setEnabled(False)
  2120. else:
  2121. self.storage_to_form(self.db_tool_dict[str(self.current_toolid)])
  2122. self.ui_connect()
  2123. def on_tool_target_changed(self, index=None, val=None):
  2124. if val is None:
  2125. tool_target = self.ui.tool_op_combo.get_value()
  2126. else:
  2127. tool_target = val
  2128. self.ui.tool_description_box.setEnabled(True)
  2129. if self.db_tool_dict:
  2130. if tool_target == _("General"):
  2131. self.ui.milling_box.setEnabled(True)
  2132. self.ui.ncc_box.setEnabled(True)
  2133. self.ui.paint_box.setEnabled(True)
  2134. self.ui.iso_box.setEnabled(True)
  2135. self.ui.drill_box.setEnabled(True)
  2136. self.ui.milling_box.show()
  2137. self.ui.ncc_box.show()
  2138. self.ui.paint_box.show()
  2139. self.ui.iso_box.show()
  2140. self.ui.drill_box.show()
  2141. else:
  2142. self.ui.ncc_box.hide()
  2143. self.ui.paint_box.hide()
  2144. self.ui.iso_box.hide()
  2145. self.ui.drill_box.hide()
  2146. if tool_target == _("Milling"):
  2147. self.ui.milling_box.setEnabled(True)
  2148. self.ui.milling_box.show()
  2149. if tool_target == _("Drilling"):
  2150. self.ui.drill_box.setEnabled(True)
  2151. self.ui.drill_box.show()
  2152. if tool_target == _("Isolation"):
  2153. self.ui.iso_box.setEnabled(True)
  2154. self.ui.iso_box.show()
  2155. if tool_target == _("Paint"):
  2156. self.ui.paint_box.setEnabled(True)
  2157. self.ui.paint_box.show()
  2158. if tool_target == _("NCC"):
  2159. self.ui.ncc_box.setEnabled(True)
  2160. self.ui.ncc_box.show()
  2161. def on_tool_add(self):
  2162. """
  2163. Add a tool in the DB Tool Table
  2164. :return: None
  2165. """
  2166. default_data = {}
  2167. default_data.update({
  2168. "plot": True,
  2169. "tool_target": _("General"),
  2170. "tol_min": 0.0,
  2171. "tol_max": 0.0,
  2172. # Milling
  2173. "cutz": float(self.app.defaults["geometry_cutz"]),
  2174. "multidepth": self.app.defaults["geometry_multidepth"],
  2175. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  2176. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  2177. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  2178. "travelz": float(self.app.defaults["geometry_travelz"]),
  2179. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  2180. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  2181. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  2182. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  2183. "dwell": self.app.defaults["geometry_dwell"],
  2184. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  2185. "ppname_g": self.app.defaults["geometry_ppname_g"],
  2186. "extracut": self.app.defaults["geometry_extracut"],
  2187. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  2188. "toolchange": self.app.defaults["geometry_toolchange"],
  2189. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  2190. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  2191. "startz": self.app.defaults["geometry_startz"],
  2192. "endz": float(self.app.defaults["geometry_endz"]),
  2193. # NCC
  2194. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  2195. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  2196. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  2197. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  2198. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  2199. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  2200. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  2201. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  2202. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  2203. # Paint
  2204. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  2205. "tools_paintoffset": float(self.app.defaults["tools_paintoffset"]),
  2206. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  2207. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  2208. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  2209. # Isolation
  2210. "tools_iso_passes": int(self.app.defaults["tools_iso_passes"]),
  2211. "tools_iso_overlap": float(self.app.defaults["tools_iso_overlap"]),
  2212. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  2213. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  2214. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  2215. # Drilling
  2216. "tools_drill_cutz": float(self.app.defaults["tools_drill_cutz"]),
  2217. "tools_drill_multidepth": self.app.defaults["tools_drill_multidepth"],
  2218. "tools_drill_depthperpass": float(self.app.defaults["tools_drill_depthperpass"]),
  2219. "tools_drill_travelz": float(self.app.defaults["tools_drill_travelz"]),
  2220. "tools_drill_feedrate_z": float(self.app.defaults["tools_drill_feedrate_z"]),
  2221. "tools_drill_feedrate_rapid": float(self.app.defaults["tools_drill_feedrate_rapid"]),
  2222. "tools_drill_spindlespeed": float(self.app.defaults["tools_drill_spindlespeed"]),
  2223. "tools_drill_dwell": self.app.defaults["tools_drill_dwell"],
  2224. "tools_drill_offset": float(self.app.defaults["tools_drill_offset"]),
  2225. "tools_drill_drill_slots": self.app.defaults["tools_drill_drill_slots"],
  2226. "tools_drill_drill_overlap": float(self.app.defaults["tools_drill_drill_overlap"]),
  2227. "tools_drill_last_drill": self.app.defaults["tools_drill_last_drill"],
  2228. })
  2229. temp = []
  2230. for k, v in self.db_tool_dict.items():
  2231. if "new_tool_" in v['name']:
  2232. temp.append(float(v['name'].rpartition('_')[2]))
  2233. if temp:
  2234. new_name = "new_tool_%d" % int(max(temp) + 1)
  2235. else:
  2236. new_name = "new_tool_1"
  2237. dict_elem = {}
  2238. dict_elem['name'] = new_name
  2239. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  2240. dict_elem['tooldia'] = self.app.defaults["geometry_cnctooldia"]
  2241. else:
  2242. try:
  2243. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  2244. tools_diameters = [eval(a) for a in tools_string if a != '']
  2245. dict_elem['tooldia'] = tools_diameters[0] if tools_diameters else 0.0
  2246. except Exception as e:
  2247. self.app.log.debug("ToolDB.on_tool_add() --> %s" % str(e))
  2248. return
  2249. dict_elem['offset'] = 'Path'
  2250. dict_elem['offset_value'] = 0.0
  2251. dict_elem['type'] = 'Rough'
  2252. dict_elem['tool_type'] = 'C1'
  2253. dict_elem['data'] = default_data
  2254. new_toolid = len(self.db_tool_dict) + 1
  2255. self.db_tool_dict[str(new_toolid)] = deepcopy(dict_elem)
  2256. # add the new entry to the Tools DB table
  2257. self.update_storage()
  2258. self.build_db_ui()
  2259. # select the last Tree item just added
  2260. nr_items = self.ui.tree_widget.topLevelItemCount()
  2261. if nr_items:
  2262. last_item = self.ui.tree_widget.topLevelItem(nr_items - 1)
  2263. self.ui.tree_widget.setCurrentItem(last_item)
  2264. last_item.setSelected(True)
  2265. self.on_tool_target_changed(val=dict_elem['data']['tool_target'])
  2266. self.app.inform.emit('[success] %s' % _("Tool added to DB."))
  2267. def on_tool_copy(self):
  2268. """
  2269. Copy a selection of Tools in the Tools DB table
  2270. :return:
  2271. """
  2272. new_tool_id = len(self.db_tool_dict)
  2273. for item in self.ui.tree_widget.selectedItems():
  2274. old_tool_id = item.data(0, QtCore.Qt.DisplayRole)
  2275. for toolid, dict_val in list(self.db_tool_dict.items()):
  2276. if int(old_tool_id) == int(toolid):
  2277. new_tool_id += 1
  2278. new_key = str(new_tool_id)
  2279. self.db_tool_dict.update({
  2280. new_key: deepcopy(dict_val)
  2281. })
  2282. self.current_toolid = new_tool_id
  2283. self.update_storage()
  2284. self.build_db_ui()
  2285. # select the last Tree item just added
  2286. nr_items = self.ui.tree_widget.topLevelItemCount()
  2287. if nr_items:
  2288. last_item = self.ui.tree_widget.topLevelItem(nr_items - 1)
  2289. self.ui.tree_widget.setCurrentItem(last_item)
  2290. last_item.setSelected(True)
  2291. self.callback_app()
  2292. self.app.inform.emit('[success] %s' % _("Tool copied from Tools DB."))
  2293. def on_tool_delete(self):
  2294. """
  2295. Delete a selection of Tools in the Tools DB table
  2296. :return:
  2297. """
  2298. for item in self.ui.tree_widget.selectedItems():
  2299. toolname_to_remove = item.data(0, QtCore.Qt.DisplayRole)
  2300. for toolid, dict_val in list(self.db_tool_dict.items()):
  2301. if int(toolname_to_remove) == int(toolid):
  2302. # remove from the storage
  2303. self.db_tool_dict.pop(toolid, None)
  2304. self.current_toolid -= 1
  2305. self.update_storage()
  2306. self.build_db_ui()
  2307. # select the first Tree item
  2308. nr_items = self.ui.tree_widget.topLevelItemCount()
  2309. if nr_items:
  2310. first_item = self.ui.tree_widget.topLevelItem(0)
  2311. self.ui.tree_widget.setCurrentItem(first_item)
  2312. first_item.setSelected(True)
  2313. self.app.inform.emit('[success] %s' % _("Tool removed from Tools DB."))
  2314. def on_export_tools_db_file(self):
  2315. self.app.defaults.report_usage("on_export_tools_db_file")
  2316. self.app.log.debug("on_export_tools_db_file()")
  2317. date = str(datetime.today()).rpartition('.')[0]
  2318. date = ''.join(c for c in date if c not in ':-')
  2319. date = date.replace(' ', '_')
  2320. filter__ = "Text File (*.TXT);;All Files (*.*)"
  2321. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Tools Database"),
  2322. directory='{l_save}/FlatCAM_{n}_{date}'.format(
  2323. l_save=str(self.app.get_last_save_folder()),
  2324. n=_("Tools_Database"),
  2325. date=date),
  2326. ext_filter=filter__)
  2327. filename = str(filename)
  2328. if filename == "":
  2329. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2330. return
  2331. else:
  2332. try:
  2333. f = open(filename, 'w')
  2334. f.close()
  2335. except PermissionError:
  2336. self.app.inform.emit('[WARNING] %s' %
  2337. _("Permission denied, saving not possible.\n"
  2338. "Most likely another app is holding the file open and not accessible."))
  2339. return
  2340. except IOError:
  2341. self.app.log.debug('Creating a new Tools DB file ...')
  2342. f = open(filename, 'w')
  2343. f.close()
  2344. except Exception:
  2345. e = sys.exc_info()[0]
  2346. self.app.log.error("Could not load Tools DB file.")
  2347. self.app.log.error(str(e))
  2348. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  2349. return
  2350. # Save update options
  2351. try:
  2352. # Save Tools DB in a file
  2353. try:
  2354. with open(filename, "w") as f:
  2355. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  2356. except Exception as e:
  2357. self.app.log.debug("App.on_save_tools_db() --> %s" % str(e))
  2358. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  2359. return
  2360. except Exception:
  2361. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  2362. return
  2363. self.app.inform.emit('[success] %s: %s' % (_("Exported Tools DB to"), filename))
  2364. def on_import_tools_db_file(self):
  2365. self.app.defaults.report_usage("on_import_tools_db_file")
  2366. self.app.log.debug("on_import_tools_db_file()")
  2367. filter__ = "Text File (*.TXT);;All Files (*.*)"
  2368. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Tools DB"), filter=filter__)
  2369. if filename == "":
  2370. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2371. else:
  2372. try:
  2373. with open(filename) as f:
  2374. tools_in_db = f.read()
  2375. except IOError:
  2376. self.app.log.error("Could not load Tools DB file.")
  2377. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  2378. return
  2379. try:
  2380. self.db_tool_dict = json.loads(tools_in_db)
  2381. except Exception:
  2382. e = sys.exc_info()[0]
  2383. self.app.log.error(str(e))
  2384. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  2385. return
  2386. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  2387. self.build_db_ui()
  2388. self.update_storage()
  2389. def on_save_tools_db(self, silent=False):
  2390. self.app.log.debug("ToolsDB.on_save_button() --> Saving Tools Database to file.")
  2391. filename = self.app.data_path + "/geo_tools_db.FlatDB"
  2392. # Preferences save, update the color of the Tools DB Tab text
  2393. for idx in range(self.app_ui.plot_tab_area.count()):
  2394. if self.app_ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2395. self.app_ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  2396. self.ui.save_db_btn.setStyleSheet("")
  2397. # clean the dictionary and leave only keys of interest
  2398. for tool_id in self.db_tool_dict.keys():
  2399. if self.db_tool_dict[tool_id]['data']['tool_target'] != _('General'):
  2400. continue
  2401. if self.db_tool_dict[tool_id]['data']['tool_target'] == _('Milling'):
  2402. for k in list(self.db_tool_dict[tool_id]['data'].keys()):
  2403. if str(k).startswith('tools_'):
  2404. self.db_tool_dict[tool_id]['data'].pop(k, None)
  2405. if self.db_tool_dict[tool_id]['data']['tool_target'] == _('Drilling'):
  2406. for k in list(self.db_tool_dict[tool_id]['data'].keys()):
  2407. if str(k).startswith('tools_'):
  2408. if str(k).startswith('tools_drill'):
  2409. pass
  2410. else:
  2411. self.db_tool_dict[tool_id]['data'].pop(k, None)
  2412. if self.db_tool_dict[tool_id]['data']['tool_target'] == _('Isolation'):
  2413. for k in list(self.db_tool_dict[tool_id]['data'].keys()):
  2414. if str(k).startswith('tools_'):
  2415. if str(k).startswith('tools_iso'):
  2416. pass
  2417. else:
  2418. self.db_tool_dict[tool_id]['data'].pop(k, None)
  2419. if self.db_tool_dict[tool_id]['data']['tool_target'] == _('Paint'):
  2420. for k in list(self.db_tool_dict[tool_id]['data'].keys()):
  2421. if str(k).startswith('tools_'):
  2422. if str(k).startswith('tools_paint'):
  2423. pass
  2424. else:
  2425. self.db_tool_dict[tool_id]['data'].pop(k, None)
  2426. if self.db_tool_dict[tool_id]['data']['tool_target'] == _('NCC'):
  2427. for k in list(self.db_tool_dict[tool_id]['data'].keys()):
  2428. if str(k).startswith('tools_'):
  2429. if str(k).startswith('tools_ncc'):
  2430. pass
  2431. else:
  2432. self.db_tool_dict[tool_id]['data'].pop(k, None)
  2433. # Save Tools DB in a file
  2434. try:
  2435. f = open(filename, "w")
  2436. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  2437. f.close()
  2438. except Exception as e:
  2439. self.app.log.debug("ToolsDB.on_save_tools_db() --> %s" % str(e))
  2440. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  2441. return
  2442. if not silent:
  2443. self.app.inform.emit('[success] %s' % _("Saved Tools DB."))
  2444. def on_save_db_btn_click(self):
  2445. self.app.tools_db_changed_flag = False
  2446. self.on_save_tools_db()
  2447. def on_calculate_tooldia(self):
  2448. if self.ui.shape_combo.get_value() == 'V':
  2449. tip_dia = float(self.ui.vdia_entry.get_value())
  2450. half_tip_angle = float(self.ui.vangle_entry.get_value()) / 2.0
  2451. cut_z = float(self.ui.cutz_entry.get_value())
  2452. cut_z = -cut_z if cut_z < 0 else cut_z
  2453. # calculated tool diameter so the cut_z parameter is obeyed
  2454. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(half_tip_angle)))
  2455. self.ui.dia_entry.set_value(tool_dia)
  2456. def ui_connect(self):
  2457. # make sure that we don't make multiple connections to the widgets
  2458. self.ui_disconnect()
  2459. self.ui.name_entry.editingFinished.connect(self.update_tree_name)
  2460. for key in self.form_fields:
  2461. wdg = self.form_fields[key]
  2462. # FCEntry
  2463. if isinstance(wdg, FCEntry):
  2464. wdg.textChanged.connect(self.update_storage)
  2465. # ComboBox
  2466. if isinstance(wdg, FCComboBox):
  2467. wdg.currentIndexChanged.connect(self.update_storage)
  2468. # CheckBox
  2469. if isinstance(wdg, FCCheckBox):
  2470. wdg.toggled.connect(self.update_storage)
  2471. # FCRadio
  2472. if isinstance(wdg, RadioSet):
  2473. wdg.activated_custom.connect(self.update_storage)
  2474. # SpinBox, DoubleSpinBox
  2475. if isinstance(wdg, FCSpinner) or isinstance(wdg, FCDoubleSpinner):
  2476. wdg.valueChanged.connect(self.update_storage)
  2477. # connect the calculate tooldia method to the controls
  2478. # if the tool shape is 'V' the tool dia will be calculated to obey Cut Z parameter
  2479. self.ui.shape_combo.currentIndexChanged.connect(self.on_calculate_tooldia)
  2480. self.ui.cutz_entry.valueChanged.connect(self.on_calculate_tooldia)
  2481. self.ui.vdia_entry.valueChanged.connect(self.on_calculate_tooldia)
  2482. self.ui.vangle_entry.valueChanged.connect(self.on_calculate_tooldia)
  2483. def ui_disconnect(self):
  2484. try:
  2485. self.ui.name_entry.editingFinished.disconnect(self.update_tree_name)
  2486. except (TypeError, AttributeError):
  2487. pass
  2488. try:
  2489. self.ui.shape_combo.currentIndexChanged.disconnect(self.on_calculate_tooldia)
  2490. except (TypeError, AttributeError):
  2491. pass
  2492. try:
  2493. self.ui.cutz_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2494. except (TypeError, AttributeError):
  2495. pass
  2496. try:
  2497. self.ui.vdia_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2498. except (TypeError, AttributeError):
  2499. pass
  2500. try:
  2501. self.ui.vangle_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2502. except (TypeError, AttributeError):
  2503. pass
  2504. for key in self.form_fields:
  2505. wdg = self.form_fields[key]
  2506. # FCEntry
  2507. if isinstance(wdg, FCEntry):
  2508. try:
  2509. wdg.textChanged.disconnect(self.update_storage)
  2510. except (TypeError, AttributeError):
  2511. pass
  2512. # ComboBox
  2513. if isinstance(wdg, FCComboBox):
  2514. try:
  2515. wdg.currentIndexChanged.disconnect(self.update_storage)
  2516. except (TypeError, AttributeError):
  2517. pass
  2518. # CheckBox
  2519. if isinstance(wdg, FCCheckBox):
  2520. try:
  2521. wdg.toggled.disconnect(self.update_storage)
  2522. except (TypeError, AttributeError):
  2523. pass
  2524. # FCRadio
  2525. if isinstance(wdg, RadioSet):
  2526. try:
  2527. wdg.activated_custom.disconnect(self.update_storage)
  2528. except (TypeError, AttributeError):
  2529. pass
  2530. # SpinBox, DoubleSpinBox
  2531. if isinstance(wdg, FCSpinner) or isinstance(wdg, FCDoubleSpinner):
  2532. try:
  2533. wdg.valueChanged.disconnect(self.update_storage)
  2534. except (TypeError, AttributeError):
  2535. pass
  2536. def update_tree_name(self):
  2537. val = self.ui.name_entry.get_value()
  2538. item = self.ui.tree_widget.currentItem()
  2539. if item is None:
  2540. return
  2541. # I'm setting the value for the second column (designated by 1) because first column holds the ID
  2542. # and second column holds the Name (this behavior is set in the build_ui method)
  2543. item.setData(1, QtCore.Qt.DisplayRole, val)
  2544. def update_storage(self):
  2545. """
  2546. Update the dictionary that is the storage of the tools 'database'
  2547. :return:
  2548. """
  2549. tool_id = str(self.current_toolid)
  2550. try:
  2551. wdg = self.sender()
  2552. assert isinstance(wdg, QtWidgets.QWidget) or isinstance(wdg, QtWidgets.QAction), \
  2553. "Expected a QWidget got %s" % type(wdg)
  2554. if wdg is None:
  2555. return
  2556. wdg_name = wdg.objectName()
  2557. val = wdg.get_value()
  2558. except AttributeError:
  2559. return
  2560. # #############################################################################################################
  2561. # this might change in the future; it makes sense to change values at once for all tools
  2562. # for now change values only for one tool at once
  2563. sel_rows = []
  2564. for item in self.ui.tree_widget.selectedItems():
  2565. sel_rows.append(item.data(0, QtCore.Qt.DisplayRole))
  2566. len_sel_rows = len(sel_rows)
  2567. if len_sel_rows > 1:
  2568. msg = '[ERROR_NOTCL] %s: %s' % \
  2569. (_("To change tool properties select only one tool. Tools currently selected"), str(len_sel_rows))
  2570. self.app.inform.emit(msg)
  2571. old_value = self.db_tool_dict[tool_id]['data'][self.name2option[wdg_name]]
  2572. wdg.set_value(old_value)
  2573. wdg.clearFocus()
  2574. return
  2575. # #############################################################################################################
  2576. if wdg_name == "gdb_name":
  2577. self.db_tool_dict[tool_id]['name'] = val
  2578. elif wdg_name == "gdb_dia":
  2579. self.db_tool_dict[tool_id]['tooldia'] = val
  2580. elif wdg_name == "gdb_tool_offset":
  2581. self.db_tool_dict[tool_id]['offset'] = val
  2582. elif wdg_name == "gdb_custom_offset":
  2583. self.db_tool_dict[tool_id]['offset_value'] = val
  2584. elif wdg_name == "gdb_type":
  2585. self.db_tool_dict[tool_id]['type'] = val
  2586. elif wdg_name == "gdb_shape":
  2587. self.db_tool_dict[tool_id]['tool_type'] = val
  2588. else:
  2589. # Milling Tool
  2590. if wdg_name == "gdb_tool_target":
  2591. self.db_tool_dict[tool_id]['data']['tool_target'] = val
  2592. elif wdg_name == "gdb_tol_min":
  2593. self.db_tool_dict[tool_id]['data']['tol_min'] = val
  2594. elif wdg_name == "gdb_tol_max":
  2595. self.db_tool_dict[tool_id]['data']['tol_max'] = val
  2596. elif wdg_name == "gdb_cutz":
  2597. self.db_tool_dict[tool_id]['data']['cutz'] = val
  2598. elif wdg_name == "gdb_multidepth":
  2599. self.db_tool_dict[tool_id]['data']['multidepth'] = val
  2600. elif wdg_name == "gdb_multidepth_entry":
  2601. self.db_tool_dict[tool_id]['data']['depthperpass'] = val
  2602. elif wdg_name == "gdb_travelz":
  2603. self.db_tool_dict[tool_id]['data']['travelz'] = val
  2604. elif wdg_name == "gdb_frxy":
  2605. self.db_tool_dict[tool_id]['data']['feedrate'] = val
  2606. elif wdg_name == "gdb_frz":
  2607. self.db_tool_dict[tool_id]['data']['feedrate_z'] = val
  2608. elif wdg_name == "gdb_spindle":
  2609. self.db_tool_dict[tool_id]['data']['spindlespeed'] = val
  2610. elif wdg_name == "gdb_dwell":
  2611. self.db_tool_dict[tool_id]['data']['dwell'] = val
  2612. elif wdg_name == "gdb_dwelltime":
  2613. self.db_tool_dict[tool_id]['data']['dwelltime'] = val
  2614. elif wdg_name == "gdb_vdia":
  2615. self.db_tool_dict[tool_id]['data']['vtipdia'] = val
  2616. elif wdg_name == "gdb_vangle":
  2617. self.db_tool_dict[tool_id]['data']['vtipangle'] = val
  2618. elif wdg_name == "gdb_frapids":
  2619. self.db_tool_dict[tool_id]['data']['feedrate_rapid'] = val
  2620. elif wdg_name == "gdb_ecut":
  2621. self.db_tool_dict[tool_id]['data']['extracut'] = val
  2622. elif wdg_name == "gdb_ecut_length":
  2623. self.db_tool_dict[tool_id]['data']['extracut_length'] = val
  2624. # NCC Tool
  2625. elif wdg_name == "gdb_n_operation":
  2626. self.db_tool_dict[tool_id]['data']['tools_nccoperation'] = val
  2627. elif wdg_name == "gdb_n_overlap":
  2628. self.db_tool_dict[tool_id]['data']['tools_nccoverlap'] = val
  2629. elif wdg_name == "gdb_n_margin":
  2630. self.db_tool_dict[tool_id]['data']['tools_nccmargin'] = val
  2631. elif wdg_name == "gdb_n_method":
  2632. self.db_tool_dict[tool_id]['data']['tools_nccmethod'] = val
  2633. elif wdg_name == "gdb_n_connect":
  2634. self.db_tool_dict[tool_id]['data']['tools_nccconnect'] = val
  2635. elif wdg_name == "gdb_n_contour":
  2636. self.db_tool_dict[tool_id]['data']['tools_ncccontour'] = val
  2637. elif wdg_name == "gdb_n_offset":
  2638. self.db_tool_dict[tool_id]['data']['tools_ncc_offset_choice'] = val
  2639. elif wdg_name == "gdb_n_offset_value":
  2640. self.db_tool_dict[tool_id]['data']['tools_ncc_offset_value'] = val
  2641. elif wdg_name == "gdb_n_milling_type":
  2642. self.db_tool_dict[tool_id]['data']['tools_nccmilling_type'] = val
  2643. # Paint Tool
  2644. elif wdg_name == "gdb_p_overlap":
  2645. self.db_tool_dict[tool_id]['data']['tools_paintoverlap'] = val
  2646. elif wdg_name == "gdb_p_offset":
  2647. self.db_tool_dict[tool_id]['data']['tools_paintoffset'] = val
  2648. elif wdg_name == "gdb_p_method":
  2649. self.db_tool_dict[tool_id]['data']['tools_paintmethod'] = val
  2650. elif wdg_name == "gdb_p_connect":
  2651. self.db_tool_dict[tool_id]['data']['tools_pathconnect'] = val
  2652. elif wdg_name == "gdb_p_contour":
  2653. self.db_tool_dict[tool_id]['data']['tools_paintcontour'] = val
  2654. # Isolation Tool
  2655. elif wdg_name == "gdb_i_passes":
  2656. self.db_tool_dict[tool_id]['data']['tools_iso_passes'] = val
  2657. elif wdg_name == "gdb_i_overlap":
  2658. self.db_tool_dict[tool_id]['data']['tools_iso_overlap'] = val
  2659. elif wdg_name == "gdb_i_milling_type":
  2660. self.db_tool_dict[tool_id]['data']['tools_iso_milling_type'] = val
  2661. elif wdg_name == "gdb_i_follow":
  2662. self.db_tool_dict[tool_id]['data']['tools_iso_follow'] = val
  2663. elif wdg_name == "gdb_i_iso_type":
  2664. self.db_tool_dict[tool_id]['data']['tools_iso_isotype'] = val
  2665. # Drilling Tool
  2666. elif wdg_name == "gdb_e_cutz":
  2667. self.db_tool_dict[tool_id]['data']['tools_drill_cutz'] = val
  2668. elif wdg_name == "gdb_e_multidepth":
  2669. self.db_tool_dict[tool_id]['data']['tools_drill_multidepth'] = val
  2670. elif wdg_name == "gdb_e_depthperpass":
  2671. self.db_tool_dict[tool_id]['data']['tools_drill_depthperpass'] = val
  2672. elif wdg_name == "gdb_e_travelz":
  2673. self.db_tool_dict[tool_id]['data']['tools_drill_travelz'] = val
  2674. elif wdg_name == "gdb_e_feedratez":
  2675. self.db_tool_dict[tool_id]['data']['tools_drill_feedrate_z'] = val
  2676. elif wdg_name == "gdb_e_fr_rapid":
  2677. self.db_tool_dict[tool_id]['data']['tools_drill_feedrate_rapid'] = val
  2678. elif wdg_name == "gdb_e_spindlespeed":
  2679. self.db_tool_dict[tool_id]['data']['tools_drill_spindlespeed'] = val
  2680. elif wdg_name == "gdb_e_dwell":
  2681. self.db_tool_dict[tool_id]['data']['tools_drill_dwell'] = val
  2682. elif wdg_name == "gdb_e_dwelltime":
  2683. self.db_tool_dict[tool_id]['data']['tools_drill_dwelltime'] = val
  2684. elif wdg_name == "gdb_e_offset":
  2685. self.db_tool_dict[tool_id]['data']['tools_drill_offset'] = val
  2686. elif wdg_name == "gdb_e_drill_slots":
  2687. self.db_tool_dict[tool_id]['data']['tools_drill_drill_slots'] = val
  2688. elif wdg_name == "gdb_e_drill_slots_over":
  2689. self.db_tool_dict[tool_id]['data']['tools_drill_drill_overlap'] = val
  2690. elif wdg_name == "gdb_e_drill_last_drill":
  2691. self.db_tool_dict[tool_id]['data']['tools_drill_last_drill'] = val
  2692. self.callback_app()
  2693. def on_tool_requested_from_app(self):
  2694. if not self.ui.tree_widget.selectedItems():
  2695. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("No Tool/row selected in the Tools Database table"))
  2696. return
  2697. for item in self.ui.tree_widget.selectedItems():
  2698. tool_uid = item.data(0, QtCore.Qt.DisplayRole)
  2699. for key in self.db_tool_dict.keys():
  2700. if str(key) == str(tool_uid):
  2701. selected_tool = self.db_tool_dict[key]
  2702. self.on_tool_request(tool=selected_tool)
  2703. def on_cancel_tool(self):
  2704. for idx in range(self.app_ui.plot_tab_area.count()):
  2705. if self.app_ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2706. wdg = self.app_ui.plot_tab_area.widget(idx)
  2707. wdg.deleteLater()
  2708. self.app_ui.plot_tab_area.removeTab(idx)
  2709. self.app.inform.emit('%s' % _("Cancelled adding tool from DB."))
  2710. # def resize_new_tool_table_widget(self, min_size, max_size):
  2711. # """
  2712. # Resize the table widget responsible for adding new tool in the Tool Database
  2713. #
  2714. # :param min_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  2715. # :param max_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  2716. # :return:
  2717. # """
  2718. # t_height = self.t_height
  2719. # if max_size > min_size:
  2720. # t_height = self.t_height + self.new_tool_table_widget.verticalScrollBar().height()
  2721. #
  2722. # self.new_tool_table_widget.setMaximumHeight(t_height)
  2723. def closeEvent(self, QCloseEvent):
  2724. super().closeEvent(QCloseEvent)