appDatabase.py 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  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 it's set speed."))
  224. self.table_widget.horizontalHeaderItem(18).setToolTip(
  225. _("Dwell Time.\n"
  226. "A delay used to allow the motor spindle reach it's 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 ToolsDB2(QtWidgets.QWidget):
  810. mark_tools_rows = QtCore.pyqtSignal()
  811. def __init__(self, app, callback_on_edited, callback_on_tool_request, parent=None):
  812. super(ToolsDB2, self).__init__(parent)
  813. self.app = app
  814. self.decimals = self.app.decimals
  815. self.callback_app = callback_on_edited
  816. self.on_tool_request = callback_on_tool_request
  817. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  818. self.type_item_options = ["Iso", "Rough", "Finish"]
  819. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  820. '''
  821. dict to hold all the tools in the Tools DB
  822. format:
  823. {
  824. tool_id: {
  825. 'name': 'new_tool'
  826. 'tooldia': self.app.defaults["geometry_cnctooldia"]
  827. 'offset': 'Path'
  828. 'offset_value': 0.0
  829. 'type': _('Rough'),
  830. 'tool_type': 'C1'
  831. 'data': dict()
  832. }
  833. }
  834. '''
  835. self.db_tool_dict = {}
  836. # layouts
  837. grid_layout = QtWidgets.QGridLayout()
  838. grid_layout.setColumnStretch(0, 0)
  839. grid_layout.setColumnStretch(1, 1)
  840. self.setLayout(grid_layout)
  841. tree_layout = QtWidgets.QVBoxLayout()
  842. grid_layout.addLayout(tree_layout, 0, 0)
  843. self.tree_widget = FCTree(columns=2, header_hidden=False, protected_column=[0])
  844. self.tree_widget.setHeaderLabels(["ID", "Tool Name"])
  845. self.tree_widget.setIndentation(0)
  846. self.tree_widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
  847. self.tree_widget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  848. # set alternating colors
  849. # self.tree_widget.setAlternatingRowColors(True)
  850. # p = QtGui.QPalette()
  851. # p.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(226, 237, 253) )
  852. # self.tree_widget.setPalette(p)
  853. self.tree_widget.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
  854. tree_layout.addWidget(self.tree_widget)
  855. param_hlay = QtWidgets.QHBoxLayout()
  856. param_area = QtWidgets.QScrollArea()
  857. param_widget = QtWidgets.QWidget()
  858. param_widget.setLayout(param_hlay)
  859. param_area.setWidget(param_widget)
  860. param_area.setWidgetResizable(True)
  861. grid_layout.addWidget(param_area, 0, 1)
  862. # ###########################################################################
  863. # ############## The UI form ################################################
  864. # ###########################################################################
  865. self.basic_box = QtWidgets.QGroupBox()
  866. self.basic_box.setStyleSheet("""
  867. QGroupBox
  868. {
  869. font-size: 16px;
  870. font-weight: bold;
  871. }
  872. """)
  873. self.basic_vlay = QtWidgets.QVBoxLayout()
  874. self.basic_box.setTitle(_("Basic Geo Parameters"))
  875. self.basic_box.setFixedWidth(250)
  876. self.advanced_box = QtWidgets.QGroupBox()
  877. self.advanced_box.setStyleSheet("""
  878. QGroupBox
  879. {
  880. font-size: 16px;
  881. font-weight: bold;
  882. }
  883. """)
  884. self.advanced_vlay = QtWidgets.QVBoxLayout()
  885. self.advanced_box.setTitle(_("Advanced Geo Parameters"))
  886. self.advanced_box.setFixedWidth(250)
  887. # NCC TOOL BOX
  888. self.ncc_box = QtWidgets.QGroupBox()
  889. self.ncc_box.setStyleSheet("""
  890. QGroupBox
  891. {
  892. font-size: 16px;
  893. font-weight: bold;
  894. }
  895. """)
  896. self.ncc_vlay = QtWidgets.QVBoxLayout()
  897. self.ncc_box.setTitle(_("NCC Parameters"))
  898. self.ncc_box.setFixedWidth(250)
  899. # PAINT TOOL BOX
  900. self.paint_box = QtWidgets.QGroupBox()
  901. self.paint_box.setStyleSheet("""
  902. QGroupBox
  903. {
  904. font-size: 16px;
  905. font-weight: bold;
  906. }
  907. """)
  908. self.paint_vlay = QtWidgets.QVBoxLayout()
  909. self.paint_box.setTitle(_("Paint Parameters"))
  910. self.paint_box.setFixedWidth(250)
  911. # ISOLATION TOOL BOX
  912. self.iso_box = QtWidgets.QGroupBox()
  913. self.iso_box.setStyleSheet("""
  914. QGroupBox
  915. {
  916. font-size: 16px;
  917. font-weight: bold;
  918. }
  919. """)
  920. self.iso_vlay = QtWidgets.QVBoxLayout()
  921. self.iso_box.setTitle(_("Isolation Parameters"))
  922. self.iso_box.setFixedWidth(250)
  923. self.basic_box.setLayout(self.basic_vlay)
  924. self.advanced_box.setLayout(self.advanced_vlay)
  925. self.ncc_box.setLayout(self.ncc_vlay)
  926. self.paint_box.setLayout(self.paint_vlay)
  927. self.iso_box.setLayout(self.iso_vlay)
  928. geo_vlay = QtWidgets.QVBoxLayout()
  929. geo_vlay.addWidget(self.basic_box)
  930. geo_vlay.addWidget(self.advanced_box)
  931. geo_vlay.addStretch()
  932. tools_vlay = QtWidgets.QVBoxLayout()
  933. tools_vlay.addWidget(self.ncc_box)
  934. tools_vlay.addWidget(self.paint_box)
  935. tools_vlay.addWidget(self.iso_box)
  936. tools_vlay.addStretch()
  937. param_hlay.addLayout(geo_vlay)
  938. param_hlay.addLayout(tools_vlay)
  939. param_hlay.addStretch()
  940. # ###########################################################################
  941. # ############### BASIC UI form #############################################
  942. # ###########################################################################
  943. self.grid0 = QtWidgets.QGridLayout()
  944. self.basic_vlay.addLayout(self.grid0)
  945. self.grid0.setColumnStretch(0, 0)
  946. self.grid0.setColumnStretch(1, 1)
  947. self.basic_vlay.addStretch()
  948. # Tool Name
  949. self.name_label = QtWidgets.QLabel('<span style="color:red;"><b>%s:</b></span>' % _('Tool Name'))
  950. self.name_label.setToolTip(
  951. _("Tool name.\n"
  952. "This is not used in the app, it's function\n"
  953. "is to serve as a note for the user."))
  954. self.name_entry = FCEntry()
  955. self.name_entry.setObjectName('gdb_name')
  956. self.grid0.addWidget(self.name_label, 0, 0)
  957. self.grid0.addWidget(self.name_entry, 0, 1)
  958. # Tool Dia
  959. self.dia_label = QtWidgets.QLabel('%s:' % _('Tool Dia'))
  960. self.dia_label.setToolTip(
  961. _("Tool Diameter."))
  962. self.dia_entry = FCDoubleSpinner()
  963. self.dia_entry.set_range(-9999.9999, 9999.9999)
  964. self.dia_entry.set_precision(self.decimals)
  965. self.dia_entry.setObjectName('gdb_dia')
  966. self.grid0.addWidget(self.dia_label, 1, 0)
  967. self.grid0.addWidget(self.dia_entry, 1, 1)
  968. # Tool Shape
  969. self.shape_label = QtWidgets.QLabel('%s:' % _('Tool Shape'))
  970. self.shape_label.setToolTip(
  971. _("Tool Shape. \n"
  972. "Can be:\n"
  973. "C1 ... C4 = circular tool with x flutes\n"
  974. "B = ball tip milling tool\n"
  975. "V = v-shape milling tool"))
  976. self.shape_combo = FCComboBox()
  977. self.shape_combo.addItems(["C1", "C2", "C3", "C4", "B", "V"])
  978. self.shape_combo.setObjectName('gdb_shape')
  979. self.grid0.addWidget(self.shape_label, 2, 0)
  980. self.grid0.addWidget(self.shape_combo, 2, 1)
  981. # Cut Z
  982. self.cutz_label = QtWidgets.QLabel('%s:' % _("Cut Z"))
  983. self.cutz_label.setToolTip(
  984. _("Cutting Depth.\n"
  985. "The depth at which to cut into material."))
  986. self.cutz_entry = FCDoubleSpinner()
  987. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  988. self.cutz_entry.set_precision(self.decimals)
  989. self.cutz_entry.setObjectName('gdb_cutz')
  990. self.grid0.addWidget(self.cutz_label, 4, 0)
  991. self.grid0.addWidget(self.cutz_entry, 4, 1)
  992. # Multi Depth
  993. self.multidepth_label = QtWidgets.QLabel('%s:' % _("MultiDepth"))
  994. self.multidepth_label.setToolTip(
  995. _("Multi Depth.\n"
  996. "Selecting this will allow cutting in multiple passes,\n"
  997. "each pass adding a DPP parameter depth."))
  998. self.multidepth_cb = FCCheckBox()
  999. self.multidepth_cb.setObjectName('gdb_multidepth')
  1000. self.grid0.addWidget(self.multidepth_label, 5, 0)
  1001. self.grid0.addWidget(self.multidepth_cb, 5, 1)
  1002. # Depth Per Pass
  1003. self.dpp_label = QtWidgets.QLabel('%s:' % _("DPP"))
  1004. self.dpp_label.setToolTip(
  1005. _("DPP. Depth per Pass.\n"
  1006. "The value used to cut into material on each pass."))
  1007. self.multidepth_entry = FCDoubleSpinner()
  1008. self.multidepth_entry.set_range(-9999.9999, 9999.9999)
  1009. self.multidepth_entry.set_precision(self.decimals)
  1010. self.multidepth_entry.setObjectName('gdb_multidepth_entry')
  1011. self.grid0.addWidget(self.dpp_label, 7, 0)
  1012. self.grid0.addWidget(self.multidepth_entry, 7, 1)
  1013. # Travel Z
  1014. self.travelz_label = QtWidgets.QLabel('%s:' % _("Travel Z"))
  1015. self.travelz_label.setToolTip(
  1016. _("Clearance Height.\n"
  1017. "Height at which the milling bit will travel between cuts,\n"
  1018. "above the surface of the material, avoiding all fixtures."))
  1019. self.travelz_entry = FCDoubleSpinner()
  1020. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  1021. self.travelz_entry.set_precision(self.decimals)
  1022. self.travelz_entry.setObjectName('gdb_travel')
  1023. self.grid0.addWidget(self.travelz_label, 9, 0)
  1024. self.grid0.addWidget(self.travelz_entry, 9, 1)
  1025. # Feedrate X-Y
  1026. self.frxy_label = QtWidgets.QLabel('%s:' % _("Feedrate X-Y"))
  1027. self.frxy_label.setToolTip(
  1028. _("Feedrate X-Y. Feedrate\n"
  1029. "The speed on XY plane used while cutting into material."))
  1030. self.frxy_entry = FCDoubleSpinner()
  1031. self.frxy_entry.set_range(-999999.9999, 999999.9999)
  1032. self.frxy_entry.set_precision(self.decimals)
  1033. self.frxy_entry.setObjectName('gdb_frxy')
  1034. self.grid0.addWidget(self.frxy_label, 12, 0)
  1035. self.grid0.addWidget(self.frxy_entry, 12, 1)
  1036. # Feedrate Z
  1037. self.frz_label = QtWidgets.QLabel('%s:' % _("Feedrate Z"))
  1038. self.frz_label.setToolTip(
  1039. _("Feedrate Z\n"
  1040. "The speed on Z plane."))
  1041. self.frz_entry = FCDoubleSpinner()
  1042. self.frz_entry.set_range(-999999.9999, 999999.9999)
  1043. self.frz_entry.set_precision(self.decimals)
  1044. self.frz_entry.setObjectName('gdb_frz')
  1045. self.grid0.addWidget(self.frz_label, 14, 0)
  1046. self.grid0.addWidget(self.frz_entry, 14, 1)
  1047. # Spindle Spped
  1048. self.spindle_label = QtWidgets.QLabel('%s:' % _("Spindle Speed"))
  1049. self.spindle_label.setToolTip(
  1050. _("Spindle Speed.\n"
  1051. "If it's left empty it will not be used.\n"
  1052. "The speed of the spindle in RPM."))
  1053. self.spindle_entry = FCDoubleSpinner()
  1054. self.spindle_entry.set_range(-999999.9999, 999999.9999)
  1055. self.spindle_entry.set_precision(self.decimals)
  1056. self.spindle_entry.setObjectName('gdb_spindle')
  1057. self.grid0.addWidget(self.spindle_label, 15, 0)
  1058. self.grid0.addWidget(self.spindle_entry, 15, 1)
  1059. # Dwell
  1060. self.dwell_label = QtWidgets.QLabel('%s:' % _("Dwell"))
  1061. self.dwell_label.setToolTip(
  1062. _("Dwell.\n"
  1063. "Check this if a delay is needed to allow\n"
  1064. "the spindle motor to reach it's set speed."))
  1065. self.dwell_cb = FCCheckBox()
  1066. self.dwell_cb.setObjectName('gdb_dwell')
  1067. self.grid0.addWidget(self.dwell_label, 16, 0)
  1068. self.grid0.addWidget(self.dwell_cb, 16, 1)
  1069. # Dwell Time
  1070. self.dwelltime_label = QtWidgets.QLabel('%s:' % _("Dwelltime"))
  1071. self.dwelltime_label.setToolTip(
  1072. _("Dwell Time.\n"
  1073. "A delay used to allow the motor spindle reach it's set speed."))
  1074. self.dwelltime_entry = FCDoubleSpinner()
  1075. self.dwelltime_entry.set_range(0.0000, 9999.9999)
  1076. self.dwelltime_entry.set_precision(self.decimals)
  1077. self.dwelltime_entry.setObjectName('gdb_dwelltime')
  1078. self.grid0.addWidget(self.dwelltime_label, 17, 0)
  1079. self.grid0.addWidget(self.dwelltime_entry, 17, 1)
  1080. # ###########################################################################
  1081. # ############### ADVANCED UI form ##########################################
  1082. # ###########################################################################
  1083. self.grid1 = QtWidgets.QGridLayout()
  1084. self.advanced_vlay.addLayout(self.grid1)
  1085. self.grid1.setColumnStretch(0, 0)
  1086. self.grid1.setColumnStretch(1, 1)
  1087. self.advanced_vlay.addStretch()
  1088. # Tool Type
  1089. self.type_label = QtWidgets.QLabel('%s:' % _("Tool Type"))
  1090. self.type_label.setToolTip(
  1091. _("Tool Type.\n"
  1092. "Can be:\n"
  1093. "Iso = isolation cut\n"
  1094. "Rough = rough cut, low feedrate, multiple passes\n"
  1095. "Finish = finishing cut, high feedrate"))
  1096. self.type_combo = FCComboBox()
  1097. self.type_combo.addItems(["Iso", "Rough", "Finish"])
  1098. self.type_combo.setObjectName('gdb_type')
  1099. self.grid1.addWidget(self.type_label, 0, 0)
  1100. self.grid1.addWidget(self.type_combo, 0, 1)
  1101. # Tool Offset
  1102. self.tooloffset_label = QtWidgets.QLabel('%s:' % _('Tool Offset'))
  1103. self.tooloffset_label.setToolTip(
  1104. _("Tool Offset.\n"
  1105. "Can be of a few types:\n"
  1106. "Path = zero offset\n"
  1107. "In = offset inside by half of tool diameter\n"
  1108. "Out = offset outside by half of tool diameter\n"
  1109. "Custom = custom offset using the Custom Offset value"))
  1110. self.tooloffset_combo = FCComboBox()
  1111. self.tooloffset_combo.addItems(["Path", "In", "Out", "Custom"])
  1112. self.tooloffset_combo.setObjectName('gdb_tool_offset')
  1113. self.grid1.addWidget(self.tooloffset_label, 2, 0)
  1114. self.grid1.addWidget(self.tooloffset_combo, 2, 1)
  1115. # Custom Offset
  1116. self.custom_offset_label = QtWidgets.QLabel('%s:' % _("Custom Offset"))
  1117. self.custom_offset_label.setToolTip(
  1118. _("Custom Offset.\n"
  1119. "A value to be used as offset from the current path."))
  1120. self.custom_offset_entry = FCDoubleSpinner()
  1121. self.custom_offset_entry.set_range(-9999.9999, 9999.9999)
  1122. self.custom_offset_entry.set_precision(self.decimals)
  1123. self.custom_offset_entry.setObjectName('gdb_custom_offset')
  1124. self.grid1.addWidget(self.custom_offset_label, 5, 0)
  1125. self.grid1.addWidget(self.custom_offset_entry, 5, 1)
  1126. # V-Dia
  1127. self.vdia_label = QtWidgets.QLabel('%s:' % _("V-Dia"))
  1128. self.vdia_label.setToolTip(
  1129. _("V-Dia.\n"
  1130. "Diameter of the tip for V-Shape Tools."))
  1131. self.vdia_entry = FCDoubleSpinner()
  1132. self.vdia_entry.set_range(0.0000, 9999.9999)
  1133. self.vdia_entry.set_precision(self.decimals)
  1134. self.vdia_entry.setObjectName('gdb_vdia')
  1135. self.grid1.addWidget(self.vdia_label, 7, 0)
  1136. self.grid1.addWidget(self.vdia_entry, 7, 1)
  1137. # V-Angle
  1138. self.vangle_label = QtWidgets.QLabel('%s:' % _("V-Angle"))
  1139. self.vangle_label.setToolTip(
  1140. _("V-Agle.\n"
  1141. "Angle at the tip for the V-Shape Tools."))
  1142. self.vangle_entry = FCDoubleSpinner()
  1143. self.vangle_entry.set_range(-360.0, 360.0)
  1144. self.vangle_entry.set_precision(self.decimals)
  1145. self.vangle_entry.setObjectName('gdb_vangle')
  1146. self.grid1.addWidget(self.vangle_label, 8, 0)
  1147. self.grid1.addWidget(self.vangle_entry, 8, 1)
  1148. # Feedrate Rapids
  1149. self.frapids_label = QtWidgets.QLabel('%s:' % _("FR Rapids"))
  1150. self.frapids_label.setToolTip(
  1151. _("FR Rapids. Feedrate Rapids\n"
  1152. "Speed used while moving as fast as possible.\n"
  1153. "This is used only by some devices that can't use\n"
  1154. "the G0 g-code command. Mostly 3D printers."))
  1155. self.frapids_entry = FCDoubleSpinner()
  1156. self.frapids_entry.set_range(0.0000, 9999.9999)
  1157. self.frapids_entry.set_precision(self.decimals)
  1158. self.frapids_entry.setObjectName('gdb_frapids')
  1159. self.grid1.addWidget(self.frapids_label, 10, 0)
  1160. self.grid1.addWidget(self.frapids_entry, 10, 1)
  1161. # Extra Cut
  1162. self.ecut_label = QtWidgets.QLabel('%s:' % _("ExtraCut"))
  1163. self.ecut_label.setToolTip(
  1164. _("Extra Cut.\n"
  1165. "If checked, after a isolation is finished an extra cut\n"
  1166. "will be added where the start and end of isolation meet\n"
  1167. "such as that this point is covered by this extra cut to\n"
  1168. "ensure a complete isolation."))
  1169. self.ecut_cb = FCCheckBox()
  1170. self.ecut_cb.setObjectName('gdb_ecut')
  1171. self.grid1.addWidget(self.ecut_label, 12, 0)
  1172. self.grid1.addWidget(self.ecut_cb, 12, 1)
  1173. # Extra Cut Length
  1174. self.ecut_length_label = QtWidgets.QLabel('%s:' % _("E-Cut Length"))
  1175. self.ecut_length_label.setToolTip(
  1176. _("Extra Cut length.\n"
  1177. "If checked, after a isolation is finished an extra cut\n"
  1178. "will be added where the start and end of isolation meet\n"
  1179. "such as that this point is covered by this extra cut to\n"
  1180. "ensure a complete isolation. This is the length of\n"
  1181. "the extra cut."))
  1182. self.ecut_length_entry = FCDoubleSpinner()
  1183. self.ecut_length_entry.set_range(0.0000, 9999.9999)
  1184. self.ecut_length_entry.set_precision(self.decimals)
  1185. self.ecut_length_entry.setObjectName('gdb_ecut_length')
  1186. self.grid1.addWidget(self.ecut_length_label, 13, 0)
  1187. self.grid1.addWidget(self.ecut_length_entry, 13, 1)
  1188. # ###########################################################################
  1189. # ############### NCC UI form ###############################################
  1190. # ###########################################################################
  1191. self.grid2 = QtWidgets.QGridLayout()
  1192. self.ncc_vlay.addLayout(self.grid2)
  1193. self.grid2.setColumnStretch(0, 0)
  1194. self.grid2.setColumnStretch(1, 1)
  1195. self.ncc_vlay.addStretch()
  1196. # Operation
  1197. op_label = QtWidgets.QLabel('%s:' % _('Operation'))
  1198. op_label.setToolTip(
  1199. _("The 'Operation' can be:\n"
  1200. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  1201. "If it's not successful then the non-copper clearing will fail, too.\n"
  1202. "- Clear -> the regular non-copper clearing.")
  1203. )
  1204. self.op_radio = RadioSet([
  1205. {"label": _("Clear"), "value": "clear"},
  1206. {"label": _("Isolation"), "value": "iso"}
  1207. ], orientation='horizontal', stretch=False)
  1208. self.op_radio.setObjectName("gdb_n_operation")
  1209. self.grid2.addWidget(op_label, 13, 0)
  1210. self.grid2.addWidget(self.op_radio, 13, 1)
  1211. # Milling Type Radio Button
  1212. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  1213. self.milling_type_label.setToolTip(
  1214. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1215. "- climb / best for precision milling and to reduce tool usage\n"
  1216. "- conventional / useful when there is no backlash compensation")
  1217. )
  1218. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  1219. {'label': _('Conventional'), 'value': 'cv'}])
  1220. self.milling_type_radio.setToolTip(
  1221. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1222. "- climb / best for precision milling and to reduce tool usage\n"
  1223. "- conventional / useful when there is no backlash compensation")
  1224. )
  1225. self.milling_type_radio.setObjectName("gdb_n_milling_type")
  1226. self.grid2.addWidget(self.milling_type_label, 14, 0)
  1227. self.grid2.addWidget(self.milling_type_radio, 14, 1)
  1228. # Overlap Entry
  1229. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1230. nccoverlabel.setToolTip(
  1231. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  1232. "Adjust the value starting with lower values\n"
  1233. "and increasing it if areas that should be cleared are still \n"
  1234. "not cleared.\n"
  1235. "Lower values = faster processing, faster execution on CNC.\n"
  1236. "Higher values = slow processing and slow execution on CNC\n"
  1237. "due of too many paths.")
  1238. )
  1239. self.ncc_overlap_entry = FCDoubleSpinner(suffix='%')
  1240. self.ncc_overlap_entry.set_precision(self.decimals)
  1241. self.ncc_overlap_entry.setWrapping(True)
  1242. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  1243. self.ncc_overlap_entry.setSingleStep(0.1)
  1244. self.ncc_overlap_entry.setObjectName("gdb_n_overlap")
  1245. self.grid2.addWidget(nccoverlabel, 15, 0)
  1246. self.grid2.addWidget(self.ncc_overlap_entry, 15, 1)
  1247. # Margin
  1248. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  1249. nccmarginlabel.setToolTip(
  1250. _("Bounding box margin.")
  1251. )
  1252. self.ncc_margin_entry = FCDoubleSpinner()
  1253. self.ncc_margin_entry.set_precision(self.decimals)
  1254. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  1255. self.ncc_margin_entry.setObjectName("gdb_n_margin")
  1256. self.grid2.addWidget(nccmarginlabel, 16, 0)
  1257. self.grid2.addWidget(self.ncc_margin_entry, 16, 1)
  1258. # Method
  1259. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  1260. methodlabel.setToolTip(
  1261. _("Algorithm for copper clearing:\n"
  1262. "- Standard: Fixed step inwards.\n"
  1263. "- Seed-based: Outwards from seed.\n"
  1264. "- Line-based: Parallel lines.")
  1265. )
  1266. self.ncc_method_combo = FCComboBox()
  1267. self.ncc_method_combo.addItems(
  1268. [_("Standard"), _("Seed"), _("Lines"), _("Combo")]
  1269. )
  1270. self.ncc_method_combo.setObjectName("gdb_n_method")
  1271. self.grid2.addWidget(methodlabel, 17, 0)
  1272. self.grid2.addWidget(self.ncc_method_combo, 17, 1)
  1273. # Connect lines
  1274. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  1275. self.ncc_connect_cb.setObjectName("gdb_n_connect")
  1276. self.ncc_connect_cb.setToolTip(
  1277. _("Draw lines between resulting\n"
  1278. "segments to minimize tool lifts.")
  1279. )
  1280. self.grid2.addWidget(self.ncc_connect_cb, 18, 0)
  1281. # Contour
  1282. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  1283. self.ncc_contour_cb.setObjectName("gdb_n_contour")
  1284. self.ncc_contour_cb.setToolTip(
  1285. _("Cut around the perimeter of the polygon\n"
  1286. "to trim rough edges.")
  1287. )
  1288. self.grid2.addWidget(self.ncc_contour_cb, 18, 1)
  1289. # ## NCC Offset choice
  1290. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  1291. self.ncc_choice_offset_cb.setObjectName("gdb_n_offset")
  1292. self.ncc_choice_offset_cb.setToolTip(
  1293. _("If used, it will add an offset to the copper features.\n"
  1294. "The copper clearing will finish to a distance\n"
  1295. "from the copper features.\n"
  1296. "The value can be between 0 and 10 FlatCAM units.")
  1297. )
  1298. self.grid2.addWidget(self.ncc_choice_offset_cb, 19, 0)
  1299. # ## NCC Offset Entry
  1300. self.ncc_offset_spinner = FCDoubleSpinner()
  1301. self.ncc_offset_spinner.set_range(0.00, 10.00)
  1302. self.ncc_offset_spinner.set_precision(4)
  1303. self.ncc_offset_spinner.setWrapping(True)
  1304. self.ncc_offset_spinner.setObjectName("gdb_n_offset_value")
  1305. units = self.app.defaults['units'].upper()
  1306. if units == 'MM':
  1307. self.ncc_offset_spinner.setSingleStep(0.1)
  1308. else:
  1309. self.ncc_offset_spinner.setSingleStep(0.01)
  1310. self.grid2.addWidget(self.ncc_offset_spinner, 19, 1)
  1311. # ###########################################################################
  1312. # ############### Paint UI form #############################################
  1313. # ###########################################################################
  1314. self.grid3 = QtWidgets.QGridLayout()
  1315. self.paint_vlay.addLayout(self.grid3)
  1316. self.grid3.setColumnStretch(0, 0)
  1317. self.grid3.setColumnStretch(1, 1)
  1318. self.paint_vlay.addStretch()
  1319. # Overlap
  1320. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1321. ovlabel.setToolTip(
  1322. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  1323. "Adjust the value starting with lower values\n"
  1324. "and increasing it if areas that should be painted are still \n"
  1325. "not painted.\n"
  1326. "Lower values = faster processing, faster execution on CNC.\n"
  1327. "Higher values = slow processing and slow execution on CNC\n"
  1328. "due of too many paths.")
  1329. )
  1330. self.paintoverlap_entry = FCDoubleSpinner(suffix='%')
  1331. self.paintoverlap_entry.set_precision(3)
  1332. self.paintoverlap_entry.setWrapping(True)
  1333. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  1334. self.paintoverlap_entry.setSingleStep(0.1)
  1335. self.paintoverlap_entry.setObjectName('gdb_p_overlap')
  1336. self.grid3.addWidget(ovlabel, 1, 0)
  1337. self.grid3.addWidget(self.paintoverlap_entry, 1, 1)
  1338. # Margin
  1339. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  1340. marginlabel.setToolTip(
  1341. _("Distance by which to avoid\n"
  1342. "the edges of the polygon to\n"
  1343. "be painted.")
  1344. )
  1345. self.paintmargin_entry = FCDoubleSpinner()
  1346. self.paintmargin_entry.set_precision(self.decimals)
  1347. self.paintmargin_entry.set_range(-9999.9999, 9999.9999)
  1348. self.paintmargin_entry.setObjectName('gdb_p_margin')
  1349. self.grid3.addWidget(marginlabel, 2, 0)
  1350. self.grid3.addWidget(self.paintmargin_entry, 2, 1)
  1351. # Method
  1352. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  1353. methodlabel.setToolTip(
  1354. _("Algorithm for painting:\n"
  1355. "- Standard: Fixed step inwards.\n"
  1356. "- Seed-based: Outwards from seed.\n"
  1357. "- Line-based: Parallel lines.\n"
  1358. "- Laser-lines: Active only for Gerber objects.\n"
  1359. "Will create lines that follow the traces.\n"
  1360. "- Combo: In case of failure a new method will be picked from the above\n"
  1361. "in the order specified.")
  1362. )
  1363. self.paintmethod_combo = FCComboBox()
  1364. self.paintmethod_combo.addItems(
  1365. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  1366. )
  1367. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  1368. self.paintmethod_combo.model().item(idx).setEnabled(False)
  1369. self.paintmethod_combo.setObjectName('gdb_p_method')
  1370. self.grid3.addWidget(methodlabel, 7, 0)
  1371. self.grid3.addWidget(self.paintmethod_combo, 7, 1)
  1372. # Connect lines
  1373. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  1374. self.pathconnect_cb.setObjectName('gdb_p_connect')
  1375. self.pathconnect_cb.setToolTip(
  1376. _("Draw lines between resulting\n"
  1377. "segments to minimize tool lifts.")
  1378. )
  1379. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  1380. self.paintcontour_cb.setObjectName('gdb_p_contour')
  1381. self.paintcontour_cb.setToolTip(
  1382. _("Cut around the perimeter of the polygon\n"
  1383. "to trim rough edges.")
  1384. )
  1385. self.grid3.addWidget(self.pathconnect_cb, 10, 0)
  1386. self.grid3.addWidget(self.paintcontour_cb, 10, 1)
  1387. # ###########################################################################
  1388. # ############### Paint UI form #############################################
  1389. # ###########################################################################
  1390. self.grid4 = QtWidgets.QGridLayout()
  1391. self.iso_vlay.addLayout(self.grid4)
  1392. self.grid4.setColumnStretch(0, 0)
  1393. self.grid4.setColumnStretch(1, 1)
  1394. self.iso_vlay.addStretch()
  1395. # Passes
  1396. passlabel = QtWidgets.QLabel('%s:' % _('Passes'))
  1397. passlabel.setToolTip(
  1398. _("Width of the isolation gap in\n"
  1399. "number (integer) of tool widths.")
  1400. )
  1401. self.passes_entry = FCSpinner()
  1402. self.passes_entry.set_range(1, 999)
  1403. self.passes_entry.setObjectName("gdb_i_passes")
  1404. self.grid4.addWidget(passlabel, 0, 0)
  1405. self.grid4.addWidget(self.passes_entry, 0, 1)
  1406. # Overlap Entry
  1407. overlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  1408. overlabel.setToolTip(
  1409. _("How much (percentage) of the tool width to overlap each tool pass.")
  1410. )
  1411. self.iso_overlap_entry = FCDoubleSpinner(suffix='%')
  1412. self.iso_overlap_entry.set_precision(self.decimals)
  1413. self.iso_overlap_entry.setWrapping(True)
  1414. self.iso_overlap_entry.set_range(0.0000, 99.9999)
  1415. self.iso_overlap_entry.setSingleStep(0.1)
  1416. self.iso_overlap_entry.setObjectName("gdb_i_overlap")
  1417. self.grid4.addWidget(overlabel, 2, 0)
  1418. self.grid4.addWidget(self.iso_overlap_entry, 2, 1)
  1419. # Milling Type Radio Button
  1420. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  1421. self.milling_type_label.setToolTip(
  1422. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1423. "- climb / best for precision milling and to reduce tool usage\n"
  1424. "- conventional / useful when there is no backlash compensation")
  1425. )
  1426. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  1427. {'label': _('Conventional'), 'value': 'cv'}])
  1428. self.milling_type_radio.setToolTip(
  1429. _("Milling type when the selected tool is of type: 'iso_op':\n"
  1430. "- climb / best for precision milling and to reduce tool usage\n"
  1431. "- conventional / useful when there is no backlash compensation")
  1432. )
  1433. self.milling_type_radio.setObjectName("gdb_i_milling_type")
  1434. self.grid4.addWidget(self.milling_type_label, 4, 0)
  1435. self.grid4.addWidget(self.milling_type_radio, 4, 1)
  1436. # Follow
  1437. self.follow_label = QtWidgets.QLabel('%s:' % _('Follow'))
  1438. self.follow_label.setToolTip(
  1439. _("Generate a 'Follow' geometry.\n"
  1440. "This means that it will cut through\n"
  1441. "the middle of the trace.")
  1442. )
  1443. self.follow_cb = FCCheckBox()
  1444. self.follow_cb.setToolTip(_("Generate a 'Follow' geometry.\n"
  1445. "This means that it will cut through\n"
  1446. "the middle of the trace."))
  1447. self.follow_cb.setObjectName("gdb_i_follow")
  1448. self.grid4.addWidget(self.follow_label, 6, 0)
  1449. self.grid4.addWidget(self.follow_cb, 6, 1)
  1450. # Isolation Type
  1451. self.iso_type_label = QtWidgets.QLabel('%s:' % _('Isolation Type'))
  1452. self.iso_type_label.setToolTip(
  1453. _("Choose how the isolation will be executed:\n"
  1454. "- 'Full' -> complete isolation of polygons\n"
  1455. "- 'Ext' -> will isolate only on the outside\n"
  1456. "- 'Int' -> will isolate only on the inside\n"
  1457. "'Exterior' isolation is almost always possible\n"
  1458. "(with the right tool) but 'Interior'\n"
  1459. "isolation can be done only when there is an opening\n"
  1460. "inside of the polygon (e.g polygon is a 'doughnut' shape).")
  1461. )
  1462. self.iso_type_radio = RadioSet([{'label': _('Full'), 'value': 'full'},
  1463. {'label': _('Ext'), 'value': 'ext'},
  1464. {'label': _('Int'), 'value': 'int'}])
  1465. self.iso_type_radio.setObjectName("gdb_i_iso_type")
  1466. self.grid4.addWidget(self.iso_type_label, 8, 0)
  1467. self.grid4.addWidget(self.iso_type_radio, 8, 1)
  1468. # ####################################################################
  1469. # ####################################################################
  1470. # GUI for the lower part of the window
  1471. # ####################################################################
  1472. # ####################################################################
  1473. new_vlay = QtWidgets.QVBoxLayout()
  1474. grid_layout.addLayout(new_vlay, 1, 0, 1, 2)
  1475. self.buttons_frame = QtWidgets.QFrame()
  1476. self.buttons_frame.setContentsMargins(0, 0, 0, 0)
  1477. new_vlay.addWidget(self.buttons_frame)
  1478. self.buttons_box = QtWidgets.QHBoxLayout()
  1479. self.buttons_box.setContentsMargins(0, 0, 0, 0)
  1480. self.buttons_frame.setLayout(self.buttons_box)
  1481. self.buttons_frame.show()
  1482. add_entry_btn = FCButton(_("Add Tool in DB"))
  1483. add_entry_btn.setToolTip(
  1484. _("Add a new tool in the Tools Database.\n"
  1485. "It will be used in the Geometry UI.\n"
  1486. "You can edit it after it is added.")
  1487. )
  1488. self.buttons_box.addWidget(add_entry_btn)
  1489. # add_fct_entry_btn = FCButton(_("Add Paint/NCC Tool in DB"))
  1490. # add_fct_entry_btn.setToolTip(
  1491. # _("Add a new tool in the Tools Database.\n"
  1492. # "It will be used in the Paint/NCC Tools UI.\n"
  1493. # "You can edit it after it is added.")
  1494. # )
  1495. # self.buttons_box.addWidget(add_fct_entry_btn)
  1496. remove_entry_btn = FCButton(_("Delete Tool from DB"))
  1497. remove_entry_btn.setToolTip(
  1498. _("Remove a selection of tools in the Tools Database.")
  1499. )
  1500. self.buttons_box.addWidget(remove_entry_btn)
  1501. export_db_btn = FCButton(_("Export DB"))
  1502. export_db_btn.setToolTip(
  1503. _("Save the Tools Database to a custom text file.")
  1504. )
  1505. self.buttons_box.addWidget(export_db_btn)
  1506. import_db_btn = FCButton(_("Import DB"))
  1507. import_db_btn.setToolTip(
  1508. _("Load the Tools Database information's from a custom text file.")
  1509. )
  1510. self.buttons_box.addWidget(import_db_btn)
  1511. self.save_db_btn = FCButton(_("Save DB"))
  1512. self.save_db_btn.setToolTip(
  1513. _("Save the Tools Database information's.")
  1514. )
  1515. self.buttons_box.addWidget(self.save_db_btn)
  1516. self.add_tool_from_db = FCButton(_("Transfer the Tool"))
  1517. self.add_tool_from_db.setToolTip(
  1518. _("Insert a new tool in the Tools Table of the\n"
  1519. "object/application tool after selecting a tool\n"
  1520. "in the Tools Database.")
  1521. )
  1522. self.add_tool_from_db.setStyleSheet("""
  1523. QPushButton
  1524. {
  1525. font-weight: bold;
  1526. color: green;
  1527. }
  1528. """)
  1529. self.add_tool_from_db.hide()
  1530. self.cancel_tool_from_db = FCButton(_("Cancel"))
  1531. self.cancel_tool_from_db.hide()
  1532. hlay = QtWidgets.QHBoxLayout()
  1533. tree_layout.addLayout(hlay)
  1534. hlay.addWidget(self.add_tool_from_db)
  1535. hlay.addWidget(self.cancel_tool_from_db)
  1536. # hlay.addStretch()
  1537. # ##############################################################################
  1538. # ##############################################################################
  1539. # ########## SETUP THE DICTIONARIES THAT HOLD THE WIDGETS #####################
  1540. # ##############################################################################
  1541. # ##############################################################################
  1542. self.form_fields = {
  1543. # Basic
  1544. "name": self.name_entry,
  1545. "tooldia": self.dia_entry,
  1546. "tool_type": self.shape_combo,
  1547. "cutz": self.cutz_entry,
  1548. "multidepth": self.multidepth_cb,
  1549. "depthperpass": self.multidepth_entry,
  1550. "travelz": self.travelz_entry,
  1551. "feedrate": self.frxy_entry,
  1552. "feedrate_z": self.frz_entry,
  1553. "spindlespeed": self.spindle_entry,
  1554. "dwell": self.dwell_cb,
  1555. "dwelltime": self.dwelltime_entry,
  1556. # Advanced
  1557. "type": self.type_combo,
  1558. "offset": self.tooloffset_combo,
  1559. "offset_value": self.custom_offset_entry,
  1560. "vtipdia": self.vdia_entry,
  1561. "vtipangle": self.vangle_entry,
  1562. "feedrate_rapid": self.frapids_entry,
  1563. "extracut": self.ecut_cb,
  1564. "extracut_length": self.ecut_length_entry,
  1565. # NCC
  1566. "tools_nccoperation": self.op_radio,
  1567. "tools_nccmilling_type": self.milling_type_radio,
  1568. "tools_nccoverlap": self.ncc_overlap_entry,
  1569. "tools_nccmargin": self.ncc_margin_entry,
  1570. "tools_nccmethod": self.ncc_method_combo,
  1571. "tools_nccconnect": self.ncc_connect_cb,
  1572. "tools_ncccontour": self.ncc_contour_cb,
  1573. "tools_ncc_offset_choice": self.ncc_choice_offset_cb,
  1574. "tools_ncc_offset_value": self.ncc_offset_spinner,
  1575. # Paint
  1576. "tools_paintoverlap": self.paintoverlap_entry,
  1577. "tools_paintmargin": self.paintmargin_entry,
  1578. "tools_paintmethod": self.paintmethod_combo,
  1579. "tools_pathconnect": self.pathconnect_cb,
  1580. "tools_paintcontour": self.paintcontour_cb,
  1581. # Isolation
  1582. "tools_iso_passes": self.passes_entry,
  1583. "tools_iso_overlap": self.iso_overlap_entry,
  1584. "tools_iso_milling_type": self.milling_type_radio,
  1585. "tools_iso_follow": self.follow_cb,
  1586. "tools_iso_isotype": self.iso_type_radio
  1587. }
  1588. self.name2option = {
  1589. # Basic
  1590. "gdb_name": "name",
  1591. "gdb_dia": "tooldia",
  1592. "gdb_shape": "tool_type",
  1593. "gdb_cutz": "cutz",
  1594. "gdb_multidepth": "multidepth",
  1595. "gdb_multidepth_entry": "depthperpass",
  1596. "gdb_travel": "travelz",
  1597. "gdb_frxy": "feedrate",
  1598. "gdb_frz": "feedrate_z",
  1599. "gdb_spindle": "spindlespeed",
  1600. "gdb_dwell": "dwell",
  1601. "gdb_dwelltime": "dwelltime",
  1602. # Advanced
  1603. "gdb_type": "type",
  1604. "gdb_tool_offset": "offset",
  1605. "gdb_custom_offset": "offset_value",
  1606. "gdb_vdia": "vtipdia",
  1607. "gdb_vangle": "vtipangle",
  1608. "gdb_frapids": "feedrate_rapid",
  1609. "gdb_ecut": "extracut",
  1610. "gdb_ecut_length": "extracut_length",
  1611. # NCC
  1612. "gdb_n_operation": "tools_nccoperation",
  1613. "gdb_n_overlap": "tools_nccoverlap",
  1614. "gdb_n_margin": "tools_nccmargin",
  1615. "gdb_n_method": "tools_nccmethod",
  1616. "gdb_n_connect": "tools_nccconnect",
  1617. "gdb_n_contour": "tools_ncccontour",
  1618. "gdb_n_offset": "tools_ncc_offset_choice",
  1619. "gdb_n_offset_value": "tools_ncc_offset_value",
  1620. "gdb_n_milling_type": "tools_nccmilling_type",
  1621. # Paint
  1622. 'gdb_p_overlap': "tools_paintoverlap",
  1623. 'gdb_p_margin': "tools_paintmargin",
  1624. 'gdb_p_method': "tools_paintmethod",
  1625. 'gdb_p_connect': "tools_pathconnect",
  1626. 'gdb_p_contour': "tools_paintcontour",
  1627. # Isolation
  1628. "gdb_i_passes": "tools_iso_passes",
  1629. "gdb_i_overlap": "tools_iso_overlap",
  1630. "gdb_i_milling_type": "tools_iso_milling_type",
  1631. "gdb_i_follow": "tools_iso_follow",
  1632. "gdb_i_iso_type": "tools_iso_isotype"
  1633. }
  1634. self.current_toolid = None
  1635. # variable to show if double clicking and item will trigger adding a tool from DB
  1636. self.ok_to_add = False
  1637. # ##############################################################################
  1638. # ######################## SIGNALS #############################################
  1639. # ##############################################################################
  1640. add_entry_btn.clicked.connect(self.on_tool_add)
  1641. remove_entry_btn.clicked.connect(self.on_tool_delete)
  1642. export_db_btn.clicked.connect(self.on_export_tools_db_file)
  1643. import_db_btn.clicked.connect(self.on_import_tools_db_file)
  1644. self.save_db_btn.clicked.connect(self.on_save_db_btn_click)
  1645. # closebtn.clicked.connect(self.accept)
  1646. self.add_tool_from_db.clicked.connect(self.on_tool_requested_from_app)
  1647. self.cancel_tool_from_db.clicked.connect(self.on_cancel_tool)
  1648. # self.tree_widget.selectionModel().selectionChanged.connect(self.on_list_selection_change)
  1649. self.tree_widget.currentItemChanged.connect(self.on_list_selection_change)
  1650. self.tree_widget.itemChanged.connect(self.on_list_item_edited)
  1651. self.tree_widget.customContextMenuRequested.connect(self.on_menu_request)
  1652. self.tree_widget.itemDoubleClicked.connect(self.on_item_double_clicked)
  1653. self.setup_db_ui()
  1654. def on_menu_request(self, pos):
  1655. menu = QtWidgets.QMenu()
  1656. add_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/plus16.png'), _("Add to DB"))
  1657. add_tool.triggered.connect(self.on_tool_add)
  1658. copy_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/copy16.png'), _("Copy from DB"))
  1659. copy_tool.triggered.connect(self.on_tool_copy)
  1660. delete_tool = menu.addAction(QtGui.QIcon(self.app.resource_location + '/delete32.png'), _("Delete from DB"))
  1661. delete_tool.triggered.connect(self.on_tool_delete)
  1662. # tree_item = self.tree_widget.itemAt(pos)
  1663. menu.exec(self.tree_widget.viewport().mapToGlobal(pos))
  1664. def on_item_double_clicked(self, item, column):
  1665. if column == 0 and self.ok_to_add is True:
  1666. self.ok_to_add = False
  1667. self.on_tool_requested_from_app()
  1668. def on_list_selection_change(self, current, previous):
  1669. # for idx in current.indexes():
  1670. # print(idx.data())
  1671. # print(current.text(0))
  1672. self.current_toolid = int(current.text(0))
  1673. self.storage_to_form(self.db_tool_dict[current.text(0)])
  1674. def on_list_item_edited(self, item, column):
  1675. if column == 0:
  1676. return
  1677. self.name_entry.set_value(item.text(1))
  1678. def storage_to_form(self, dict_storage):
  1679. for form_key in self.form_fields:
  1680. for storage_key in dict_storage:
  1681. if form_key == storage_key:
  1682. try:
  1683. self.form_fields[form_key].set_value(dict_storage[form_key])
  1684. except Exception as e:
  1685. print(str(e))
  1686. if storage_key == 'data':
  1687. for data_key in dict_storage[storage_key]:
  1688. if form_key == data_key:
  1689. try:
  1690. self.form_fields[form_key].set_value(dict_storage['data'][data_key])
  1691. except Exception as e:
  1692. print(str(e))
  1693. def form_to_storage(self, tool):
  1694. self.blockSignals(True)
  1695. widget_changed = self.sender()
  1696. wdg_objname = widget_changed.objectName()
  1697. option_changed = self.name2option[wdg_objname]
  1698. tooluid_item = int(tool)
  1699. for tooluid_key, tooluid_val in self.db_tool_dict.items():
  1700. if int(tooluid_key) == tooluid_item:
  1701. new_option_value = self.form_fields[option_changed].get_value()
  1702. if option_changed in tooluid_val:
  1703. tooluid_val[option_changed] = new_option_value
  1704. if option_changed in tooluid_val['data']:
  1705. tooluid_val['data'][option_changed] = new_option_value
  1706. self.blockSignals(False)
  1707. def setup_db_ui(self):
  1708. filename = self.app.data_path + '\geo_tools_db.FlatDB'
  1709. # load the database tools from the file
  1710. try:
  1711. with open(filename) as f:
  1712. tools = f.read()
  1713. except IOError:
  1714. self.app.log.error("Could not load tools DB file.")
  1715. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  1716. return
  1717. try:
  1718. self.db_tool_dict = json.loads(tools)
  1719. except Exception:
  1720. e = sys.exc_info()[0]
  1721. self.app.log.error(str(e))
  1722. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  1723. return
  1724. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  1725. self.build_db_ui()
  1726. def build_db_ui(self):
  1727. self.ui_disconnect()
  1728. nr_crt = 0
  1729. parent = self.tree_widget
  1730. self.tree_widget.blockSignals(True)
  1731. self.tree_widget.clear()
  1732. self.tree_widget.blockSignals(False)
  1733. for toolid, dict_val in self.db_tool_dict.items():
  1734. row = nr_crt
  1735. nr_crt += 1
  1736. t_name = dict_val['name']
  1737. try:
  1738. # self.add_tool_table_line(row, name=t_name, tooldict=dict_val)
  1739. self.tree_widget.blockSignals(True)
  1740. try:
  1741. self.tree_widget.addParentEditable(parent=parent, title=[str(row+1), t_name], editable=True)
  1742. except Exception as e:
  1743. print('FlatCAMCoomn.ToolDB2.build_db_ui() -> ', str(e))
  1744. self.tree_widget.blockSignals(False)
  1745. except Exception as e:
  1746. self.app.log.debug("ToolDB.build_db_ui.add_tool_table_line() --> %s" % str(e))
  1747. if self.current_toolid is None or self.current_toolid < 1:
  1748. if self.db_tool_dict:
  1749. self.storage_to_form(self.db_tool_dict['1'])
  1750. # Enable appGUI
  1751. self.basic_box.setEnabled(True)
  1752. self.advanced_box.setEnabled(True)
  1753. self.ncc_box.setEnabled(True)
  1754. self.paint_box.setEnabled(True)
  1755. self.iso_box.setEnabled(True)
  1756. self.tree_widget.setCurrentItem(self.tree_widget.topLevelItem(0))
  1757. # self.tree_widget.setFocus()
  1758. else:
  1759. # Disable appGUI
  1760. self.basic_box.setEnabled(False)
  1761. self.advanced_box.setEnabled(False)
  1762. self.ncc_box.setEnabled(False)
  1763. self.paint_box.setEnabled(False)
  1764. self.iso_box.setEnabled(False)
  1765. else:
  1766. self.storage_to_form(self.db_tool_dict[str(self.current_toolid)])
  1767. self.ui_connect()
  1768. def on_tool_add(self):
  1769. """
  1770. Add a tool in the DB Tool Table
  1771. :return: None
  1772. """
  1773. default_data = {}
  1774. default_data.update({
  1775. "plot": True,
  1776. "cutz": float(self.app.defaults["geometry_cutz"]),
  1777. "multidepth": self.app.defaults["geometry_multidepth"],
  1778. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  1779. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  1780. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  1781. "travelz": float(self.app.defaults["geometry_travelz"]),
  1782. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  1783. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  1784. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  1785. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  1786. "dwell": self.app.defaults["geometry_dwell"],
  1787. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  1788. "ppname_g": self.app.defaults["geometry_ppname_g"],
  1789. "extracut": self.app.defaults["geometry_extracut"],
  1790. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  1791. "toolchange": self.app.defaults["geometry_toolchange"],
  1792. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  1793. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  1794. "startz": self.app.defaults["geometry_startz"],
  1795. "endz": float(self.app.defaults["geometry_endz"]),
  1796. # NCC
  1797. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  1798. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  1799. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  1800. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  1801. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  1802. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  1803. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  1804. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  1805. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  1806. # Paint
  1807. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  1808. "tools_paintmargin": float(self.app.defaults["tools_paintmargin"]),
  1809. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  1810. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  1811. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  1812. # Isolation
  1813. "tools_iso_passes": int(self.app.defaults["tools_iso_passes"]),
  1814. "tools_iso_overlap": float(self.app.defaults["tools_iso_overlap"]),
  1815. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  1816. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  1817. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  1818. })
  1819. temp = []
  1820. for k, v in self.db_tool_dict.items():
  1821. if "new_tool_" in v['name']:
  1822. temp.append(float(v['name'].rpartition('_')[2]))
  1823. if temp:
  1824. new_name = "new_tool_%d" % int(max(temp) + 1)
  1825. else:
  1826. new_name = "new_tool_1"
  1827. dict_elem = {}
  1828. dict_elem['name'] = new_name
  1829. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  1830. dict_elem['tooldia'] = self.app.defaults["geometry_cnctooldia"]
  1831. else:
  1832. try:
  1833. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  1834. tools_diameters = [eval(a) for a in tools_string if a != '']
  1835. dict_elem['tooldia'] = tools_diameters[0] if tools_diameters else 0.0
  1836. except Exception as e:
  1837. self.app.log.debug("ToolDB.on_tool_add() --> %s" % str(e))
  1838. return
  1839. dict_elem['offset'] = 'Path'
  1840. dict_elem['offset_value'] = 0.0
  1841. dict_elem['type'] = 'Rough'
  1842. dict_elem['tool_type'] = 'C1'
  1843. dict_elem['data'] = default_data
  1844. new_toolid = len(self.db_tool_dict) + 1
  1845. self.db_tool_dict[str(new_toolid)] = deepcopy(dict_elem)
  1846. # add the new entry to the Tools DB table
  1847. self.update_storage()
  1848. self.build_db_ui()
  1849. # select the last Tree item just added
  1850. nr_items = self.tree_widget.topLevelItemCount()
  1851. if nr_items:
  1852. last_item = self.tree_widget.topLevelItem(nr_items - 1)
  1853. self.tree_widget.setCurrentItem(last_item)
  1854. last_item.setSelected(True)
  1855. self.app.inform.emit('[success] %s' % _("Tool added to DB."))
  1856. def on_tool_copy(self):
  1857. """
  1858. Copy a selection of Tools in the Tools DB table
  1859. :return:
  1860. """
  1861. new_tool_id = len(self.db_tool_dict)
  1862. for item in self.tree_widget.selectedItems():
  1863. old_tool_id = item.data(0, QtCore.Qt.DisplayRole)
  1864. for toolid, dict_val in list(self.db_tool_dict.items()):
  1865. if int(old_tool_id) == int(toolid):
  1866. new_tool_id += 1
  1867. new_key = str(new_tool_id)
  1868. self.db_tool_dict.update({
  1869. new_key: deepcopy(dict_val)
  1870. })
  1871. self.current_toolid = new_tool_id
  1872. self.update_storage()
  1873. self.build_db_ui()
  1874. # select the last Tree item just added
  1875. nr_items = self.tree_widget.topLevelItemCount()
  1876. if nr_items:
  1877. last_item = self.tree_widget.topLevelItem(nr_items - 1)
  1878. self.tree_widget.setCurrentItem(last_item)
  1879. last_item.setSelected(True)
  1880. self.callback_app()
  1881. self.app.inform.emit('[success] %s' % _("Tool copied from Tools DB."))
  1882. def on_tool_delete(self):
  1883. """
  1884. Delete a selection of Tools in the Tools DB table
  1885. :return:
  1886. """
  1887. for item in self.tree_widget.selectedItems():
  1888. toolname_to_remove = item.data(0, QtCore.Qt.DisplayRole)
  1889. for toolid, dict_val in list(self.db_tool_dict.items()):
  1890. if int(toolname_to_remove) == int(toolid):
  1891. # remove from the storage
  1892. self.db_tool_dict.pop(toolid, None)
  1893. self.current_toolid -= 1
  1894. self.update_storage()
  1895. self.build_db_ui()
  1896. # select the first Tree item
  1897. nr_items = self.tree_widget.topLevelItemCount()
  1898. if nr_items:
  1899. first_item = self.tree_widget.topLevelItem(0)
  1900. self.tree_widget.setCurrentItem(first_item)
  1901. first_item.setSelected(True)
  1902. self.app.inform.emit('[success] %s' % _("Tool removed from Tools DB."))
  1903. def on_export_tools_db_file(self):
  1904. self.app.defaults.report_usage("on_export_tools_db_file")
  1905. self.app.log.debug("on_export_tools_db_file()")
  1906. date = str(datetime.today()).rpartition('.')[0]
  1907. date = ''.join(c for c in date if c not in ':-')
  1908. date = date.replace(' ', '_')
  1909. filter__ = "Text File (*.TXT);;All Files (*.*)"
  1910. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Tools Database"),
  1911. directory='{l_save}/FlatCAM_{n}_{date}'.format(
  1912. l_save=str(self.app.get_last_save_folder()),
  1913. n=_("Tools_Database"),
  1914. date=date),
  1915. ext_filter=filter__)
  1916. filename = str(filename)
  1917. if filename == "":
  1918. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1919. return
  1920. else:
  1921. try:
  1922. f = open(filename, 'w')
  1923. f.close()
  1924. except PermissionError:
  1925. self.app.inform.emit('[WARNING] %s' %
  1926. _("Permission denied, saving not possible.\n"
  1927. "Most likely another app is holding the file open and not accessible."))
  1928. return
  1929. except IOError:
  1930. self.app.log.debug('Creating a new Tools DB file ...')
  1931. f = open(filename, 'w')
  1932. f.close()
  1933. except Exception:
  1934. e = sys.exc_info()[0]
  1935. self.app.log.error("Could not load Tools DB file.")
  1936. self.app.log.error(str(e))
  1937. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  1938. return
  1939. # Save update options
  1940. try:
  1941. # Save Tools DB in a file
  1942. try:
  1943. with open(filename, "w") as f:
  1944. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  1945. except Exception as e:
  1946. self.app.log.debug("App.on_save_tools_db() --> %s" % str(e))
  1947. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  1948. return
  1949. except Exception:
  1950. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  1951. return
  1952. self.app.inform.emit('[success] %s: %s' % (_("Exported Tools DB to"), filename))
  1953. def on_import_tools_db_file(self):
  1954. self.app.defaults.report_usage("on_import_tools_db_file")
  1955. self.app.log.debug("on_import_tools_db_file()")
  1956. filter__ = "Text File (*.TXT);;All Files (*.*)"
  1957. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Tools DB"), filter=filter__)
  1958. if filename == "":
  1959. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1960. else:
  1961. try:
  1962. with open(filename) as f:
  1963. tools_in_db = f.read()
  1964. except IOError:
  1965. self.app.log.error("Could not load Tools DB file.")
  1966. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load Tools DB file."))
  1967. return
  1968. try:
  1969. self.db_tool_dict = json.loads(tools_in_db)
  1970. except Exception:
  1971. e = sys.exc_info()[0]
  1972. self.app.log.error(str(e))
  1973. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  1974. return
  1975. self.app.inform.emit('[success] %s: %s' % (_("Loaded Tools DB from"), filename))
  1976. self.build_db_ui()
  1977. self.update_storage()
  1978. def on_save_tools_db(self, silent=False):
  1979. self.app.log.debug("ToolsDB.on_save_button() --> Saving Tools Database to file.")
  1980. filename = self.app.data_path + "/geo_tools_db.FlatDB"
  1981. # Preferences save, update the color of the Tools DB Tab text
  1982. for idx in range(self.app.ui.plot_tab_area.count()):
  1983. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  1984. self.app.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  1985. self.save_db_btn.setStyleSheet("")
  1986. # Save Tools DB in a file
  1987. try:
  1988. f = open(filename, "w")
  1989. json.dump(self.db_tool_dict, f, default=to_dict, indent=2)
  1990. f.close()
  1991. except Exception as e:
  1992. self.app.log.debug("ToolsDB.on_save_tools_db() --> %s" % str(e))
  1993. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write Tools DB to file."))
  1994. return
  1995. if not silent:
  1996. self.app.inform.emit('[success] %s' % _("Saved Tools DB."))
  1997. def on_save_db_btn_click(self):
  1998. self.app.tools_db_changed_flag = False
  1999. self.on_save_tools_db()
  2000. def on_calculate_tooldia(self):
  2001. if self.shape_combo.get_value() == 'V':
  2002. tip_dia = float(self.vdia_entry.get_value())
  2003. half_tip_angle = float(self.vangle_entry.get_value()) / 2.0
  2004. cut_z = float(self.cutz_entry.get_value())
  2005. cut_z = -cut_z if cut_z < 0 else cut_z
  2006. # calculated tool diameter so the cut_z parameter is obeyed
  2007. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(half_tip_angle)))
  2008. self.dia_entry.set_value(tool_dia)
  2009. def ui_connect(self):
  2010. # make sure that we don't make multiple connections to the widgets
  2011. self.ui_disconnect()
  2012. self.name_entry.editingFinished.connect(self.update_tree_name)
  2013. for key in self.form_fields:
  2014. wdg = self.form_fields[key]
  2015. # FCEntry
  2016. if isinstance(wdg, FCEntry):
  2017. wdg.textChanged.connect(self.update_storage)
  2018. # ComboBox
  2019. if isinstance(wdg, FCComboBox):
  2020. wdg.currentIndexChanged.connect(self.update_storage)
  2021. # CheckBox
  2022. if isinstance(wdg, FCCheckBox):
  2023. wdg.toggled.connect(self.update_storage)
  2024. # FCRadio
  2025. if isinstance(wdg, RadioSet):
  2026. wdg.activated_custom.connect(self.update_storage)
  2027. # SpinBox, DoubleSpinBox
  2028. if isinstance(wdg, FCSpinner) or isinstance(wdg, FCDoubleSpinner):
  2029. wdg.valueChanged.connect(self.update_storage)
  2030. # connect the calculate tooldia method to the controls
  2031. # if the tool shape is 'V' the tool dia will be calculated to obey Cut Z parameter
  2032. self.shape_combo.currentIndexChanged.connect(self.on_calculate_tooldia)
  2033. self.cutz_entry.valueChanged.connect(self.on_calculate_tooldia)
  2034. self.vdia_entry.valueChanged.connect(self.on_calculate_tooldia)
  2035. self.vangle_entry.valueChanged.connect(self.on_calculate_tooldia)
  2036. def ui_disconnect(self):
  2037. try:
  2038. self.name_entry.editingFinished.disconnect(self.update_tree_name)
  2039. except (TypeError, AttributeError):
  2040. pass
  2041. try:
  2042. self.shape_combo.currentIndexChanged.disconnect(self.on_calculate_tooldia)
  2043. except (TypeError, AttributeError):
  2044. pass
  2045. try:
  2046. self.cutz_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2047. except (TypeError, AttributeError):
  2048. pass
  2049. try:
  2050. self.vdia_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2051. except (TypeError, AttributeError):
  2052. pass
  2053. try:
  2054. self.vangle_entry.valueChanged.disconnect(self.on_calculate_tooldia)
  2055. except (TypeError, AttributeError):
  2056. pass
  2057. for key in self.form_fields:
  2058. wdg = self.form_fields[key]
  2059. # FCEntry
  2060. if isinstance(wdg, FCEntry):
  2061. try:
  2062. wdg.textChanged.disconnect(self.update_storage)
  2063. except (TypeError, AttributeError):
  2064. pass
  2065. # ComboBox
  2066. if isinstance(wdg, FCComboBox):
  2067. try:
  2068. wdg.currentIndexChanged.disconnect(self.update_storage)
  2069. except (TypeError, AttributeError):
  2070. pass
  2071. # CheckBox
  2072. if isinstance(wdg, FCCheckBox):
  2073. try:
  2074. wdg.toggled.disconnect(self.update_storage)
  2075. except (TypeError, AttributeError):
  2076. pass
  2077. # FCRadio
  2078. if isinstance(wdg, RadioSet):
  2079. try:
  2080. wdg.activated_custom.disconnect(self.update_storage)
  2081. except (TypeError, AttributeError):
  2082. pass
  2083. # SpinBox, DoubleSpinBox
  2084. if isinstance(wdg, FCSpinner) or isinstance(wdg, FCDoubleSpinner):
  2085. try:
  2086. wdg.valueChanged.disconnect(self.update_storage)
  2087. except (TypeError, AttributeError):
  2088. pass
  2089. def update_tree_name(self):
  2090. val = self.name_entry.get_value()
  2091. item = self.tree_widget.currentItem()
  2092. if item is None:
  2093. return
  2094. # I'm setting the value for the second column (designated by 1) because first column holds the ID
  2095. # and second column holds the Name (this behavior is set in the build_ui method)
  2096. item.setData(1, QtCore.Qt.DisplayRole, val)
  2097. def update_storage(self):
  2098. """
  2099. Update the dictionary that is the storage of the tools 'database'
  2100. :return:
  2101. """
  2102. tool_id = str(self.current_toolid)
  2103. try:
  2104. wdg = self.sender()
  2105. assert isinstance(wdg, QtWidgets.QWidget) or isinstance(wdg, QtWidgets.QAction), \
  2106. "Expected a QWidget got %s" % type(wdg)
  2107. if wdg is None:
  2108. return
  2109. wdg_name = wdg.objectName()
  2110. val = wdg.get_value()
  2111. except AttributeError:
  2112. return
  2113. if wdg_name == "gdb_name":
  2114. self.db_tool_dict[tool_id]['name'] = val
  2115. elif wdg_name == "gdb_dia":
  2116. self.db_tool_dict[tool_id]['tooldia'] = val
  2117. elif wdg_name == "gdb_tool_offset":
  2118. self.db_tool_dict[tool_id]['offset'] = val
  2119. elif wdg_name == "gdb_custom_offset":
  2120. self.db_tool_dict[tool_id]['offset_value'] = val
  2121. elif wdg_name == "gdb_type":
  2122. self.db_tool_dict[tool_id]['type'] = val
  2123. elif wdg_name == "gdb_shape":
  2124. self.db_tool_dict[tool_id]['tool_type'] = val
  2125. else:
  2126. if wdg_name == "gdb_cutz":
  2127. self.db_tool_dict[tool_id]['data']['cutz'] = val
  2128. elif wdg_name == "gdb_multidepth":
  2129. self.db_tool_dict[tool_id]['data']['multidepth'] = val
  2130. elif wdg_name == "gdb_multidepth_entry":
  2131. self.db_tool_dict[tool_id]['data']['depthperpass'] = val
  2132. elif wdg_name == "gdb_travel":
  2133. self.db_tool_dict[tool_id]['data']['travelz'] = val
  2134. elif wdg_name == "gdb_frxy":
  2135. self.db_tool_dict[tool_id]['data']['feedrate'] = val
  2136. elif wdg_name == "gdb_frz":
  2137. self.db_tool_dict[tool_id]['data']['feedrate_z'] = val
  2138. elif wdg_name == "gdb_spindle":
  2139. self.db_tool_dict[tool_id]['data']['spindlespeed'] = val
  2140. elif wdg_name == "gdb_dwell":
  2141. self.db_tool_dict[tool_id]['data']['dwell'] = val
  2142. elif wdg_name == "gdb_dwelltime":
  2143. self.db_tool_dict[tool_id]['data']['dwelltime'] = val
  2144. elif wdg_name == "gdb_vdia":
  2145. self.db_tool_dict[tool_id]['data']['vtipdia'] = val
  2146. elif wdg_name == "gdb_vangle":
  2147. self.db_tool_dict[tool_id]['data']['vtipangle'] = val
  2148. elif wdg_name == "gdb_frapids":
  2149. self.db_tool_dict[tool_id]['data']['feedrate_rapid'] = val
  2150. elif wdg_name == "gdb_ecut":
  2151. self.db_tool_dict[tool_id]['data']['extracut'] = val
  2152. elif wdg_name == "gdb_ecut_length":
  2153. self.db_tool_dict[tool_id]['data']['extracut_length'] = val
  2154. # NCC Tool
  2155. elif wdg_name == "gdb_n_operation":
  2156. self.db_tool_dict[tool_id]['data']['tools_nccoperation'] = val
  2157. elif wdg_name == "gdb_n_overlap":
  2158. self.db_tool_dict[tool_id]['data']['tools_nccoverlap'] = val
  2159. elif wdg_name == "gdb_n_margin":
  2160. self.db_tool_dict[tool_id]['data']['tools_nccmargin'] = val
  2161. elif wdg_name == "gdb_n_method":
  2162. self.db_tool_dict[tool_id]['data']['tools_nccmethod'] = val
  2163. elif wdg_name == "gdb_n_connect":
  2164. self.db_tool_dict[tool_id]['data']['tools_nccconnect'] = val
  2165. elif wdg_name == "gdb_n_contour":
  2166. self.db_tool_dict[tool_id]['data']['tools_ncccontour'] = val
  2167. elif wdg_name == "gdb_n_offset":
  2168. self.db_tool_dict[tool_id]['data']['tools_ncc_offset_choice'] = val
  2169. elif wdg_name == "gdb_n_offset_value":
  2170. self.db_tool_dict[tool_id]['data']['tools_ncc_offset_value'] = val
  2171. elif wdg_name == "gdb_n_milling_type":
  2172. self.db_tool_dict[tool_id]['data']['tools_nccmilling_type'] = val
  2173. # Paint Tool
  2174. elif wdg_name == "gdb_p_overlap":
  2175. self.db_tool_dict[tool_id]['data']['tools_paintoverlap'] = val
  2176. elif wdg_name == "gdb_p_margin":
  2177. self.db_tool_dict[tool_id]['data']['tools_paintmargin'] = val
  2178. elif wdg_name == "gdb_p_method":
  2179. self.db_tool_dict[tool_id]['data']['tools_paintmethod'] = val
  2180. elif wdg_name == "gdb_p_connect":
  2181. self.db_tool_dict[tool_id]['data']['tools_pathconnect'] = val
  2182. elif wdg_name == "gdb_p_contour":
  2183. self.db_tool_dict[tool_id]['data']['tools_paintcontour'] = val
  2184. # Isolation Tool
  2185. elif wdg_name == "gdb_i_passes":
  2186. self.db_tool_dict[tool_id]['data']['tools_iso_passes'] = val
  2187. elif wdg_name == "gdb_i_overlap":
  2188. self.db_tool_dict[tool_id]['data']['tools_iso_overlap'] = val
  2189. elif wdg_name == "gdb_i_milling_type":
  2190. self.db_tool_dict[tool_id]['data']['tools_iso_milling_type'] = val
  2191. elif wdg_name == "gdb_i_follow":
  2192. self.db_tool_dict[tool_id]['data']['tools_iso_follow'] = val
  2193. elif wdg_name == "gdb_i_iso_type":
  2194. self.db_tool_dict[tool_id]['data']['tools_iso_isotype'] = val
  2195. self.callback_app()
  2196. def on_tool_requested_from_app(self):
  2197. if not self.tree_widget.selectedItems():
  2198. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("No Tool/row selected in the Tools Database table"))
  2199. return
  2200. for item in self.tree_widget.selectedItems():
  2201. tool_uid = item.data(0, QtCore.Qt.DisplayRole)
  2202. for key in self.db_tool_dict.keys():
  2203. if str(key) == str(tool_uid):
  2204. selected_tool = self.db_tool_dict[key]
  2205. self.on_tool_request(tool=selected_tool)
  2206. def on_cancel_tool(self):
  2207. for idx in range(self.app.ui.plot_tab_area.count()):
  2208. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2209. wdg = self.app.ui.plot_tab_area.widget(idx)
  2210. wdg.deleteLater()
  2211. self.app.ui.plot_tab_area.removeTab(idx)
  2212. self.app.inform.emit('%s' % _("Cancelled adding tool from DB."))
  2213. # def resize_new_tool_table_widget(self, min_size, max_size):
  2214. # """
  2215. # Resize the table widget responsible for adding new tool in the Tool Database
  2216. #
  2217. # :param min_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  2218. # :param max_size: passed by rangeChanged signal or the self.new_tool_table_widget.horizontalScrollBar()
  2219. # :return:
  2220. # """
  2221. # t_height = self.t_height
  2222. # if max_size > min_size:
  2223. # t_height = self.t_height + self.new_tool_table_widget.verticalScrollBar().height()
  2224. #
  2225. # self.new_tool_table_widget.setMaximumHeight(t_height)
  2226. def closeEvent(self, QCloseEvent):
  2227. super().closeEvent(QCloseEvent)