ToolDistance.py 20 KB

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