appDatabase.py 114 KB

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