ToolDistance.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. self.snap_center_cb.toggled.connect(self.on_snap_toggled)
  133. def run(self, toggle=False):
  134. self.app.report_usage("ToolDistance()")
  135. self.points[:] = []
  136. self.rel_point1 = None
  137. self.rel_point2 = None
  138. self.tool_done = False
  139. if self.app.tool_tab_locked is True:
  140. return
  141. self.app.ui.notebook.setTabText(2, _("Distance Tool"))
  142. # if the splitter is hidden, display it
  143. if self.app.ui.splitter.sizes()[0] == 0:
  144. self.app.ui.splitter.setSizes([1, 1])
  145. if toggle:
  146. pass
  147. if self.active is False:
  148. self.activate_measure_tool()
  149. else:
  150. self.deactivate_measure_tool()
  151. def install(self, icon=None, separator=None, **kwargs):
  152. FlatCAMTool.install(self, icon, separator, shortcut='CTRL+M', **kwargs)
  153. def set_tool_ui(self):
  154. # Remove anything else in the GUI
  155. self.app.ui.tool_scroll_area.takeWidget()
  156. # Put ourselves in the GUI
  157. self.app.ui.tool_scroll_area.setWidget(self)
  158. # Switch notebook to tool page
  159. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  160. self.units = self.app.defaults['units'].lower()
  161. self.app.command_active = "Distance"
  162. # initial view of the layout
  163. self.start_entry.set_value('(0, 0)')
  164. self.stop_entry.set_value('(0, 0)')
  165. self.distance_x_entry.set_value('0.0')
  166. self.distance_y_entry.set_value('0.0')
  167. self.angle_entry.set_value('0.0')
  168. self.total_distance_entry.set_value('0.0')
  169. self.snap_center_cb.set_value(self.app.defaults['tools_dist_snap_center'])
  170. # snap center works only for Gerber and Execellon Editor's
  171. if self.original_call_source == 'exc_editor' or self.original_call_source == 'grb_editor':
  172. self.snap_center_cb.show()
  173. else:
  174. self.snap_center_cb.hide()
  175. # this is a hack; seems that triggering the grid will make the visuals better
  176. # trigger it twice to return to the original state
  177. self.app.ui.grid_snap_btn.trigger()
  178. self.app.ui.grid_snap_btn.trigger()
  179. if self.app.ui.grid_snap_btn.isChecked():
  180. self.grid_status_memory = True
  181. log.debug("Distance Tool --> tool initialized")
  182. def on_snap_toggled(self, state):
  183. self.app.defaults['tools_dist_snap_center'] = state
  184. if state:
  185. # disengage the grid snapping since it will be hard to find the drills or pads on grid
  186. if self.app.ui.grid_snap_btn.isChecked():
  187. self.app.ui.grid_snap_btn.trigger()
  188. def activate_measure_tool(self):
  189. # ENABLE the Measuring TOOL
  190. self.active = True
  191. # disable the measuring button
  192. self.measure_btn.setDisabled(True)
  193. self.measure_btn.setText('%s...' % _("Working"))
  194. self.clicked_meas = 0
  195. self.original_call_source = copy(self.app.call_source)
  196. snap_center = self.app.defaults['tools_dist_snap_center']
  197. self.on_snap_toggled(snap_center)
  198. self.app.inform.emit(_("MEASURING: Click on the Start point ..."))
  199. self.units = self.app.defaults['units'].lower()
  200. # we can connect the app mouse events to the measurement tool
  201. # NEVER DISCONNECT THOSE before connecting some other handlers; it breaks something in VisPy
  202. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_mouse_move_meas)
  203. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  204. # we disconnect the mouse/key handlers from wherever the measurement tool was called
  205. if self.app.call_source == 'app':
  206. if self.app.is_legacy is False:
  207. self.canvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  208. self.canvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  209. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  210. else:
  211. self.canvas.graph_event_disconnect(self.app.mm)
  212. self.canvas.graph_event_disconnect(self.app.mp)
  213. self.canvas.graph_event_disconnect(self.app.mr)
  214. elif self.app.call_source == 'geo_editor':
  215. if self.app.is_legacy is False:
  216. self.canvas.graph_event_disconnect('mouse_move', self.app.geo_editor.on_canvas_move)
  217. self.canvas.graph_event_disconnect('mouse_press', self.app.geo_editor.on_canvas_click)
  218. self.canvas.graph_event_disconnect('mouse_release', self.app.geo_editor.on_geo_click_release)
  219. else:
  220. self.canvas.graph_event_disconnect(self.app.geo_editor.mm)
  221. self.canvas.graph_event_disconnect(self.app.geo_editor.mp)
  222. self.canvas.graph_event_disconnect(self.app.geo_editor.mr)
  223. elif self.app.call_source == 'exc_editor':
  224. if self.app.is_legacy is False:
  225. self.canvas.graph_event_disconnect('mouse_move', self.app.exc_editor.on_canvas_move)
  226. self.canvas.graph_event_disconnect('mouse_press', self.app.exc_editor.on_canvas_click)
  227. self.canvas.graph_event_disconnect('mouse_release', self.app.exc_editor.on_exc_click_release)
  228. else:
  229. self.canvas.graph_event_disconnect(self.app.exc_editor.mm)
  230. self.canvas.graph_event_disconnect(self.app.exc_editor.mp)
  231. self.canvas.graph_event_disconnect(self.app.exc_editor.mr)
  232. elif self.app.call_source == 'grb_editor':
  233. if self.app.is_legacy is False:
  234. self.canvas.graph_event_disconnect('mouse_move', self.app.grb_editor.on_canvas_move)
  235. self.canvas.graph_event_disconnect('mouse_press', self.app.grb_editor.on_canvas_click)
  236. self.canvas.graph_event_disconnect('mouse_release', self.app.grb_editor.on_grb_click_release)
  237. else:
  238. self.canvas.graph_event_disconnect(self.app.grb_editor.mm)
  239. self.canvas.graph_event_disconnect(self.app.grb_editor.mp)
  240. self.canvas.graph_event_disconnect(self.app.grb_editor.mr)
  241. self.app.call_source = 'measurement'
  242. self.set_tool_ui()
  243. def deactivate_measure_tool(self):
  244. # DISABLE the Measuring TOOL
  245. self.active = False
  246. self.points = []
  247. # disable the measuring button
  248. self.measure_btn.setDisabled(False)
  249. self.measure_btn.setText(_("Measure"))
  250. self.app.call_source = copy(self.original_call_source)
  251. if self.original_call_source == 'app':
  252. self.app.mm = self.canvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  253. self.app.mp = self.canvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  254. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  255. elif self.original_call_source == 'geo_editor':
  256. self.app.geo_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.geo_editor.on_canvas_move)
  257. self.app.geo_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.geo_editor.on_canvas_click)
  258. self.app.geo_editor.mr = self.canvas.graph_event_connect('mouse_release',
  259. self.app.geo_editor.on_geo_click_release)
  260. elif self.original_call_source == 'exc_editor':
  261. self.app.exc_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.exc_editor.on_canvas_move)
  262. self.app.exc_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.exc_editor.on_canvas_click)
  263. self.app.exc_editor.mr = self.canvas.graph_event_connect('mouse_release',
  264. self.app.exc_editor.on_exc_click_release)
  265. elif self.original_call_source == 'grb_editor':
  266. self.app.grb_editor.mm = self.canvas.graph_event_connect('mouse_move', self.app.grb_editor.on_canvas_move)
  267. self.app.grb_editor.mp = self.canvas.graph_event_connect('mouse_press', self.app.grb_editor.on_canvas_click)
  268. self.app.grb_editor.mr = self.canvas.graph_event_connect('mouse_release',
  269. self.app.grb_editor.on_grb_click_release)
  270. # disconnect the mouse/key events from functions of measurement tool
  271. if self.app.is_legacy is False:
  272. self.canvas.graph_event_disconnect('mouse_move', self.on_mouse_move_meas)
  273. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  274. else:
  275. self.canvas.graph_event_disconnect(self.mm)
  276. self.canvas.graph_event_disconnect(self.mr)
  277. # self.app.ui.notebook.setTabText(2, _("Tools"))
  278. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  279. self.app.command_active = None
  280. # delete the measuring line
  281. self.delete_shape()
  282. # restore the grid status
  283. if (self.app.ui.grid_snap_btn.isChecked() and self.grid_status_memory is False) or \
  284. (not self.app.ui.grid_snap_btn.isChecked() and self.grid_status_memory is True):
  285. self.app.ui.grid_snap_btn.trigger()
  286. log.debug("Distance Tool --> exit tool")
  287. if self.tool_done is False:
  288. self.app.inform.emit('%s' % _("Distance Tool finished."))
  289. def on_mouse_click_release(self, event):
  290. # mouse click releases will be accepted only if the left button is clicked
  291. # this is necessary because right mouse click or middle mouse click
  292. # are used for panning on the canvas
  293. log.debug("Distance Tool --> mouse click release")
  294. if event.button == 1:
  295. if self.app.is_legacy is False:
  296. event_pos = event.pos
  297. else:
  298. event_pos = (event.xdata, event.ydata)
  299. pos_canvas = self.canvas.translate_coords(event_pos)
  300. if self.snap_center_cb.get_value() is False:
  301. # if GRID is active we need to get the snapped positions
  302. if self.app.grid_status():
  303. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  304. else:
  305. pos = pos_canvas[0], pos_canvas[1]
  306. else:
  307. pos = (pos_canvas[0], pos_canvas[1])
  308. current_pt = Point(pos)
  309. shapes_storage = self.make_storage()
  310. if self.original_call_source == 'exc_editor':
  311. for storage in self.app.exc_editor.storage_dict:
  312. __, st_closest_shape = self.app.exc_editor.storage_dict[storage].nearest(pos)
  313. shapes_storage.insert(st_closest_shape)
  314. __, closest_shape = shapes_storage.nearest(pos)
  315. # if it's a drill
  316. if isinstance(closest_shape.geo, MultiLineString):
  317. radius = closest_shape.geo[0].length / 2.0
  318. center_pt = closest_shape.geo.centroid
  319. geo_buffered = center_pt.buffer(radius)
  320. if current_pt.within(geo_buffered):
  321. pos = (center_pt.x, center_pt.y)
  322. # if it's a slot
  323. elif isinstance(closest_shape.geo, Polygon):
  324. geo_buffered = closest_shape.geo.buffer(0)
  325. center_pt = geo_buffered.centroid
  326. if current_pt.within(geo_buffered):
  327. pos = (center_pt.x, center_pt.y)
  328. elif self.original_call_source == 'grb_editor':
  329. clicked_pads = list()
  330. for storage in self.app.grb_editor.storage_dict:
  331. try:
  332. for shape_stored in self.app.grb_editor.storage_dict[storage]['geometry']:
  333. if 'solid' in shape_stored.geo:
  334. geometric_data = shape_stored.geo['solid']
  335. if Point(current_pt).within(geometric_data):
  336. if isinstance(shape_stored.geo['follow'], Point):
  337. clicked_pads.append(shape_stored.geo['follow'])
  338. except KeyError:
  339. pass
  340. if len(clicked_pads) > 1:
  341. self.tool_done = True
  342. self.deactivate_measure_tool()
  343. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Pads overlapped. Aborting."))
  344. return
  345. pos = (clicked_pads[0].x, clicked_pads[0].y)
  346. self.app.on_jump_to(custom_location=pos, fit_center=False)
  347. # Update cursor
  348. self.app.app_cursor.enabled = True
  349. self.app.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  350. symbol='++', edge_color='#000000',
  351. edge_width=self.app.defaults["global_cursor_width"],
  352. size=self.app.defaults["global_cursor_size"])
  353. self.points.append(pos)
  354. # Reset here the relative coordinates so there is a new reference on the click position
  355. if self.rel_point1 is None:
  356. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.*f&nbsp;&nbsp; <b>Dy</b>: "
  357. "%.*f&nbsp;&nbsp;&nbsp;&nbsp;" %
  358. (self.decimals, 0.0, self.decimals, 0.0))
  359. self.rel_point1 = pos
  360. else:
  361. self.rel_point2 = copy(self.rel_point1)
  362. self.rel_point1 = pos
  363. self.calculate_distance(pos=pos)
  364. def calculate_distance(self, pos):
  365. if len(self.points) == 1:
  366. self.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  367. self.app.inform.emit(_("MEASURING: Click on the Destination point ..."))
  368. elif len(self.points) == 2:
  369. self.app.app_cursor.enabled = False
  370. dx = self.points[1][0] - self.points[0][0]
  371. dy = self.points[1][1] - self.points[0][1]
  372. d = math.sqrt(dx ** 2 + dy ** 2)
  373. self.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, pos[0], self.decimals, pos[1]))
  374. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  375. tx1=_("MEASURING"),
  376. tx2=_("Result"),
  377. tx3=_("Distance"),
  378. d_x='%*f' % (self.decimals, abs(dx)),
  379. d_y='%*f' % (self.decimals, abs(dy)),
  380. d_z='%*f' % (self.decimals, abs(d)))
  381. )
  382. self.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  383. self.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  384. if dx != 0.0:
  385. try:
  386. angle = math.degrees(math.atan(dy / dx))
  387. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  388. except Exception:
  389. pass
  390. self.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  391. self.app.ui.rel_position_label.setText(
  392. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  393. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  394. )
  395. )
  396. self.tool_done = True
  397. self.deactivate_measure_tool()
  398. def on_mouse_move_meas(self, event):
  399. try: # May fail in case mouse not within axes
  400. if self.app.is_legacy is False:
  401. event_pos = event.pos
  402. else:
  403. event_pos = (event.xdata, event.ydata)
  404. try:
  405. x = float(event_pos[0])
  406. y = float(event_pos[1])
  407. except TypeError:
  408. return
  409. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  410. if self.app.grid_status():
  411. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  412. # Update cursor
  413. self.app.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  414. symbol='++', edge_color=self.app.cursor_color_3D,
  415. edge_width=self.app.defaults["global_cursor_width"],
  416. size=self.app.defaults["global_cursor_size"])
  417. else:
  418. pos = (pos_canvas[0], pos_canvas[1])
  419. self.app.ui.position_label.setText(
  420. "&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: {}&nbsp;&nbsp; <b>Y</b>: {}".format(
  421. '%.*f' % (self.decimals, pos[0]), '%.*f' % (self.decimals, pos[1])
  422. )
  423. )
  424. if self.rel_point1 is not None:
  425. dx = pos[0] - float(self.rel_point1[0])
  426. dy = pos[1] - float(self.rel_point1[1])
  427. else:
  428. dx = pos[0]
  429. dy = pos[1]
  430. self.app.ui.rel_position_label.setText(
  431. "<b>Dx</b>: {}&nbsp;&nbsp; <b>Dy</b>: {}&nbsp;&nbsp;&nbsp;&nbsp;".format(
  432. '%.*f' % (self.decimals, dx), '%.*f' % (self.decimals, dy)
  433. )
  434. )
  435. # update utility geometry
  436. if len(self.points) == 1:
  437. self.utility_geometry(pos=pos)
  438. # and display the temporary angle
  439. if dx != 0.0:
  440. try:
  441. angle = math.degrees(math.atan(dy / dx))
  442. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  443. except Exception as e:
  444. log.debug("Distance.on_mouse_move_meas() -> update utility geometry -> %s" % str(e))
  445. pass
  446. except Exception as e:
  447. log.debug("Distance.on_mouse_move_meas() --> %s" % str(e))
  448. self.app.ui.position_label.setText("")
  449. self.app.ui.rel_position_label.setText("")
  450. def utility_geometry(self, pos):
  451. # first delete old shape
  452. self.delete_shape()
  453. # second draw the new shape of the utility geometry
  454. meas_line = LineString([pos, self.points[0]])
  455. settings = QtCore.QSettings("Open Source", "FlatCAM")
  456. if settings.contains("theme"):
  457. theme = settings.value('theme', type=str)
  458. else:
  459. theme = 'white'
  460. if theme == 'white':
  461. color = '#000000FF'
  462. else:
  463. color = '#FFFFFFFF'
  464. self.sel_shapes.add(meas_line, color=color, update=True, layer=0, tolerance=None)
  465. if self.app.is_legacy is True:
  466. self.sel_shapes.redraw()
  467. def delete_shape(self):
  468. self.sel_shapes.clear()
  469. self.sel_shapes.redraw()
  470. @staticmethod
  471. def make_storage():
  472. # ## Shape storage.
  473. storage = FlatCAMRTreeStorage()
  474. storage.get_points = DrawToolShape.get_pts
  475. return storage
  476. # def set_meas_units(self, units):
  477. # self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  478. # end of file