ToolCalibration.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCDoubleSpinner, EvalEntry, FCCheckBox, OptionalInputSection, FCEntry
  10. from appGUI.GUIElements import FCTable, FCComboBox, RadioSet
  11. from appEditors.AppTextEditor import AppTextEditor
  12. from shapely.geometry import Point
  13. from shapely.geometry.base import *
  14. from shapely.affinity import scale, skew
  15. import math
  16. from datetime import datetime
  17. import logging
  18. from copy import deepcopy
  19. import gettext
  20. import appTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. class ToolCalibration(AppTool):
  27. toolName = _("Calibration Tool")
  28. def __init__(self, app):
  29. AppTool.__init__(self, app)
  30. self.app = app
  31. self.canvas = self.app.plotcanvas
  32. self.decimals = self.app.decimals
  33. # ## Title
  34. title_label = QtWidgets.QLabel("%s" % self.toolName)
  35. title_label.setStyleSheet("""
  36. QLabel
  37. {
  38. font-size: 16px;
  39. font-weight: bold;
  40. }
  41. """)
  42. self.layout.addWidget(title_label)
  43. self.layout.addWidget(QtWidgets.QLabel(''))
  44. # ## Grid Layout
  45. grid_lay = QtWidgets.QGridLayout()
  46. self.layout.addLayout(grid_lay)
  47. grid_lay.setColumnStretch(0, 0)
  48. grid_lay.setColumnStretch(1, 1)
  49. grid_lay.setColumnStretch(2, 0)
  50. self.gcode_title_label = QtWidgets.QLabel('<b>%s:</b>' % _('Parameters'))
  51. self.gcode_title_label.setToolTip(
  52. _("Parameters used when creating the GCode in this tool.")
  53. )
  54. grid_lay.addWidget(self.gcode_title_label, 0, 0, 1, 3)
  55. # Travel Z entry
  56. travelz_lbl = QtWidgets.QLabel('%s:' % _("Travel Z"))
  57. travelz_lbl.setToolTip(
  58. _("Height (Z) for travelling between the points.")
  59. )
  60. self.travelz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  61. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  62. self.travelz_entry.set_precision(self.decimals)
  63. self.travelz_entry.setSingleStep(0.1)
  64. grid_lay.addWidget(travelz_lbl, 1, 0)
  65. grid_lay.addWidget(self.travelz_entry, 1, 1, 1, 2)
  66. # Verification Z entry
  67. verz_lbl = QtWidgets.QLabel('%s:' % _("Verification Z"))
  68. verz_lbl.setToolTip(
  69. _("Height (Z) for checking the point.")
  70. )
  71. self.verz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  72. self.verz_entry.set_range(-9999.9999, 9999.9999)
  73. self.verz_entry.set_precision(self.decimals)
  74. self.verz_entry.setSingleStep(0.1)
  75. grid_lay.addWidget(verz_lbl, 2, 0)
  76. grid_lay.addWidget(self.verz_entry, 2, 1, 1, 2)
  77. # Zero the Z of the verification tool
  78. self.zeroz_cb = FCCheckBox('%s' % _("Zero Z tool"))
  79. self.zeroz_cb.setToolTip(
  80. _("Include a sequence to zero the height (Z)\n"
  81. "of the verification tool.")
  82. )
  83. grid_lay.addWidget(self.zeroz_cb, 3, 0, 1, 3)
  84. # Toolchange Z entry
  85. toolchangez_lbl = QtWidgets.QLabel('%s:' % _("Toolchange Z"))
  86. toolchangez_lbl.setToolTip(
  87. _("Height (Z) for mounting the verification probe.")
  88. )
  89. self.toolchangez_entry = FCDoubleSpinner(callback=self.confirmation_message)
  90. self.toolchangez_entry.set_range(0.0000, 9999.9999)
  91. self.toolchangez_entry.set_precision(self.decimals)
  92. self.toolchangez_entry.setSingleStep(0.1)
  93. grid_lay.addWidget(toolchangez_lbl, 4, 0)
  94. grid_lay.addWidget(self.toolchangez_entry, 4, 1, 1, 2)
  95. # Toolchange X-Y entry
  96. toolchangexy_lbl = QtWidgets.QLabel('%s:' % _('Toolchange X-Y'))
  97. toolchangexy_lbl.setToolTip(
  98. _("Toolchange X,Y position.\n"
  99. "If no value is entered then the current\n"
  100. "(x, y) point will be used,")
  101. )
  102. self.toolchange_xy_entry = FCEntry()
  103. grid_lay.addWidget(toolchangexy_lbl, 5, 0)
  104. grid_lay.addWidget(self.toolchange_xy_entry, 5, 1, 1, 2)
  105. self.z_ois = OptionalInputSection(
  106. self.zeroz_cb,
  107. [
  108. toolchangez_lbl,
  109. self.toolchangez_entry,
  110. toolchangexy_lbl,
  111. self.toolchange_xy_entry
  112. ]
  113. )
  114. separator_line1 = QtWidgets.QFrame()
  115. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  116. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  117. grid_lay.addWidget(separator_line1, 6, 0, 1, 3)
  118. # Second point choice
  119. second_point_lbl = QtWidgets.QLabel('%s:' % _("Second point"))
  120. second_point_lbl.setToolTip(
  121. _("Second point in the Gcode verification can be:\n"
  122. "- top-left -> the user will align the PCB vertically\n"
  123. "- bottom-right -> the user will align the PCB horizontally")
  124. )
  125. self.second_point_radio = RadioSet([{'label': _('Top-Left'), 'value': 'tl'},
  126. {'label': _('Bottom-Right'), 'value': 'br'}],
  127. orientation='vertical')
  128. grid_lay.addWidget(second_point_lbl, 7, 0)
  129. grid_lay.addWidget(self.second_point_radio, 7, 1, 1, 2)
  130. separator_line1 = QtWidgets.QFrame()
  131. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  132. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  133. grid_lay.addWidget(separator_line1, 8, 0, 1, 3)
  134. grid_lay.addWidget(QtWidgets.QLabel(''), 9, 0, 1, 3)
  135. step_1 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 1: Acquire Calibration Points"))
  136. step_1.setToolTip(
  137. _("Pick four points by clicking on canvas.\n"
  138. "Those four points should be in the four\n"
  139. "(as much as possible) corners of the object.")
  140. )
  141. grid_lay.addWidget(step_1, 10, 0, 1, 3)
  142. self.cal_source_lbl = QtWidgets.QLabel("<b>%s:</b>" % _("Source Type"))
  143. self.cal_source_lbl.setToolTip(_("The source of calibration points.\n"
  144. "It can be:\n"
  145. "- Object -> click a hole geo for Excellon or a pad for Gerber\n"
  146. "- Free -> click freely on canvas to acquire the calibration points"))
  147. self.cal_source_radio = RadioSet([{'label': _('Object'), 'value': 'object'},
  148. {'label': _('Free'), 'value': 'free'}],
  149. stretch=False)
  150. grid_lay.addWidget(self.cal_source_lbl, 11, 0)
  151. grid_lay.addWidget(self.cal_source_radio, 11, 1, 1, 2)
  152. self.obj_type_label = QtWidgets.QLabel("%s:" % _("Object Type"))
  153. self.obj_type_combo = FCComboBox()
  154. self.obj_type_combo.addItem(_("Gerber"))
  155. self.obj_type_combo.addItem(_("Excellon"))
  156. self.obj_type_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  157. self.obj_type_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/drill16.png"))
  158. grid_lay.addWidget(self.obj_type_label, 12, 0)
  159. grid_lay.addWidget(self.obj_type_combo, 12, 1, 1, 2)
  160. self.object_combo = FCComboBox()
  161. self.object_combo.setModel(self.app.collection)
  162. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  163. self.object_combo.is_last = True
  164. self.object_label = QtWidgets.QLabel("%s:" % _("Source object selection"))
  165. self.object_label.setToolTip(
  166. _("FlatCAM Object to be used as a source for reference points.")
  167. )
  168. grid_lay.addWidget(self.object_label, 13, 0, 1, 3)
  169. grid_lay.addWidget(self.object_combo, 14, 0, 1, 3)
  170. self.points_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Calibration Points'))
  171. self.points_table_label.setToolTip(
  172. _("Contain the expected calibration points and the\n"
  173. "ones measured.")
  174. )
  175. grid_lay.addWidget(self.points_table_label, 15, 0, 1, 3)
  176. self.points_table = FCTable()
  177. self.points_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  178. # self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  179. grid_lay.addWidget(self.points_table, 16, 0, 1, 3)
  180. self.points_table.setColumnCount(4)
  181. self.points_table.setHorizontalHeaderLabels(
  182. [
  183. '#',
  184. _("Name"),
  185. _("Target"),
  186. _("Found Delta")
  187. ]
  188. )
  189. self.points_table.setRowCount(8)
  190. row = 0
  191. # BOTTOM LEFT
  192. id_item_1 = QtWidgets.QTableWidgetItem('%d' % 1)
  193. flags = QtCore.Qt.ItemIsEnabled
  194. id_item_1.setFlags(flags)
  195. self.points_table.setItem(row, 0, id_item_1) # Tool name/id
  196. self.bottom_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Left X'))
  197. self.points_table.setCellWidget(row, 1, self.bottom_left_coordx_lbl)
  198. self.bottom_left_coordx_tgt = EvalEntry()
  199. self.points_table.setCellWidget(row, 2, self.bottom_left_coordx_tgt)
  200. self.bottom_left_coordx_tgt.setReadOnly(True)
  201. self.bottom_left_coordx_found = EvalEntry()
  202. self.points_table.setCellWidget(row, 3, self.bottom_left_coordx_found)
  203. row += 1
  204. self.bottom_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Left Y'))
  205. self.points_table.setCellWidget(row, 1, self.bottom_left_coordy_lbl)
  206. self.bottom_left_coordy_tgt = EvalEntry()
  207. self.points_table.setCellWidget(row, 2, self.bottom_left_coordy_tgt)
  208. self.bottom_left_coordy_tgt.setReadOnly(True)
  209. self.bottom_left_coordy_found = EvalEntry()
  210. self.points_table.setCellWidget(row, 3, self.bottom_left_coordy_found)
  211. self.bottom_left_coordx_found.setDisabled(True)
  212. self.bottom_left_coordy_found.setDisabled(True)
  213. row += 1
  214. # BOTTOM RIGHT
  215. id_item_2 = QtWidgets.QTableWidgetItem('%d' % 2)
  216. flags = QtCore.Qt.ItemIsEnabled
  217. id_item_2.setFlags(flags)
  218. self.points_table.setItem(row, 0, id_item_2) # Tool name/id
  219. self.bottom_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Right X'))
  220. self.points_table.setCellWidget(row, 1, self.bottom_right_coordx_lbl)
  221. self.bottom_right_coordx_tgt = EvalEntry()
  222. self.points_table.setCellWidget(row, 2, self.bottom_right_coordx_tgt)
  223. self.bottom_right_coordx_tgt.setReadOnly(True)
  224. self.bottom_right_coordx_found = EvalEntry()
  225. self.points_table.setCellWidget(row, 3, self.bottom_right_coordx_found)
  226. row += 1
  227. self.bottom_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Right Y'))
  228. self.points_table.setCellWidget(row, 1, self.bottom_right_coordy_lbl)
  229. self.bottom_right_coordy_tgt = EvalEntry()
  230. self.points_table.setCellWidget(row, 2, self.bottom_right_coordy_tgt)
  231. self.bottom_right_coordy_tgt.setReadOnly(True)
  232. self.bottom_right_coordy_found = EvalEntry()
  233. self.points_table.setCellWidget(row, 3, self.bottom_right_coordy_found)
  234. row += 1
  235. # TOP LEFT
  236. id_item_3 = QtWidgets.QTableWidgetItem('%d' % 3)
  237. flags = QtCore.Qt.ItemIsEnabled
  238. id_item_3.setFlags(flags)
  239. self.points_table.setItem(row, 0, id_item_3) # Tool name/id
  240. self.top_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Left X'))
  241. self.points_table.setCellWidget(row, 1, self.top_left_coordx_lbl)
  242. self.top_left_coordx_tgt = EvalEntry()
  243. self.points_table.setCellWidget(row, 2, self.top_left_coordx_tgt)
  244. self.top_left_coordx_tgt.setReadOnly(True)
  245. self.top_left_coordx_found = EvalEntry()
  246. self.points_table.setCellWidget(row, 3, self.top_left_coordx_found)
  247. row += 1
  248. self.top_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Left Y'))
  249. self.points_table.setCellWidget(row, 1, self.top_left_coordy_lbl)
  250. self.top_left_coordy_tgt = EvalEntry()
  251. self.points_table.setCellWidget(row, 2, self.top_left_coordy_tgt)
  252. self.top_left_coordy_tgt.setReadOnly(True)
  253. self.top_left_coordy_found = EvalEntry()
  254. self.points_table.setCellWidget(row, 3, self.top_left_coordy_found)
  255. row += 1
  256. # TOP RIGHT
  257. id_item_4 = QtWidgets.QTableWidgetItem('%d' % 4)
  258. flags = QtCore.Qt.ItemIsEnabled
  259. id_item_4.setFlags(flags)
  260. self.points_table.setItem(row, 0, id_item_4) # Tool name/id
  261. self.top_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Right X'))
  262. self.points_table.setCellWidget(row, 1, self.top_right_coordx_lbl)
  263. self.top_right_coordx_tgt = EvalEntry()
  264. self.points_table.setCellWidget(row, 2, self.top_right_coordx_tgt)
  265. self.top_right_coordx_tgt.setReadOnly(True)
  266. self.top_right_coordx_found = EvalEntry()
  267. self.top_right_coordx_found.setDisabled(True)
  268. self.points_table.setCellWidget(row, 3, self.top_right_coordx_found)
  269. row += 1
  270. self.top_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Right Y'))
  271. self.points_table.setCellWidget(row, 1, self.top_right_coordy_lbl)
  272. self.top_right_coordy_tgt = EvalEntry()
  273. self.points_table.setCellWidget(row, 2, self.top_right_coordy_tgt)
  274. self.top_right_coordy_tgt.setReadOnly(True)
  275. self.top_right_coordy_found = EvalEntry()
  276. self.top_right_coordy_found.setDisabled(True)
  277. self.points_table.setCellWidget(row, 3, self.top_right_coordy_found)
  278. vertical_header = self.points_table.verticalHeader()
  279. vertical_header.hide()
  280. self.points_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  281. horizontal_header = self.points_table.horizontalHeader()
  282. horizontal_header.setMinimumSectionSize(10)
  283. horizontal_header.setDefaultSectionSize(70)
  284. self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  285. # for x in range(4):
  286. # self.points_table.resizeColumnToContents(x)
  287. self.points_table.resizeColumnsToContents()
  288. self.points_table.resizeRowsToContents()
  289. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  290. horizontal_header.resizeSection(0, 20)
  291. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Fixed)
  292. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  293. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
  294. self.points_table.setMinimumHeight(self.points_table.getHeight() + 2)
  295. self.points_table.setMaximumHeight(self.points_table.getHeight() + 3)
  296. # ## Get Points Button
  297. self.start_button = QtWidgets.QPushButton(_("Get Points"))
  298. self.start_button.setToolTip(
  299. _("Pick four points by clicking on canvas if the source choice\n"
  300. "is 'free' or inside the object geometry if the source is 'object'.\n"
  301. "Those four points should be in the four squares of\n"
  302. "the object.")
  303. )
  304. self.start_button.setStyleSheet("""
  305. QPushButton
  306. {
  307. font-weight: bold;
  308. }
  309. """)
  310. grid_lay.addWidget(self.start_button, 17, 0, 1, 3)
  311. separator_line = QtWidgets.QFrame()
  312. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  313. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  314. grid_lay.addWidget(separator_line, 18, 0, 1, 3)
  315. grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  316. # STEP 2 #
  317. step_2 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 2: Verification GCode"))
  318. step_2.setToolTip(
  319. _("Generate GCode file to locate and align the PCB by using\n"
  320. "the four points acquired above.\n"
  321. "The points sequence is:\n"
  322. "- first point -> set the origin\n"
  323. "- second point -> alignment point. Can be: top-left or bottom-right.\n"
  324. "- third point -> check point. Can be: top-left or bottom-right.\n"
  325. "- forth point -> final verification point. Just for evaluation.")
  326. )
  327. grid_lay.addWidget(step_2, 20, 0, 1, 3)
  328. # ## GCode Button
  329. self.gcode_button = QtWidgets.QPushButton(_("Generate GCode"))
  330. self.gcode_button.setToolTip(
  331. _("Generate GCode file to locate and align the PCB by using\n"
  332. "the four points acquired above.\n"
  333. "The points sequence is:\n"
  334. "- first point -> set the origin\n"
  335. "- second point -> alignment point. Can be: top-left or bottom-right.\n"
  336. "- third point -> check point. Can be: top-left or bottom-right.\n"
  337. "- forth point -> final verification point. Just for evaluation.")
  338. )
  339. self.gcode_button.setStyleSheet("""
  340. QPushButton
  341. {
  342. font-weight: bold;
  343. }
  344. """)
  345. grid_lay.addWidget(self.gcode_button, 21, 0, 1, 3)
  346. separator_line1 = QtWidgets.QFrame()
  347. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  348. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  349. grid_lay.addWidget(separator_line1, 22, 0, 1, 3)
  350. grid_lay.addWidget(QtWidgets.QLabel(''), 23, 0, 1, 3)
  351. # STEP 3 #
  352. step_3 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 3: Adjustments"))
  353. step_3.setToolTip(
  354. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  355. "found when checking the PCB pattern. The differences must be filled\n"
  356. "in the fields Found (Delta).")
  357. )
  358. grid_lay.addWidget(step_3, 24, 0, 1, 3)
  359. # ## Factors Button
  360. self.generate_factors_button = QtWidgets.QPushButton(_("Calculate Factors"))
  361. self.generate_factors_button.setToolTip(
  362. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  363. "found when checking the PCB pattern. The differences must be filled\n"
  364. "in the fields Found (Delta).")
  365. )
  366. self.generate_factors_button.setStyleSheet("""
  367. QPushButton
  368. {
  369. font-weight: bold;
  370. }
  371. """)
  372. grid_lay.addWidget(self.generate_factors_button, 25, 0, 1, 3)
  373. separator_line1 = QtWidgets.QFrame()
  374. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  375. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  376. grid_lay.addWidget(separator_line1, 26, 0, 1, 3)
  377. grid_lay.addWidget(QtWidgets.QLabel(''), 27, 0, 1, 3)
  378. # STEP 4 #
  379. step_4 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 4: Adjusted GCode"))
  380. step_4.setToolTip(
  381. _("Generate verification GCode file adjusted with\n"
  382. "the factors above.")
  383. )
  384. grid_lay.addWidget(step_4, 28, 0, 1, 3)
  385. self.scalex_label = QtWidgets.QLabel(_("Scale Factor X:"))
  386. self.scalex_label.setToolTip(
  387. _("Factor for Scale action over X axis.")
  388. )
  389. self.scalex_entry = FCDoubleSpinner(callback=self.confirmation_message)
  390. self.scalex_entry.set_range(0, 9999.9999)
  391. self.scalex_entry.set_precision(self.decimals)
  392. self.scalex_entry.setSingleStep(0.1)
  393. grid_lay.addWidget(self.scalex_label, 29, 0)
  394. grid_lay.addWidget(self.scalex_entry, 29, 1, 1, 2)
  395. self.scaley_label = QtWidgets.QLabel(_("Scale Factor Y:"))
  396. self.scaley_label.setToolTip(
  397. _("Factor for Scale action over Y axis.")
  398. )
  399. self.scaley_entry = FCDoubleSpinner(callback=self.confirmation_message)
  400. self.scaley_entry.set_range(0, 9999.9999)
  401. self.scaley_entry.set_precision(self.decimals)
  402. self.scaley_entry.setSingleStep(0.1)
  403. grid_lay.addWidget(self.scaley_label, 30, 0)
  404. grid_lay.addWidget(self.scaley_entry, 30, 1, 1, 2)
  405. self.scale_button = QtWidgets.QPushButton(_("Apply Scale Factors"))
  406. self.scale_button.setToolTip(
  407. _("Apply Scale factors on the calibration points.")
  408. )
  409. self.scale_button.setStyleSheet("""
  410. QPushButton
  411. {
  412. font-weight: bold;
  413. }
  414. """)
  415. grid_lay.addWidget(self.scale_button, 31, 0, 1, 3)
  416. self.skewx_label = QtWidgets.QLabel(_("Skew Angle X:"))
  417. self.skewx_label.setToolTip(
  418. _("Angle for Skew action, in degrees.\n"
  419. "Float number between -360 and 359.")
  420. )
  421. self.skewx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  422. self.skewx_entry.set_range(-360, 360)
  423. self.skewx_entry.set_precision(self.decimals)
  424. self.skewx_entry.setSingleStep(0.1)
  425. grid_lay.addWidget(self.skewx_label, 32, 0)
  426. grid_lay.addWidget(self.skewx_entry, 32, 1, 1, 2)
  427. self.skewy_label = QtWidgets.QLabel(_("Skew Angle Y:"))
  428. self.skewy_label.setToolTip(
  429. _("Angle for Skew action, in degrees.\n"
  430. "Float number between -360 and 359.")
  431. )
  432. self.skewy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  433. self.skewy_entry.set_range(-360, 360)
  434. self.skewy_entry.set_precision(self.decimals)
  435. self.skewy_entry.setSingleStep(0.1)
  436. grid_lay.addWidget(self.skewy_label, 33, 0)
  437. grid_lay.addWidget(self.skewy_entry, 33, 1, 1, 2)
  438. self.skew_button = QtWidgets.QPushButton(_("Apply Skew Factors"))
  439. self.skew_button.setToolTip(
  440. _("Apply Skew factors on the calibration points.")
  441. )
  442. self.skew_button.setStyleSheet("""
  443. QPushButton
  444. {
  445. font-weight: bold;
  446. }
  447. """)
  448. grid_lay.addWidget(self.skew_button, 34, 0, 1, 3)
  449. # final_factors_lbl = QtWidgets.QLabel('<b>%s</b>' % _("Final Factors"))
  450. # final_factors_lbl.setToolTip(
  451. # _("Generate verification GCode file adjusted with\n"
  452. # "the factors above.")
  453. # )
  454. # grid_lay.addWidget(final_factors_lbl, 27, 0, 1, 3)
  455. #
  456. # self.fin_scalex_label = QtWidgets.QLabel(_("Scale Factor X:"))
  457. # self.fin_scalex_label.setToolTip(
  458. # _("Final factor for Scale action over X axis.")
  459. # )
  460. # self.fin_scalex_entry = FCDoubleSpinner(callback=self.confirmation_message)
  461. # self.fin_scalex_entry.set_range(0, 9999.9999)
  462. # self.fin_scalex_entry.set_precision(self.decimals)
  463. # self.fin_scalex_entry.setSingleStep(0.1)
  464. #
  465. # grid_lay.addWidget(self.fin_scalex_label, 28, 0)
  466. # grid_lay.addWidget(self.fin_scalex_entry, 28, 1, 1, 2)
  467. #
  468. # self.fin_scaley_label = QtWidgets.QLabel(_("Scale Factor Y:"))
  469. # self.fin_scaley_label.setToolTip(
  470. # _("Final factor for Scale action over Y axis.")
  471. # )
  472. # self.fin_scaley_entry = FCDoubleSpinner(callback=self.confirmation_message)
  473. # self.fin_scaley_entry.set_range(0, 9999.9999)
  474. # self.fin_scaley_entry.set_precision(self.decimals)
  475. # self.fin_scaley_entry.setSingleStep(0.1)
  476. #
  477. # grid_lay.addWidget(self.fin_scaley_label, 29, 0)
  478. # grid_lay.addWidget(self.fin_scaley_entry, 29, 1, 1, 2)
  479. #
  480. # self.fin_skewx_label = QtWidgets.QLabel(_("Skew Angle X:"))
  481. # self.fin_skewx_label.setToolTip(
  482. # _("Final value for angle for Skew action, in degrees.\n"
  483. # "Float number between -360 and 359.")
  484. # )
  485. # self.fin_skewx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  486. # self.fin_skewx_entry.set_range(-360, 360)
  487. # self.fin_skewx_entry.set_precision(self.decimals)
  488. # self.fin_skewx_entry.setSingleStep(0.1)
  489. #
  490. # grid_lay.addWidget(self.fin_skewx_label, 30, 0)
  491. # grid_lay.addWidget(self.fin_skewx_entry, 30, 1, 1, 2)
  492. #
  493. # self.fin_skewy_label = QtWidgets.QLabel(_("Skew Angle Y:"))
  494. # self.fin_skewy_label.setToolTip(
  495. # _("Final value for angle for Skew action, in degrees.\n"
  496. # "Float number between -360 and 359.")
  497. # )
  498. # self.fin_skewy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  499. # self.fin_skewy_entry.set_range(-360, 360)
  500. # self.fin_skewy_entry.set_precision(self.decimals)
  501. # self.fin_skewy_entry.setSingleStep(0.1)
  502. #
  503. # grid_lay.addWidget(self.fin_skewy_label, 31, 0)
  504. # grid_lay.addWidget(self.fin_skewy_entry, 31, 1, 1, 2)
  505. # ## Adjusted GCode Button
  506. self.adj_gcode_button = QtWidgets.QPushButton(_("Generate Adjusted GCode"))
  507. self.adj_gcode_button.setToolTip(
  508. _("Generate verification GCode file adjusted with\n"
  509. "the factors set above.\n"
  510. "The GCode parameters can be readjusted\n"
  511. "before clicking this button.")
  512. )
  513. self.adj_gcode_button.setStyleSheet("""
  514. QPushButton
  515. {
  516. font-weight: bold;
  517. }
  518. """)
  519. grid_lay.addWidget(self.adj_gcode_button, 42, 0, 1, 3)
  520. separator_line1 = QtWidgets.QFrame()
  521. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  522. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  523. grid_lay.addWidget(separator_line1, 43, 0, 1, 3)
  524. grid_lay.addWidget(QtWidgets.QLabel(''), 44, 0, 1, 3)
  525. # STEP 5 #
  526. step_5 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 5: Calibrate FlatCAM Objects"))
  527. step_5.setToolTip(
  528. _("Adjust the FlatCAM objects\n"
  529. "with the factors determined and verified above.")
  530. )
  531. grid_lay.addWidget(step_5, 45, 0, 1, 3)
  532. self.adj_object_type_combo = FCComboBox()
  533. self.adj_object_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  534. self.adj_object_type_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  535. self.adj_object_type_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/drill16.png"))
  536. self.adj_object_type_combo.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  537. self.adj_object_type_label = QtWidgets.QLabel("%s:" % _("Adjusted object type"))
  538. self.adj_object_type_label.setToolTip(_("Type of the FlatCAM Object to be adjusted."))
  539. grid_lay.addWidget(self.adj_object_type_label, 46, 0, 1, 3)
  540. grid_lay.addWidget(self.adj_object_type_combo, 47, 0, 1, 3)
  541. self.adj_object_combo = FCComboBox()
  542. self.adj_object_combo.setModel(self.app.collection)
  543. self.adj_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  544. self.adj_object_combo.is_last = True
  545. self.adj_object_combo.obj_type = {
  546. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  547. }[self.adj_object_type_combo.get_value()]
  548. self.adj_object_label = QtWidgets.QLabel("%s:" % _("Adjusted object selection"))
  549. self.adj_object_label.setToolTip(
  550. _("The FlatCAM Object to be adjusted.")
  551. )
  552. grid_lay.addWidget(self.adj_object_label, 48, 0, 1, 3)
  553. grid_lay.addWidget(self.adj_object_combo, 49, 0, 1, 3)
  554. # ## Adjust Objects Button
  555. self.cal_button = QtWidgets.QPushButton(_("Calibrate"))
  556. self.cal_button.setToolTip(
  557. _("Adjust (scale and/or skew) the objects\n"
  558. "with the factors determined above.")
  559. )
  560. self.cal_button.setStyleSheet("""
  561. QPushButton
  562. {
  563. font-weight: bold;
  564. }
  565. """)
  566. grid_lay.addWidget(self.cal_button, 50, 0, 1, 3)
  567. separator_line2 = QtWidgets.QFrame()
  568. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  569. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  570. grid_lay.addWidget(separator_line2, 51, 0, 1, 3)
  571. grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0, 1, 3)
  572. self.layout.addStretch()
  573. # ## Reset Tool
  574. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  575. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  576. self.reset_button.setToolTip(
  577. _("Will reset the tool parameters.")
  578. )
  579. self.reset_button.setStyleSheet("""
  580. QPushButton
  581. {
  582. font-weight: bold;
  583. }
  584. """)
  585. self.layout.addWidget(self.reset_button)
  586. self.mr = None
  587. self.units = ''
  588. # here store 4 points to be used for calibration
  589. self.click_points = [[], [], [], []]
  590. # store the status of the grid
  591. self.grid_status_memory = None
  592. self.target_obj = None
  593. # if the mouse events are connected to a local method set this True
  594. self.local_connected = False
  595. # reference for the tab where to open and view the verification GCode
  596. self.gcode_editor_tab = None
  597. # calibrated object
  598. self.cal_object = None
  599. # ## Signals
  600. self.cal_source_radio.activated_custom.connect(self.on_cal_source_radio)
  601. self.obj_type_combo.currentIndexChanged.connect(self.on_obj_type_combo)
  602. self.adj_object_type_combo.currentIndexChanged.connect(self.on_adj_obj_type_combo)
  603. self.start_button.clicked.connect(self.on_start_collect_points)
  604. self.gcode_button.clicked.connect(self.generate_verification_gcode)
  605. self.adj_gcode_button.clicked.connect(self.generate_verification_gcode)
  606. self.generate_factors_button.clicked.connect(self.calculate_factors)
  607. self.scale_button.clicked.connect(self.on_scale_button)
  608. self.skew_button.clicked.connect(self.on_skew_button)
  609. self.cal_button.clicked.connect(self.on_cal_button_click)
  610. self.reset_button.clicked.connect(self.set_tool_ui)
  611. def run(self, toggle=True):
  612. self.app.defaults.report_usage("ToolCalibration()")
  613. if toggle:
  614. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  615. if self.app.ui.splitter.sizes()[0] == 0:
  616. self.app.ui.splitter.setSizes([1, 1])
  617. else:
  618. try:
  619. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  620. # if tab is populated with the tool but it does not have the focus, focus on it
  621. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  622. # focus on Tool Tab
  623. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  624. else:
  625. self.app.ui.splitter.setSizes([0, 1])
  626. except AttributeError:
  627. pass
  628. else:
  629. if self.app.ui.splitter.sizes()[0] == 0:
  630. self.app.ui.splitter.setSizes([1, 1])
  631. AppTool.run(self)
  632. self.set_tool_ui()
  633. self.app.ui.notebook.setTabText(2, _("Calibration Tool"))
  634. def install(self, icon=None, separator=None, **kwargs):
  635. AppTool.install(self, icon, separator, shortcut='Alt+E', **kwargs)
  636. def set_tool_ui(self):
  637. self.units = self.app.defaults['units'].upper()
  638. if self.local_connected is True:
  639. self.disconnect_cal_events()
  640. self.bottom_left_coordx_found.set_value(_("Origin"))
  641. self.bottom_left_coordy_found.set_value(_("Origin"))
  642. self.reset_calibration_points()
  643. self.cal_source_radio.set_value(self.app.defaults['tools_cal_calsource'])
  644. self.travelz_entry.set_value(self.app.defaults['tools_cal_travelz'])
  645. self.verz_entry.set_value(self.app.defaults['tools_cal_verz'])
  646. self.zeroz_cb.set_value(self.app.defaults['tools_cal_zeroz'])
  647. self.toolchangez_entry.set_value(self.app.defaults['tools_cal_toolchangez'])
  648. self.toolchange_xy_entry.set_value(self.app.defaults['tools_cal_toolchange_xy'])
  649. self.second_point_radio.set_value(self.app.defaults['tools_cal_sec_point'])
  650. self.scalex_entry.set_value(1.0)
  651. self.scaley_entry.set_value(1.0)
  652. self.skewx_entry.set_value(0.0)
  653. self.skewy_entry.set_value(0.0)
  654. # default object selection is Excellon = index_1
  655. self.obj_type_combo.setCurrentIndex(1)
  656. self.on_obj_type_combo()
  657. self.adj_object_type_combo.setCurrentIndex(0)
  658. self.on_adj_obj_type_combo()
  659. # self.adj_object_combo.setCurrentIndex(0)
  660. # calibrated object
  661. self.cal_object = None
  662. self.app.inform.emit('%s...' % _("Tool initialized"))
  663. def on_obj_type_combo(self):
  664. obj_type = self.obj_type_combo.currentIndex()
  665. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  666. # self.object_combo.setCurrentIndex(0)
  667. self.object_combo.obj_type = {
  668. _("Gerber"): "Gerber", _("Excellon"): "Excellon"
  669. }[self.obj_type_combo.get_value()]
  670. def on_adj_obj_type_combo(self):
  671. obj_type = self.adj_object_type_combo.currentIndex()
  672. self.adj_object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  673. # self.adj_object_combo.setCurrentIndex(0)
  674. self.adj_object_combo.obj_type = {
  675. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  676. }[self.adj_object_type_combo.get_value()]
  677. def on_cal_source_radio(self, val):
  678. if val == 'object':
  679. self.obj_type_label.setDisabled(False)
  680. self.obj_type_combo.setDisabled(False)
  681. self.object_label.setDisabled(False)
  682. self.object_combo.setDisabled(False)
  683. else:
  684. self.obj_type_label.setDisabled(True)
  685. self.obj_type_combo.setDisabled(True)
  686. self.object_label.setDisabled(True)
  687. self.object_combo.setDisabled(True)
  688. def on_start_collect_points(self):
  689. if self.cal_source_radio.get_value() == 'object':
  690. selection_index = self.object_combo.currentIndex()
  691. model_index = self.app.collection.index(selection_index, 0, self.object_combo.rootModelIndex())
  692. try:
  693. self.target_obj = model_index.internalPointer().obj
  694. except AttributeError:
  695. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no source FlatCAM object selected..."))
  696. return
  697. # disengage the grid snapping since it will be hard to find the drills on grid
  698. if self.app.ui.grid_snap_btn.isChecked():
  699. self.grid_status_memory = True
  700. self.app.ui.grid_snap_btn.trigger()
  701. else:
  702. self.grid_status_memory = False
  703. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  704. if self.app.is_legacy is False:
  705. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  706. else:
  707. self.canvas.graph_event_disconnect(self.app.mr)
  708. self.local_connected = True
  709. self.reset_calibration_points()
  710. self.app.inform.emit(_("Get First calibration point. Bottom Left..."))
  711. def on_mouse_click_release(self, event):
  712. if self.app.is_legacy is False:
  713. event_pos = event.pos
  714. right_button = 2
  715. self.app.event_is_dragging = self.app.event_is_dragging
  716. else:
  717. event_pos = (event.xdata, event.ydata)
  718. right_button = 3
  719. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  720. pos_canvas = self.canvas.translate_coords(event_pos)
  721. if event.button == 1:
  722. click_pt = Point([pos_canvas[0], pos_canvas[1]])
  723. if self.app.selection_type is not None:
  724. # delete previous selection shape
  725. self.app.delete_selection_shape()
  726. self.app.selection_type = None
  727. else:
  728. if self.cal_source_radio.get_value() == 'object':
  729. if self.target_obj.kind.lower() == 'excellon':
  730. for tool, tool_dict in self.target_obj.tools.items():
  731. for geo in tool_dict['solid_geometry']:
  732. if click_pt.within(geo):
  733. center_pt = geo.centroid
  734. self.click_points.append(
  735. [
  736. float('%.*f' % (self.decimals, center_pt.x)),
  737. float('%.*f' % (self.decimals, center_pt.y))
  738. ]
  739. )
  740. self.check_points()
  741. else:
  742. for apid, apid_val in self.target_obj.apertures.items():
  743. for geo_el in apid_val['geometry']:
  744. if 'solid' in geo_el:
  745. if click_pt.within(geo_el['solid']):
  746. if isinstance(geo_el['follow'], Point):
  747. center_pt = geo_el['solid'].centroid
  748. self.click_points.append(
  749. [
  750. float('%.*f' % (self.decimals, center_pt.x)),
  751. float('%.*f' % (self.decimals, center_pt.y))
  752. ]
  753. )
  754. self.check_points()
  755. else:
  756. self.click_points.append(
  757. [
  758. float('%.*f' % (self.decimals, click_pt.x)),
  759. float('%.*f' % (self.decimals, click_pt.y))
  760. ]
  761. )
  762. self.check_points()
  763. elif event.button == right_button and self.app.event_is_dragging is False:
  764. if len(self.click_points) != 4:
  765. self.reset_calibration_points()
  766. self.disconnect_cal_events()
  767. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled by user request."))
  768. def check_points(self):
  769. if len(self.click_points) == 1:
  770. self.bottom_left_coordx_tgt.set_value(self.click_points[0][0])
  771. self.bottom_left_coordy_tgt.set_value(self.click_points[0][1])
  772. self.app.inform.emit(_("Get Second calibration point. Bottom Right (Top Left)..."))
  773. elif len(self.click_points) == 2:
  774. self.bottom_right_coordx_tgt.set_value(self.click_points[1][0])
  775. self.bottom_right_coordy_tgt.set_value(self.click_points[1][1])
  776. self.app.inform.emit(_("Get Third calibration point. Top Left (Bottom Right)..."))
  777. elif len(self.click_points) == 3:
  778. self.top_left_coordx_tgt.set_value(self.click_points[2][0])
  779. self.top_left_coordy_tgt.set_value(self.click_points[2][1])
  780. self.app.inform.emit(_("Get Forth calibration point. Top Right..."))
  781. elif len(self.click_points) == 4:
  782. self.top_right_coordx_tgt.set_value(self.click_points[3][0])
  783. self.top_right_coordy_tgt.set_value(self.click_points[3][1])
  784. self.app.inform.emit('[success] %s' % _("Done. All four points have been acquired."))
  785. self.disconnect_cal_events()
  786. def reset_calibration_points(self):
  787. self.click_points = []
  788. self.bottom_left_coordx_tgt.set_value('')
  789. self.bottom_left_coordy_tgt.set_value('')
  790. self.bottom_right_coordx_tgt.set_value('')
  791. self.bottom_right_coordy_tgt.set_value('')
  792. self.top_left_coordx_tgt.set_value('')
  793. self.top_left_coordy_tgt.set_value('')
  794. self.top_right_coordx_tgt.set_value('')
  795. self.top_right_coordy_tgt.set_value('')
  796. self.bottom_right_coordx_found.set_value('')
  797. self.bottom_right_coordy_found.set_value('')
  798. self.top_left_coordx_found.set_value('')
  799. self.top_left_coordy_found.set_value('')
  800. def gcode_header(self):
  801. log.debug("ToolCalibration.gcode_header()")
  802. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  803. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  804. (str(self.app.version), str(self.app.version_date)) + '\n'
  805. gcode += '(Name: ' + _('Verification GCode for FlatCAM Calibration Tool') + ')\n'
  806. gcode += '(Units: ' + self.units.upper() + ')\n\n'
  807. gcode += '(Created on ' + time_str + ')\n\n'
  808. gcode += 'G20\n' if self.units.upper() == 'IN' else 'G21\n'
  809. gcode += 'G90\n'
  810. gcode += 'G17\n'
  811. gcode += 'G94\n\n'
  812. return gcode
  813. def close_tab(self):
  814. for idx in range(self.app.ui.plot_tab_area.count()):
  815. if self.app.ui.plot_tab_area.tabText(idx) == _("Gcode Viewer"):
  816. wdg = self.app.ui.plot_tab_area.widget(idx)
  817. wdg.deleteLater()
  818. self.app.ui.plot_tab_area.removeTab(idx)
  819. def generate_verification_gcode(self):
  820. sec_point = self.second_point_radio.get_value()
  821. travel_z = '%.*f' % (self.decimals, self.travelz_entry.get_value())
  822. toolchange_z = '%.*f' % (self.decimals, self.toolchangez_entry.get_value())
  823. toolchange_xy_temp = self.toolchange_xy_entry.get_value().split(",")
  824. toolchange_xy = [float(eval(a)) for a in toolchange_xy_temp if a != '']
  825. verification_z = '%.*f' % (self.decimals, self.verz_entry.get_value())
  826. if len(self.click_points) != 4:
  827. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Four points are needed for GCode generation."))
  828. return 'fail'
  829. gcode = self.gcode_header()
  830. if self.zeroz_cb.get_value():
  831. gcode += 'M5\n'
  832. gcode += 'G00 Z%s\n' % toolchange_z
  833. if toolchange_xy:
  834. gcode += 'G00 X%s Y%s\n' % (toolchange_xy[0], toolchange_xy[1])
  835. gcode += 'M0\n'
  836. gcode += 'G01 Z0\n'
  837. gcode += 'M0\n'
  838. gcode += 'G00 Z%s\n' % toolchange_z
  839. gcode += 'M0\n'
  840. # first point: bottom - left -> ORIGIN set
  841. gcode += 'G00 Z%s\n' % travel_z
  842. gcode += 'G00 X%s Y%s\n' % (self.click_points[0][0], self.click_points[0][1])
  843. gcode += 'G01 Z%s\n' % verification_z
  844. gcode += 'M0\n'
  845. if sec_point == 'tl':
  846. # second point: top - left -> align the PCB to this point
  847. gcode += 'G00 Z%s\n' % travel_z
  848. gcode += 'G00 X%s Y%s\n' % (self.click_points[2][0], self.click_points[2][1])
  849. gcode += 'G01 Z%s\n' % verification_z
  850. gcode += 'M0\n'
  851. # third point: bottom - right -> check for scale on X axis or for skew on Y axis
  852. gcode += 'G00 Z%s\n' % travel_z
  853. gcode += 'G00 X%s Y%s\n' % (self.click_points[1][0], self.click_points[1][1])
  854. gcode += 'G01 Z%s\n' % verification_z
  855. gcode += 'M0\n'
  856. # forth point: top - right -> verification point
  857. gcode += 'G00 Z%s\n' % travel_z
  858. gcode += 'G00 X%s Y%s\n' % (self.click_points[3][0], self.click_points[3][1])
  859. gcode += 'G01 Z%s\n' % verification_z
  860. gcode += 'M0\n'
  861. else:
  862. # second point: bottom - right -> align the PCB to this point
  863. gcode += 'G00 Z%s\n' % travel_z
  864. gcode += 'G00 X%s Y%s\n' % (self.click_points[1][0], self.click_points[1][1])
  865. gcode += 'G01 Z%s\n' % verification_z
  866. gcode += 'M0\n'
  867. # third point: top - left -> check for scale on Y axis or for skew on X axis
  868. gcode += 'G00 Z%s\n' % travel_z
  869. gcode += 'G00 X%s Y%s\n' % (self.click_points[2][0], self.click_points[2][1])
  870. gcode += 'G01 Z%s\n' % verification_z
  871. gcode += 'M0\n'
  872. # forth point: top - right -> verification point
  873. gcode += 'G00 Z%s\n' % travel_z
  874. gcode += 'G00 X%s Y%s\n' % (self.click_points[3][0], self.click_points[3][1])
  875. gcode += 'G01 Z%s\n' % verification_z
  876. gcode += 'M0\n'
  877. # return to (toolchange_xy[0], toolchange_xy[1], toolchange_z) point for toolchange event
  878. gcode += 'G00 Z%s\n' % travel_z
  879. gcode += 'G00 X0 Y0\n'
  880. gcode += 'G00 Z%s\n' % toolchange_z
  881. if toolchange_xy:
  882. gcode += 'G00 X%s Y%s\n' % (toolchange_xy[0], toolchange_xy[1])
  883. gcode += 'M2'
  884. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  885. # add the tab if it was closed
  886. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Gcode Viewer"))
  887. self.gcode_editor_tab.setObjectName('gcode_viewer_tab')
  888. # delete the absolute and relative position and messages in the infobar
  889. self.app.ui.position_label.setText("")
  890. self.app.ui.rel_position_label.setText("")
  891. self.gcode_editor_tab.code_editor.completer_enable = False
  892. self.gcode_editor_tab.buttonRun.hide()
  893. # Switch plot_area to CNCJob tab
  894. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  895. self.gcode_editor_tab.t_frame.hide()
  896. # then append the text from GCode to the text editor
  897. try:
  898. self.gcode_editor_tab.load_text(gcode, move_to_start=True, clear_text=True)
  899. except Exception as e:
  900. self.app.inform.emit('[ERROR] %s %s' % ('ERROR -->', str(e)))
  901. return
  902. self.gcode_editor_tab.t_frame.show()
  903. self.app.proc_container.view.set_idle()
  904. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  905. _filter_ = "G-Code Files (*.nc);;All Files (*.*)"
  906. self.gcode_editor_tab.buttonSave.clicked.disconnect()
  907. self.gcode_editor_tab.buttonSave.clicked.connect(
  908. lambda: self.gcode_editor_tab.handleSaveGCode(name='fc_ver_gcode', filt=_filter_, callback=self.close_tab))
  909. def calculate_factors(self):
  910. origin_x = self.click_points[0][0]
  911. origin_y = self.click_points[0][1]
  912. top_left_x = self.click_points[2][0]
  913. top_left_y = self.click_points[2][1]
  914. bot_right_x = self.click_points[1][0]
  915. bot_right_y = self.click_points[1][1]
  916. try:
  917. top_left_dx = float(self.top_left_coordx_found.get_value())
  918. except TypeError:
  919. top_left_dx = top_left_x
  920. try:
  921. top_left_dy = float(self.top_left_coordy_found.get_value())
  922. except TypeError:
  923. top_left_dy = top_left_y
  924. try:
  925. bot_right_dx = float(self.bottom_right_coordx_found.get_value())
  926. except TypeError:
  927. bot_right_dx = bot_right_x
  928. try:
  929. bot_right_dy = float(self.bottom_right_coordy_found.get_value())
  930. except TypeError:
  931. bot_right_dy = bot_right_y
  932. # ------------------------------------------------------------------------------- #
  933. # --------------------------- FACTORS CALCULUS ---------------------------------- #
  934. # ------------------------------------------------------------------------------- #
  935. if bot_right_dx != float('%.*f' % (self.decimals, bot_right_x)):
  936. # we have scale on X
  937. scale_x = (bot_right_dx / (bot_right_x - origin_x)) + 1
  938. self.scalex_entry.set_value(scale_x)
  939. if top_left_dy != float('%.*f' % (self.decimals, top_left_y)):
  940. # we have scale on Y
  941. scale_y = (top_left_dy / (top_left_y - origin_y)) + 1
  942. self.scaley_entry.set_value(scale_y)
  943. if top_left_dx != float('%.*f' % (self.decimals, top_left_x)):
  944. # we have skew on X
  945. dx = top_left_dx
  946. dy = top_left_y - origin_y
  947. skew_angle_x = math.degrees(math.atan(dx / dy))
  948. self.skewx_entry.set_value(skew_angle_x)
  949. if bot_right_dy != float('%.*f' % (self.decimals, bot_right_y)):
  950. # we have skew on Y
  951. dx = bot_right_x - origin_x
  952. dy = bot_right_dy + origin_y
  953. skew_angle_y = math.degrees(math.atan(dy / dx))
  954. self.skewy_entry.set_value(skew_angle_y)
  955. @property
  956. def target_values_in_table(self):
  957. self.click_points[0][0] = self.bottom_left_coordx_tgt.get_value()
  958. self.click_points[0][1] = self.bottom_left_coordy_tgt.get_value()
  959. self.click_points[1][0] = self.bottom_right_coordx_tgt.get_value()
  960. self.click_points[1][1] = self.bottom_right_coordy_tgt.get_value()
  961. self.click_points[2][0] = self.top_left_coordx_tgt.get_value()
  962. self.click_points[2][1] = self.top_left_coordy_tgt.get_value()
  963. self.click_points[3][0] = self.top_right_coordx_tgt.get_value()
  964. self.click_points[3][1] = self.top_right_coordy_tgt.get_value()
  965. return self.click_points
  966. @target_values_in_table.setter
  967. def target_values_in_table(self, param):
  968. bl_pt, br_pt, tl_pt, tr_pt = param
  969. self.click_points[0] = [bl_pt[0], bl_pt[1]]
  970. self.click_points[1] = [br_pt[0], br_pt[1]]
  971. self.click_points[2] = [tl_pt[0], tl_pt[1]]
  972. self.click_points[3] = [tr_pt[0], tr_pt[1]]
  973. self.bottom_left_coordx_tgt.set_value(float('%.*f' % (self.decimals, bl_pt[0])))
  974. self.bottom_left_coordy_tgt.set_value(float('%.*f' % (self.decimals, bl_pt[1])))
  975. self.bottom_right_coordx_tgt.set_value(float('%.*f' % (self.decimals, br_pt[0])))
  976. self.bottom_right_coordy_tgt.set_value(float('%.*f' % (self.decimals, br_pt[1])))
  977. self.top_left_coordx_tgt.set_value(float('%.*f' % (self.decimals, tl_pt[0])))
  978. self.top_left_coordy_tgt.set_value(float('%.*f' % (self.decimals, tl_pt[1])))
  979. self.top_right_coordx_tgt.set_value(float('%.*f' % (self.decimals, tr_pt[0])))
  980. self.top_right_coordy_tgt.set_value(float('%.*f' % (self.decimals, tr_pt[1])))
  981. def on_scale_button(self):
  982. scalex_fact = self.scalex_entry.get_value()
  983. scaley_fact = self.scaley_entry.get_value()
  984. bl, br, tl, tr = self.target_values_in_table
  985. bl_geo = Point(bl[0], bl[1])
  986. br_geo = Point(br[0], br[1])
  987. tl_geo = Point(tl[0], tl[1])
  988. tr_geo = Point(tr[0], tr[1])
  989. bl_scaled = scale(bl_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  990. br_scaled = scale(br_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  991. tl_scaled = scale(tl_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  992. tr_scaled = scale(tr_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  993. scaled_values = [
  994. [bl_scaled.x, bl_scaled.y],
  995. [br_scaled.x, br_scaled.y],
  996. [tl_scaled.x, tl_scaled.y],
  997. [tr_scaled.x, tr_scaled.y]
  998. ]
  999. self.target_values_in_table = scaled_values
  1000. def on_skew_button(self):
  1001. skewx_angle = self.skewx_entry.get_value()
  1002. skewy_angle = self.skewy_entry.get_value()
  1003. bl, br, tl, tr = self.target_values_in_table
  1004. bl_geo = Point(bl[0], bl[1])
  1005. br_geo = Point(br[0], br[1])
  1006. tl_geo = Point(tl[0], tl[1])
  1007. tr_geo = Point(tr[0], tr[1])
  1008. bl_skewed = skew(bl_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1009. br_skewed = skew(br_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1010. tl_skewed = skew(tl_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1011. tr_skewed = skew(tr_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1012. skewed_values = [
  1013. [bl_skewed.x, bl_skewed.y],
  1014. [br_skewed.x, br_skewed.y],
  1015. [tl_skewed.x, tl_skewed.y],
  1016. [tr_skewed.x, tr_skewed.y]
  1017. ]
  1018. self.target_values_in_table = skewed_values
  1019. def on_cal_button_click(self):
  1020. # get the FlatCAM object to calibrate
  1021. selection_index = self.adj_object_combo.currentIndex()
  1022. model_index = self.app.collection.index(selection_index, 0, self.adj_object_combo.rootModelIndex())
  1023. try:
  1024. self.cal_object = model_index.internalPointer().obj
  1025. except Exception as e:
  1026. log.debug("ToolCalibration.on_cal_button_click() --> %s" % str(e))
  1027. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no FlatCAM object selected..."))
  1028. return 'fail'
  1029. obj_name = self.cal_object.options["name"] + "_calibrated"
  1030. self.app.worker_task.emit({'fcn': self.new_calibrated_object, 'params': [obj_name]})
  1031. def new_calibrated_object(self, obj_name):
  1032. try:
  1033. origin_x = self.click_points[0][0]
  1034. origin_y = self.click_points[0][1]
  1035. except IndexError as e:
  1036. log.debug("ToolCalibration.new_calibrated_object() --> %s" % str(e))
  1037. return 'fail'
  1038. scalex = self.scalex_entry.get_value()
  1039. scaley = self.scaley_entry.get_value()
  1040. skewx = self.skewx_entry.get_value()
  1041. skewy = self.skewy_entry.get_value()
  1042. # create a new object adjusted (calibrated)
  1043. def initialize_geometry(obj_init, app):
  1044. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  1045. try:
  1046. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  1047. except AttributeError:
  1048. pass
  1049. try:
  1050. obj_init.apertures = deepcopy(obj.apertures)
  1051. except AttributeError:
  1052. pass
  1053. try:
  1054. if obj.tools:
  1055. obj_init.tools = deepcopy(obj.tools)
  1056. except Exception as ee:
  1057. log.debug("ToolCalibration.new_calibrated_object.initialize_geometry() --> %s" % str(ee))
  1058. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1059. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1060. try:
  1061. obj_init.source_file = deepcopy(obj.source_file)
  1062. except (AttributeError, TypeError):
  1063. pass
  1064. def initialize_gerber(obj_init, app):
  1065. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  1066. try:
  1067. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  1068. except AttributeError:
  1069. pass
  1070. try:
  1071. obj_init.apertures = deepcopy(obj.apertures)
  1072. except AttributeError:
  1073. pass
  1074. try:
  1075. if obj.tools:
  1076. obj_init.tools = deepcopy(obj.tools)
  1077. except Exception as err:
  1078. log.debug("ToolCalibration.new_calibrated_object.initialize_gerber() --> %s" % str(err))
  1079. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1080. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1081. try:
  1082. obj_init.source_file = self.export_gerber(obj_name=obj_name, filename=None, local_use=obj_init,
  1083. use_thread=False)
  1084. except (AttributeError, TypeError):
  1085. pass
  1086. def initialize_excellon(obj_init, app):
  1087. obj_init.tools = deepcopy(obj.tools)
  1088. # drills are offset, so they need to be deep copied
  1089. obj_init.drills = deepcopy(obj.drills)
  1090. # slots are offset, so they need to be deep copied
  1091. obj_init.slots = deepcopy(obj.slots)
  1092. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1093. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1094. obj_init.create_geometry()
  1095. obj_init.source_file = self.app.export_excellon(obj_name=obj_name, local_use=obj, filename=None,
  1096. use_thread=False)
  1097. obj = self.cal_object
  1098. obj_name = obj_name
  1099. if obj is None:
  1100. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no FlatCAM object selected..."))
  1101. log.debug("ToolCalibration.new_calibrated_object() --> No object to calibrate")
  1102. return 'fail'
  1103. try:
  1104. if obj.kind.lower() == 'excellon':
  1105. self.app.app_obj.new_object("excellon", str(obj_name), initialize_excellon)
  1106. elif obj.kind.lower() == 'gerber':
  1107. self.app.app_obj.new_object("gerber", str(obj_name), initialize_gerber)
  1108. elif obj.kind.lower() == 'geometry':
  1109. self.app.app_obj.new_object("geometry", str(obj_name), initialize_geometry)
  1110. except Exception as e:
  1111. log.debug("ToolCalibration.new_calibrated_object() --> %s" % str(e))
  1112. return "Operation failed: %s" % str(e)
  1113. def disconnect_cal_events(self):
  1114. # restore the Grid snapping if it was active before
  1115. if self.grid_status_memory is True:
  1116. self.app.ui.grid_snap_btn.trigger()
  1117. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1118. if self.app.is_legacy is False:
  1119. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1120. else:
  1121. self.canvas.graph_event_disconnect(self.mr)
  1122. self.local_connected = False
  1123. def reset_fields(self):
  1124. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1125. self.adj_exc_object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1126. self.adj_geo_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1127. # end of file