ToolDistance.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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, FCButton, FCCheckBox
  11. from shapely.geometry import Point, MultiLineString, Polygon
  12. import FlatCAMTranslation as fcTranslate
  13. from camlib import FlatCAMRTreeStorage
  14. from flatcamEditors.FlatCAMGeoEditor import DrawToolShape
  15. from copy import copy
  16. import math
  17. import logging
  18. import gettext
  19. import builtins
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. log = logging.getLogger('base')
  24. class Distance(FlatCAMTool):
  25. toolName = _("Distance Tool")
  26. def __init__(self, app):
  27. FlatCAMTool.__init__(self, app)
  28. self.app = app
  29. self.decimals = self.app.decimals
  30. self.canvas = self.app.plotcanvas
  31. self.units = self.app.defaults['units'].lower()
  32. # ## Title
  33. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font><br>" % self.toolName)
  34. self.layout.addWidget(title_label)
  35. # ## Form Layout
  36. grid0 = QtWidgets.QGridLayout()
  37. grid0.setColumnStretch(0, 0)
  38. grid0.setColumnStretch(1, 1)
  39. self.layout.addLayout(grid0)
  40. self.units_label = QtWidgets.QLabel('%s:' % _("Units"))
  41. self.units_label.setToolTip(_("Those are the units in which the distance is measured."))
  42. self.units_value = QtWidgets.QLabel("%s" % str({'mm': _("METRIC (mm)"), 'in': _("INCH (in)")}[self.units]))
  43. self.units_value.setDisabled(True)
  44. grid0.addWidget(self.units_label, 0, 0)
  45. grid0.addWidget(self.units_value, 0, 1)
  46. self.snap_center_cb = FCCheckBox(_("Snap to center"))
  47. self.snap_center_cb.setToolTip(
  48. _("Mouse cursor will snap to the center of the pad/drill\n"
  49. "when it is hovering over the geometry of the pad/drill.")
  50. )
  51. grid0.addWidget(self.snap_center_cb, 1, 0, 1, 2)
  52. separator_line = QtWidgets.QFrame()
  53. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  54. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  55. grid0.addWidget(separator_line, 2, 0, 1, 2)
  56. self.start_label = QtWidgets.QLabel("%s:" % _('Start Coords'))
  57. self.start_label.setToolTip(_("This is measuring Start point coordinates."))
  58. self.start_entry = FCEntry()
  59. self.start_entry.setReadOnly(True)
  60. self.start_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  61. self.start_entry.setToolTip(_("This is measuring Start point coordinates."))
  62. grid0.addWidget(self.start_label, 3, 0)
  63. grid0.addWidget(self.start_entry, 3, 1)
  64. self.stop_label = QtWidgets.QLabel("%s:" % _('Stop Coords'))
  65. self.stop_label.setToolTip(_("This is the measuring Stop point coordinates."))
  66. self.stop_entry = FCEntry()
  67. self.stop_entry.setReadOnly(True)
  68. self.stop_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  69. self.stop_entry.setToolTip(_("This is the measuring Stop point coordinates."))
  70. grid0.addWidget(self.stop_label, 4, 0)
  71. grid0.addWidget(self.stop_entry, 4, 1)
  72. self.distance_x_label = QtWidgets.QLabel('%s:' % _("Dx"))
  73. self.distance_x_label.setToolTip(_("This is the distance measured over the X axis."))
  74. self.distance_x_entry = FCEntry()
  75. self.distance_x_entry.setReadOnly(True)
  76. self.distance_x_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  77. self.distance_x_entry.setToolTip(_("This is the distance measured over the X axis."))
  78. grid0.addWidget(self.distance_x_label, 5, 0)
  79. grid0.addWidget(self.distance_x_entry, 5, 1)
  80. self.distance_y_label = QtWidgets.QLabel('%s:' % _("Dy"))
  81. self.distance_y_label.setToolTip(_("This is the distance measured over the Y axis."))
  82. self.distance_y_entry = FCEntry()
  83. self.distance_y_entry.setReadOnly(True)
  84. self.distance_y_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  85. self.distance_y_entry.setToolTip(_("This is the distance measured over the Y axis."))
  86. grid0.addWidget(self.distance_y_label, 6, 0)
  87. grid0.addWidget(self.distance_y_entry, 6, 1)
  88. self.angle_label = QtWidgets.QLabel('%s:' % _("Angle"))
  89. self.angle_label.setToolTip(_("This is orientation angle of the measuring line."))
  90. self.angle_entry = FCEntry()
  91. self.angle_entry.setReadOnly(True)
  92. self.angle_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  93. self.angle_entry.setToolTip(_("This is orientation angle of the measuring line."))
  94. grid0.addWidget(self.angle_label, 7, 0)
  95. grid0.addWidget(self.angle_entry, 7, 1)
  96. self.total_distance_label = QtWidgets.QLabel("<b>%s:</b>" % _('DISTANCE'))
  97. self.total_distance_label.setToolTip(_("This is the point to point Euclidian distance."))
  98. self.total_distance_entry = FCEntry()
  99. self.total_distance_entry.setReadOnly(True)
  100. self.total_distance_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  101. self.total_distance_entry.setToolTip(_("This is the point to point Euclidian distance."))
  102. grid0.addWidget(self.total_distance_label, 8, 0)
  103. grid0.addWidget(self.total_distance_entry, 8, 1)
  104. self.measure_btn = FCButton(_("Measure"))
  105. # self.measure_btn.setFixedWidth(70)
  106. self.layout.addWidget(self.measure_btn)
  107. self.layout.addStretch()
  108. # store here the first click and second click of the measurement process
  109. self.points = []
  110. self.rel_point1 = None
  111. self.rel_point2 = None
  112. self.active = False
  113. self.clicked_meas = None
  114. self.meas_line = None
  115. self.original_call_source = 'app'
  116. # store here the event connection ID's
  117. self.mm = None
  118. self.mr = None
  119. # monitor if the tool was used
  120. self.tool_done = False
  121. # store the grid status here
  122. self.grid_status_memory = False
  123. # store here if the snap button was clicked
  124. self.snap_toggled = None
  125. # VisPy visuals
  126. if self.app.is_legacy is False:
  127. self.sel_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  128. else:
  129. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  130. self.sel_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='measurement')
  131. self.measure_btn.clicked.connect(self.activate_measure_tool)
  132. def run(self, toggle=False):
  133. self.app.report_usage("ToolDistance()")
  134. self.points[:] = []
  135. self.rel_point1 = None
  136. self.rel_point2 = None
  137. self.tool_done = False
  138. if self.app.tool_tab_locked is True:
  139. return
  140. self.app.ui.notebook.setTabText(2, _("Distance Tool"))
  141. # if the splitter is hidden, display it
  142. if self.app.ui.splitter.sizes()[0] == 0:
  143. self.app.ui.splitter.setSizes([1, 1])
  144. if toggle:
  145. pass
  146. if self.active is False:
  147. self.activate_measure_tool()
  148. else:
  149. self.deactivate_measure_tool()
  150. def install(self, icon=None, separator=None, **kwargs):
  151. FlatCAMTool.install(self, icon, separator, shortcut='Ctrl+M', **kwargs)
  152. def set_tool_ui(self):
  153. # Remove anything else in the GUI
  154. self.app.ui.tool_scroll_area.takeWidget()
  155. # Put ourselves in the GUI
  156. self.app.ui.tool_scroll_area.setWidget(self)
  157. # Switch notebook to tool page
  158. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  159. self.units = self.app.defaults['units'].lower()
  160. self.app.command_active = "Distance"
  161. # initial view of the layout
  162. self.start_entry.set_value('(0, 0)')
  163. self.stop_entry.set_value('(0, 0)')
  164. self.distance_x_entry.set_value('0.0')
  165. self.distance_y_entry.set_value('0.0')
  166. self.angle_entry.set_value('0.0')
  167. self.total_distance_entry.set_value('0.0')
  168. self.snap_center_cb.set_value(self.app.defaults['tools_dist_snap_center'])
  169. # snap center works only for Gerber and Execellon Editor's
  170. if self.original_call_source == 'exc_editor' or self.original_call_source == 'grb_editor':
  171. self.snap_center_cb.show()
  172. snap_center = self.app.defaults['tools_dist_snap_center']
  173. self.on_snap_toggled(snap_center)
  174. self.snap_center_cb.toggled.connect(self.on_snap_toggled)
  175. else:
  176. self.snap_center_cb.hide()
  177. try:
  178. self.snap_center_cb.toggled.disconnect(self.on_snap_toggled)
  179. except (TypeError, AttributeError):
  180. pass
  181. # this is a hack; seems that triggering the grid will make the visuals better
  182. # trigger it twice to return to the original state
  183. self.app.ui.grid_snap_btn.trigger()
  184. self.app.ui.grid_snap_btn.trigger()
  185. if self.app.ui.grid_snap_btn.isChecked():
  186. self.grid_status_memory = True
  187. log.debug("Distance Tool --> tool initialized")
  188. def on_snap_toggled(self, state):
  189. self.app.defaults['tools_dist_snap_center'] = state
  190. if state:
  191. # disengage the grid snapping since it will be hard to find the drills or pads on grid
  192. if self.app.ui.grid_snap_btn.isChecked():
  193. self.app.ui.grid_snap_btn.trigger()
  194. def activate_measure_tool(self):
  195. # ENABLE the Measuring TOOL
  196. self.active = True
  197. # disable the measuring button
  198. self.measure_btn.setDisabled(True)
  199. self.measure_btn.setText('%s...' % _("Working"))
  200. self.clicked_meas = 0
  201. self.original_call_source = copy(self.app.call_source)
  202. self.app.inform.emit(_("MEASURING: Click on the Start point ..."))
  203. self.units = self.app.defaults['units'].lower()
  204. # we can connect the app mouse events to the measurement tool
  205. # NEVER DISCONNECT THOSE before connecting some other handlers; it breaks something in VisPy
  206. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_mouse_move_meas)
  207. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  208. # we disconnect the mouse/key handlers from wherever the measurement tool was called
  209. if self.app.call_source == 'app':
  210. if self.app.is_legacy is False:
  211. self.canvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  212. self.canvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  213. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  214. else:
  215. self.canvas.graph_event_disconnect(self.app.mm)
  216. self.canvas.graph_event_disconnect(self.app.mp)
  217. self.canvas.graph_event_disconnect(self.app.mr)
  218. elif self.app.call_source == 'geo_editor':
  219. if self.app.is_legacy is False:
  220. self.canvas.graph_event_disconnect('mouse_move', self.app.geo_editor.on_canvas_move)
  221. self.canvas.graph_event_disconnect('mouse_press', self.app.geo_editor.on_canvas_click)
  222. self.canvas.graph_event_disconnect('mouse_release', self.app.geo_editor.on_geo_click_release)
  223. else:
  224. self.canvas.graph_event_disconnect(self.app.geo_editor.mm)
  225. self.canvas.graph_event_disconnect(self.app.geo_editor.mp)
  226. self.canvas.graph_event_disconnect(self.app.geo_editor.mr)
  227. elif self.app.call_source == 'exc_editor':
  228. if self.app.is_legacy is False:
  229. self.canvas.graph_event_disconnect('mouse_move', self.app.exc_editor.on_canvas_move)
  230. self.canvas.graph_event_disconnect('mouse_press', self.app.exc_editor.on_canvas_click)
  231. self.canvas.graph_event_disconnect('mouse_release', self.app.exc_editor.on_exc_click_release)
  232. else:
  233. self.canvas.graph_event_disconnect(self.app.exc_editor.mm)
  234. self.canvas.graph_event_disconnect(self.app.exc_editor.mp)
  235. self.canvas.graph_event_disconnect(self.app.exc_editor.mr)
  236. elif self.app.call_source == 'grb_editor':
  237. if self.app.is_legacy is False:
  238. self.canvas.graph_event_disconnect('mouse_move', self.app.grb_editor.on_canvas_move)
  239. self.canvas.graph_event_disconnect('mouse_press', self.app.grb_editor.on_canvas_click)
  240. self.canvas.graph_event_disconnect('mouse_release', self.app.grb_editor.on_grb_click_release)
  241. else:
  242. self.canvas.graph_event_disconnect(self.app.grb_editor.mm)
  243. self.canvas.graph_event_disconnect(self.app.grb_editor.mp)
  244. self.canvas.graph_event_disconnect(self.app.grb_editor.mr)
  245. self.app.call_source = 'measurement'
  246. self.set_tool_ui()
  247. def deactivate_measure_tool(self):
  248. # DISABLE the Measuring TOOL
  249. self.active = False
  250. self.points = []
  251. # disable the measuring button
  252. self.measure_btn.setDisabled(False)
  253. self.measure_btn.setText(_("Measure"))
  254. self.app.call_source = copy(self.original_call_source)
  255. if self.original_call_source == 'app':
  256. self.app.mm = self.canvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  257. self.app.mp = self.canvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  258. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  259. elif self.original_call_source == 'geo_editor':
  260. self.app.geo_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.geo_editor.on_canvas_move)
  261. self.app.geo_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.geo_editor.on_canvas_click)
  262. self.app.geo_editor.mr = self.canvas.graph_event_connect('mouse_release',
  263. self.app.geo_editor.on_geo_click_release)
  264. elif self.original_call_source == 'exc_editor':
  265. self.app.exc_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.exc_editor.on_canvas_move)
  266. self.app.exc_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.exc_editor.on_canvas_click)
  267. self.app.exc_editor.mr = self.canvas.graph_event_connect('mouse_release',
  268. self.app.exc_editor.on_exc_click_release)
  269. elif self.original_call_source == 'grb_editor':
  270. self.app.grb_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.grb_editor.on_canvas_move)
  271. self.app.grb_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.grb_editor.on_canvas_click)
  272. self.app.grb_editor.mr = self.canvas.graph_event_connect('mouse_release',
  273. self.app.grb_editor.on_grb_click_release)
  274. # disconnect the mouse/key events from functions of measurement tool
  275. if self.app.is_legacy is False:
  276. self.canvas.graph_event_disconnect('mouse_move', self.on_mouse_move_meas)
  277. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  278. else:
  279. self.canvas.graph_event_disconnect(self.mm)
  280. self.canvas.graph_event_disconnect(self.mr)
  281. # self.app.ui.notebook.setTabText(2, _("Tools"))
  282. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  283. self.app.command_active = None
  284. # delete the measuring line
  285. self.delete_shape()
  286. # restore the grid status
  287. if (self.app.ui.grid_snap_btn.isChecked() and self.grid_status_memory is False) or \
  288. (not self.app.ui.grid_snap_btn.isChecked() and self.grid_status_memory is True):
  289. self.app.ui.grid_snap_btn.trigger()
  290. log.debug("Distance Tool --> exit tool")
  291. if self.tool_done is False:
  292. self.app.inform.emit('%s' % _("Distance Tool finished."))
  293. def on_mouse_click_release(self, event):
  294. # mouse click releases will be accepted only if the left button is clicked
  295. # this is necessary because right mouse click or middle mouse click
  296. # are used for panning on the canvas
  297. log.debug("Distance Tool --> mouse click release")
  298. if event.button == 1:
  299. if self.app.is_legacy is False:
  300. event_pos = event.pos
  301. else:
  302. event_pos = (event.xdata, event.ydata)
  303. pos_canvas = self.canvas.translate_coords(event_pos)
  304. if self.snap_center_cb.get_value() is False:
  305. # if GRID is active we need to get the snapped positions
  306. if self.app.grid_status():
  307. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  308. else:
  309. pos = pos_canvas[0], pos_canvas[1]
  310. else:
  311. pos = (pos_canvas[0], pos_canvas[1])
  312. current_pt = Point(pos)
  313. shapes_storage = self.make_storage()
  314. if self.original_call_source == 'exc_editor':
  315. for storage in self.app.exc_editor.storage_dict:
  316. __, st_closest_shape = self.app.exc_editor.storage_dict[storage].nearest(pos)
  317. shapes_storage.insert(st_closest_shape)
  318. __, closest_shape = shapes_storage.nearest(pos)
  319. # if it's a drill
  320. if isinstance(closest_shape.geo, MultiLineString):
  321. radius = closest_shape.geo[0].length / 2.0
  322. center_pt = closest_shape.geo.centroid
  323. geo_buffered = center_pt.buffer(radius)
  324. if current_pt.within(geo_buffered):
  325. pos = (center_pt.x, center_pt.y)
  326. # if it's a slot
  327. elif isinstance(closest_shape.geo, Polygon):
  328. geo_buffered = closest_shape.geo.buffer(0)
  329. center_pt = geo_buffered.centroid
  330. if current_pt.within(geo_buffered):
  331. pos = (center_pt.x, center_pt.y)
  332. elif self.original_call_source == 'grb_editor':
  333. clicked_pads = []
  334. for storage in self.app.grb_editor.storage_dict:
  335. try:
  336. for shape_stored in self.app.grb_editor.storage_dict[storage]['geometry']:
  337. if 'solid' in shape_stored.geo:
  338. geometric_data = shape_stored.geo['solid']
  339. if Point(current_pt).within(geometric_data):
  340. if isinstance(shape_stored.geo['follow'], Point):
  341. clicked_pads.append(shape_stored.geo['follow'])
  342. except KeyError:
  343. pass
  344. if len(clicked_pads) > 1:
  345. self.tool_done = True
  346. self.deactivate_measure_tool()
  347. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Pads overlapped. Aborting."))
  348. return
  349. pos = (clicked_pads[0].x, clicked_pads[0].y)
  350. self.app.on_jump_to(custom_location=pos, fit_center=False)
  351. # Update cursor
  352. self.app.app_cursor.enabled = True
  353. self.app.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  354. symbol='++', edge_color='#000000',
  355. edge_width=self.app.defaults["global_cursor_width"],
  356. size=self.app.defaults["global_cursor_size"])
  357. self.points.append(pos)
  358. # Reset here the relative coordinates so there is a new reference on the click position
  359. if self.rel_point1 is None:
  360. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.*f&nbsp;&nbsp; <b>Dy</b>: "
  361. "%.*f&nbsp;&nbsp;&nbsp;&nbsp;" %
  362. (self.decimals, 0.0, self.decimals, 0.0))
  363. self.rel_point1 = pos
  364. else:
  365. self.rel_point2 = copy(self.rel_point1)
  366. self.rel_point1 = pos
  367. self.calculate_distance(pos=pos)
  368. def calculate_distance(self, pos):
  369. if len(self.points) == 1:
  370. self.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  371. self.app.inform.emit(_("MEASURING: Click on the Destination point ..."))
  372. elif len(self.points) == 2:
  373. # self.app.app_cursor.enabled = False
  374. dx = self.points[1][0] - self.points[0][0]
  375. dy = self.points[1][1] - self.points[0][1]
  376. d = math.sqrt(dx ** 2 + dy ** 2)
  377. self.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  378. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  379. tx1=_("MEASURING"),
  380. tx2=_("Result"),
  381. tx3=_("Distance"),
  382. d_x='%*f' % (self.decimals, abs(dx)),
  383. d_y='%*f' % (self.decimals, abs(dy)),
  384. d_z='%*f' % (self.decimals, abs(d)))
  385. )
  386. self.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  387. self.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  388. if dx != 0.0:
  389. try:
  390. angle = math.degrees(math.atan(dy / dx))
  391. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  392. except Exception:
  393. pass
  394. self.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  395. self.app.ui.rel_position_label.setText(
  396. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  397. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  398. )
  399. )
  400. self.tool_done = True
  401. self.deactivate_measure_tool()
  402. def on_mouse_move_meas(self, event):
  403. try: # May fail in case mouse not within axes
  404. if self.app.is_legacy is False:
  405. event_pos = event.pos
  406. else:
  407. event_pos = (event.xdata, event.ydata)
  408. try:
  409. x = float(event_pos[0])
  410. y = float(event_pos[1])
  411. except TypeError:
  412. return
  413. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  414. if self.app.grid_status():
  415. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  416. # Update cursor
  417. self.app.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  418. symbol='++', edge_color=self.app.cursor_color_3D,
  419. edge_width=self.app.defaults["global_cursor_width"],
  420. size=self.app.defaults["global_cursor_size"])
  421. else:
  422. pos = (pos_canvas[0], pos_canvas[1])
  423. self.app.ui.position_label.setText(
  424. "&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: {}&nbsp;&nbsp; <b>Y</b>: {}".format(
  425. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  426. )
  427. )
  428. if self.rel_point1 is not None:
  429. dx = pos[0] - float(self.rel_point1[0])
  430. dy = pos[1] - float(self.rel_point1[1])
  431. else:
  432. dx = pos[0]
  433. dy = pos[1]
  434. self.app.ui.rel_position_label.setText(
  435. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  436. '%.*f' % (self.decimals, dx), '%.*f' % (self.decimals, dy)
  437. )
  438. )
  439. # update utility geometry
  440. if len(self.points) == 1:
  441. self.utility_geometry(pos=pos)
  442. # and display the temporary angle
  443. if dx != 0.0:
  444. try:
  445. angle = math.degrees(math.atan(dy / dx))
  446. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  447. except Exception as e:
  448. log.debug("Distance.on_mouse_move_meas() -> update utility geometry -> %s" % str(e))
  449. pass
  450. except Exception as e:
  451. log.debug("Distance.on_mouse_move_meas() --> %s" % str(e))
  452. self.app.ui.position_label.setText("")
  453. self.app.ui.rel_position_label.setText("")
  454. def utility_geometry(self, pos):
  455. # first delete old shape
  456. self.delete_shape()
  457. # second draw the new shape of the utility geometry
  458. meas_line = LineString([pos, self.points[0]])
  459. settings = QtCore.QSettings("Open Source", "FlatCAM")
  460. if settings.contains("theme"):
  461. theme = settings.value('theme', type=str)
  462. else:
  463. theme = 'white'
  464. if theme == 'white':
  465. color = '#000000FF'
  466. else:
  467. color = '#FFFFFFFF'
  468. self.sel_shapes.add(meas_line, color=color, update=True, layer=0, tolerance=None)
  469. if self.app.is_legacy is True:
  470. self.sel_shapes.redraw()
  471. def delete_shape(self):
  472. self.sel_shapes.clear()
  473. self.sel_shapes.redraw()
  474. @staticmethod
  475. def make_storage():
  476. # ## Shape storage.
  477. storage = FlatCAMRTreeStorage()
  478. storage.get_points = DrawToolShape.get_pts
  479. return storage
  480. # def set_meas_units(self, units):
  481. # self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  482. # end of file