ToolDistance.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.VisPyVisuals import *
  10. from flatcamGUI.GUIElements import FCEntry
  11. from copy import copy
  12. import math
  13. import logging
  14. import gettext
  15. import FlatCAMTranslation as fcTranslate
  16. import builtins
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class Distance(FlatCAMTool):
  22. toolName = _("Distance Tool")
  23. def __init__(self, app):
  24. FlatCAMTool.__init__(self, app)
  25. self.app = app
  26. self.decimals = self.app.decimals
  27. self.canvas = self.app.plotcanvas
  28. self.units = self.app.defaults['units'].lower()
  29. # ## Title
  30. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font><br>" % self.toolName)
  31. self.layout.addWidget(title_label)
  32. # ## Form Layout
  33. form_layout = QtWidgets.QFormLayout()
  34. self.layout.addLayout(form_layout)
  35. self.units_label = QtWidgets.QLabel('%s:' % _("Units"))
  36. self.units_label.setToolTip(_("Those are the units in which the distance is measured."))
  37. self.units_value = QtWidgets.QLabel("%s" % str({'mm': _("METRIC (mm)"), 'in': _("INCH (in)")}[self.units]))
  38. self.units_value.setDisabled(True)
  39. self.start_label = QtWidgets.QLabel("%s:" % _('Start Coords'))
  40. self.start_label.setToolTip(_("This is measuring Start point coordinates."))
  41. self.stop_label = QtWidgets.QLabel("%s:" % _('Stop Coords'))
  42. self.stop_label.setToolTip(_("This is the measuring Stop point coordinates."))
  43. self.distance_x_label = QtWidgets.QLabel('%s:' % _("Dx"))
  44. self.distance_x_label.setToolTip(_("This is the distance measured over the X axis."))
  45. self.distance_y_label = QtWidgets.QLabel('%s:' % _("Dy"))
  46. self.distance_y_label.setToolTip(_("This is the distance measured over the Y axis."))
  47. self.angle_label = QtWidgets.QLabel('%s:' % _("Angle"))
  48. self.angle_label.setToolTip(_("This is orientation angle of the measuring line."))
  49. self.total_distance_label = QtWidgets.QLabel("<b>%s:</b>" % _('DISTANCE'))
  50. self.total_distance_label.setToolTip(_("This is the point to point Euclidian distance."))
  51. self.start_entry = FCEntry()
  52. self.start_entry.setReadOnly(True)
  53. self.start_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  54. self.start_entry.setToolTip(_("This is measuring Start point coordinates."))
  55. self.stop_entry = FCEntry()
  56. self.stop_entry.setReadOnly(True)
  57. self.stop_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  58. self.stop_entry.setToolTip(_("This is the measuring Stop point coordinates."))
  59. self.distance_x_entry = FCEntry()
  60. self.distance_x_entry.setReadOnly(True)
  61. self.distance_x_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  62. self.distance_x_entry.setToolTip(_("This is the distance measured over the X axis."))
  63. self.distance_y_entry = FCEntry()
  64. self.distance_y_entry.setReadOnly(True)
  65. self.distance_y_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  66. self.distance_y_entry.setToolTip(_("This is the distance measured over the Y axis."))
  67. self.angle_entry = FCEntry()
  68. self.angle_entry.setReadOnly(True)
  69. self.angle_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  70. self.angle_entry.setToolTip(_("This is orientation angle of the measuring line."))
  71. self.total_distance_entry = FCEntry()
  72. self.total_distance_entry.setReadOnly(True)
  73. self.total_distance_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  74. self.total_distance_entry.setToolTip(_("This is the point to point Euclidian distance."))
  75. self.measure_btn = QtWidgets.QPushButton(_("Measure"))
  76. # self.measure_btn.setFixedWidth(70)
  77. self.layout.addWidget(self.measure_btn)
  78. form_layout.addRow(self.units_label, self.units_value)
  79. form_layout.addRow(self.start_label, self.start_entry)
  80. form_layout.addRow(self.stop_label, self.stop_entry)
  81. form_layout.addRow(self.distance_x_label, self.distance_x_entry)
  82. form_layout.addRow(self.distance_y_label, self.distance_y_entry)
  83. form_layout.addRow(self.angle_label, self.angle_entry)
  84. form_layout.addRow(self.total_distance_label, self.total_distance_entry)
  85. # initial view of the layout
  86. self.start_entry.set_value('(0, 0)')
  87. self.stop_entry.set_value('(0, 0)')
  88. self.distance_x_entry.set_value('0.0')
  89. self.distance_y_entry.set_value('0.0')
  90. self.angle_entry.set_value('0.0')
  91. self.total_distance_entry.set_value('0.0')
  92. self.layout.addStretch()
  93. # store here the first click and second click of the measurement process
  94. self.points = []
  95. self.rel_point1 = None
  96. self.rel_point2 = None
  97. self.active = False
  98. self.clicked_meas = None
  99. self.meas_line = None
  100. self.original_call_source = 'app'
  101. # store here the event connection ID's
  102. self.mm = None
  103. self.mr = None
  104. # VisPy visuals
  105. if self.app.is_legacy is False:
  106. self.sel_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  107. else:
  108. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  109. self.sel_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='measurement')
  110. self.measure_btn.clicked.connect(self.activate_measure_tool)
  111. def run(self, toggle=False):
  112. self.app.report_usage("ToolDistance()")
  113. self.points[:] = []
  114. self.rel_point1 = None
  115. self.rel_point2 = None
  116. if self.app.tool_tab_locked is True:
  117. return
  118. self.app.ui.notebook.setTabText(2, _("Distance Tool"))
  119. # if the splitter is hidden, display it
  120. if self.app.ui.splitter.sizes()[0] == 0:
  121. self.app.ui.splitter.setSizes([1, 1])
  122. if toggle:
  123. pass
  124. if self.active is False:
  125. self.activate_measure_tool()
  126. else:
  127. self.deactivate_measure_tool()
  128. def install(self, icon=None, separator=None, **kwargs):
  129. FlatCAMTool.install(self, icon, separator, shortcut='CTRL+M', **kwargs)
  130. def set_tool_ui(self):
  131. # Remove anything else in the GUI
  132. self.app.ui.tool_scroll_area.takeWidget()
  133. # Put ourself in the GUI
  134. self.app.ui.tool_scroll_area.setWidget(self)
  135. # Switch notebook to tool page
  136. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  137. self.units = self.app.defaults['units'].lower()
  138. self.app.command_active = "Distance"
  139. # initial view of the layout
  140. self.start_entry.set_value('(0, 0)')
  141. self.stop_entry.set_value('(0, 0)')
  142. self.distance_x_entry.set_value('0.0')
  143. self.distance_y_entry.set_value('0.0')
  144. self.angle_entry.set_value('0.0')
  145. self.total_distance_entry.set_value('0.0')
  146. # this is a hack; seems that triggering the grid will make the visuals better
  147. # trigger it twice to return to the original state
  148. self.app.ui.grid_snap_btn.trigger()
  149. self.app.ui.grid_snap_btn.trigger()
  150. log.debug("Distance Tool --> tool initialized")
  151. def activate_measure_tool(self):
  152. # ENABLE the Measuring TOOL
  153. self.active = True
  154. self.clicked_meas = 0
  155. self.original_call_source = copy(self.app.call_source)
  156. self.app.inform.emit(_("MEASURING: Click on the Start point ..."))
  157. self.units = self.app.defaults['units'].lower()
  158. # we can connect the app mouse events to the measurement tool
  159. # NEVER DISCONNECT THOSE before connecting some other handlers; it breaks something in VisPy
  160. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_mouse_move_meas)
  161. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  162. # we disconnect the mouse/key handlers from wherever the measurement tool was called
  163. if self.app.call_source == 'app':
  164. if self.app.is_legacy is False:
  165. self.canvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  166. self.canvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  167. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  168. else:
  169. self.canvas.graph_event_disconnect(self.app.mm)
  170. self.canvas.graph_event_disconnect(self.app.mp)
  171. self.canvas.graph_event_disconnect(self.app.mr)
  172. elif self.app.call_source == 'geo_editor':
  173. if self.app.is_legacy is False:
  174. self.canvas.graph_event_disconnect('mouse_move', self.app.geo_editor.on_canvas_move)
  175. self.canvas.graph_event_disconnect('mouse_press', self.app.geo_editor.on_canvas_click)
  176. self.canvas.graph_event_disconnect('mouse_release', self.app.geo_editor.on_geo_click_release)
  177. else:
  178. self.canvas.graph_event_disconnect(self.app.geo_editor.mm)
  179. self.canvas.graph_event_disconnect(self.app.geo_editor.mp)
  180. self.canvas.graph_event_disconnect(self.app.geo_editor.mr)
  181. elif self.app.call_source == 'exc_editor':
  182. if self.app.is_legacy is False:
  183. self.canvas.graph_event_disconnect('mouse_move', self.app.exc_editor.on_canvas_move)
  184. self.canvas.graph_event_disconnect('mouse_press', self.app.exc_editor.on_canvas_click)
  185. self.canvas.graph_event_disconnect('mouse_release', self.app.exc_editor.on_exc_click_release)
  186. else:
  187. self.canvas.graph_event_disconnect(self.app.exc_editor.mm)
  188. self.canvas.graph_event_disconnect(self.app.exc_editor.mp)
  189. self.canvas.graph_event_disconnect(self.app.exc_editor.mr)
  190. elif self.app.call_source == 'grb_editor':
  191. if self.app.is_legacy is False:
  192. self.canvas.graph_event_disconnect('mouse_move', self.app.grb_editor.on_canvas_move)
  193. self.canvas.graph_event_disconnect('mouse_press', self.app.grb_editor.on_canvas_click)
  194. self.canvas.graph_event_disconnect('mouse_release', self.app.grb_editor.on_grb_click_release)
  195. else:
  196. self.canvas.graph_event_disconnect(self.app.grb_editor.mm)
  197. self.canvas.graph_event_disconnect(self.app.grb_editor.mp)
  198. self.canvas.graph_event_disconnect(self.app.grb_editor.mr)
  199. self.app.call_source = 'measurement'
  200. self.set_tool_ui()
  201. def deactivate_measure_tool(self):
  202. # DISABLE the Measuring TOOL
  203. self.active = False
  204. self.points = []
  205. self.app.call_source = copy(self.original_call_source)
  206. if self.original_call_source == 'app':
  207. self.app.mm = self.canvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  208. self.app.mp = self.canvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  209. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  210. elif self.original_call_source == 'geo_editor':
  211. self.app.geo_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.geo_editor.on_canvas_move)
  212. self.app.geo_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.geo_editor.on_canvas_click)
  213. self.app.geo_editor.mr = self.canvas.graph_event_connect('mouse_release',
  214. self.app.geo_editor.on_geo_click_release)
  215. elif self.original_call_source == 'exc_editor':
  216. self.app.exc_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.exc_editor.on_canvas_move)
  217. self.app.exc_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.exc_editor.on_canvas_click)
  218. self.app.exc_editor.mr = self.canvas.graph_event_connect('mouse_release',
  219. self.app.exc_editor.on_exc_click_release)
  220. elif self.original_call_source == 'grb_editor':
  221. self.app.grb_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.grb_editor.on_canvas_move)
  222. self.app.grb_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.grb_editor.on_canvas_click)
  223. self.app.grb_editor.mr = self.canvas.graph_event_connect('mouse_release',
  224. self.app.grb_editor.on_grb_click_release)
  225. # disconnect the mouse/key events from functions of measurement tool
  226. if self.app.is_legacy is False:
  227. self.canvas.graph_event_disconnect('mouse_move', self.on_mouse_move_meas)
  228. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  229. else:
  230. self.canvas.graph_event_disconnect(self.mm)
  231. self.canvas.graph_event_disconnect(self.mr)
  232. # self.app.ui.notebook.setTabText(2, _("Tools"))
  233. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  234. self.app.command_active = None
  235. # delete the measuring line
  236. self.delete_shape()
  237. log.debug("Distance Tool --> exit tool")
  238. def on_mouse_click_release(self, event):
  239. # mouse click releases will be accepted only if the left button is clicked
  240. # this is necessary because right mouse click or middle mouse click
  241. # are used for panning on the canvas
  242. log.debug("Distance Tool --> mouse click release")
  243. if event.button == 1:
  244. if self.app.is_legacy is False:
  245. event_pos = event.pos
  246. else:
  247. event_pos = (event.xdata, event.ydata)
  248. pos_canvas = self.canvas.translate_coords(event_pos)
  249. # if GRID is active we need to get the snapped positions
  250. if self.app.grid_status() == True:
  251. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  252. else:
  253. pos = pos_canvas[0], pos_canvas[1]
  254. self.points.append(pos)
  255. # Reset here the relative coordinates so there is a new reference on the click position
  256. if self.rel_point1 is None:
  257. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.*f&nbsp;&nbsp; <b>Dy</b>: "
  258. "%.*f&nbsp;&nbsp;&nbsp;&nbsp;" %
  259. (self.decimals, 0.0, self.decimals, 0.0))
  260. self.rel_point1 = pos
  261. else:
  262. self.rel_point2 = copy(self.rel_point1)
  263. self.rel_point1 = pos
  264. if len(self.points) == 1:
  265. self.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  266. self.app.inform.emit(_("MEASURING: Click on the Destination point ..."))
  267. elif len(self.points) == 2:
  268. dx = self.points[1][0] - self.points[0][0]
  269. dy = self.points[1][1] - self.points[0][1]
  270. d = math.sqrt(dx ** 2 + dy ** 2)
  271. self.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  272. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  273. tx1=_("MEASURING"),
  274. tx2=_("Result"),
  275. tx3=_("Distance"),
  276. d_x='%*f' % (self.decimals, abs(dx)),
  277. d_y='%*f' % (self.decimals, abs(dy)),
  278. d_z='%*f' % (self.decimals, abs(d)))
  279. )
  280. self.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  281. self.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  282. try:
  283. angle = math.degrees(math.atan(dy / dx))
  284. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  285. except Exception as e:
  286. pass
  287. self.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  288. self.app.ui.rel_position_label.setText(
  289. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  290. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  291. )
  292. )
  293. self.deactivate_measure_tool()
  294. def on_mouse_move_meas(self, event):
  295. try: # May fail in case mouse not within axes
  296. if self.app.is_legacy is False:
  297. event_pos = event.pos
  298. else:
  299. event_pos = (event.xdata, event.ydata)
  300. try:
  301. x = float(event_pos[0])
  302. y = float(event_pos[1])
  303. except TypeError:
  304. return
  305. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  306. if self.app.grid_status() == True:
  307. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  308. # Update cursor
  309. self.app.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  310. symbol='++', edge_color=self.app.cursor_color_3D,
  311. size=self.app.defaults["global_cursor_size"])
  312. else:
  313. pos = (pos_canvas[0], pos_canvas[1])
  314. self.app.ui.position_label.setText(
  315. "&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: {}&nbsp;&nbsp; <b>Y</b>: {}".format(
  316. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  317. )
  318. )
  319. if self.rel_point1 is not None:
  320. dx = pos[0] - float(self.rel_point1[0])
  321. dy = pos[1] - float(self.rel_point1[1])
  322. else:
  323. dx = pos[0]
  324. dy = pos[1]
  325. self.app.ui.rel_position_label.setText(
  326. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  327. '%.*f' % (self.decimals, dx), '%.*f' % (self.decimals, dy)
  328. )
  329. )
  330. # update utility geometry
  331. if len(self.points) == 1:
  332. self.utility_geometry(pos=pos)
  333. # and display the temporary angle
  334. try:
  335. angle = math.degrees(math.atan(dy / dx))
  336. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  337. except Exception as e:
  338. pass
  339. except Exception as e:
  340. log.debug("Distance.on_mouse_move_meas() --> %s" % str(e))
  341. self.app.ui.position_label.setText("")
  342. self.app.ui.rel_position_label.setText("")
  343. def utility_geometry(self, pos):
  344. # first delete old shape
  345. self.delete_shape()
  346. # second draw the new shape of the utility geometry
  347. meas_line = LineString([pos, self.points[0]])
  348. settings = QtCore.QSettings("Open Source", "FlatCAM")
  349. if settings.contains("theme"):
  350. theme = settings.value('theme', type=str)
  351. else:
  352. theme = 'white'
  353. if theme == 'white':
  354. color = '#000000FF'
  355. else:
  356. color = '#FFFFFFFF'
  357. self.sel_shapes.add(meas_line, color=color, update=True, layer=0, tolerance=None)
  358. if self.app.is_legacy is True:
  359. self.sel_shapes.redraw()
  360. def delete_shape(self):
  361. self.sel_shapes.clear()
  362. self.sel_shapes.redraw()
  363. def set_meas_units(self, units):
  364. self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  365. # end of file