ToolDistanceMin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 09/29/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCEntry
  10. from shapely.ops import nearest_points
  11. from shapely.geometry import Point, MultiPolygon
  12. from shapely.ops import unary_union
  13. import math
  14. import logging
  15. import gettext
  16. import appTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. log = logging.getLogger('base')
  22. class DistanceMin(AppTool):
  23. def __init__(self, app):
  24. AppTool.__init__(self, app)
  25. self.app = app
  26. self.canvas = self.app.plotcanvas
  27. self.units = self.app.defaults['units'].lower()
  28. self.decimals = self.app.decimals
  29. # #############################################################################
  30. # ######################### Tool GUI ##########################################
  31. # #############################################################################
  32. self.ui = DistMinUI(layout=self.layout, app=self.app)
  33. self.toolName = self.ui.toolName
  34. self.h_point = (0, 0)
  35. self.ui.measure_btn.clicked.connect(self.activate_measure_tool)
  36. self.ui.jump_hp_btn.clicked.connect(self.on_jump_to_half_point)
  37. def run(self, toggle=False):
  38. self.app.defaults.report_usage("ToolDistanceMin()")
  39. if self.app.tool_tab_locked is True:
  40. return
  41. self.app.ui.notebook.setTabText(2, _("Minimum Distance Tool"))
  42. # if the splitter is hidden, display it
  43. if self.app.ui.splitter.sizes()[0] == 0:
  44. self.app.ui.splitter.setSizes([1, 1])
  45. if toggle:
  46. pass
  47. self.set_tool_ui()
  48. self.app.inform.emit('MEASURING: %s' %
  49. _("Select two objects and no more, to measure the distance between them ..."))
  50. def install(self, icon=None, separator=None, **kwargs):
  51. AppTool.install(self, icon, separator, shortcut='Shift+M', **kwargs)
  52. def set_tool_ui(self):
  53. # Remove anything else in the appGUI
  54. self.app.ui.tool_scroll_area.takeWidget()
  55. # Put oneself in the appGUI
  56. self.app.ui.tool_scroll_area.setWidget(self)
  57. # Switch notebook to tool page
  58. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  59. self.units = self.app.defaults['units'].lower()
  60. # initial view of the layout
  61. self.ui.start_entry.set_value('(0, 0)')
  62. self.ui.stop_entry.set_value('(0, 0)')
  63. self.ui.distance_x_entry.set_value('0.0')
  64. self.ui.distance_y_entry.set_value('0.0')
  65. self.ui.angle_entry.set_value('0.0')
  66. self.ui.total_distance_entry.set_value('0.0')
  67. self.ui.half_point_entry.set_value('(0, 0)')
  68. self.ui.jump_hp_btn.setDisabled(True)
  69. log.debug("Minimum Distance Tool --> tool initialized")
  70. def activate_measure_tool(self):
  71. # ENABLE the Measuring TOOL
  72. self.ui.jump_hp_btn.setDisabled(False)
  73. self.units = self.app.defaults['units'].lower()
  74. if self.app.call_source == 'app':
  75. selected_objs = self.app.collection.get_selected()
  76. if len(selected_objs) != 2:
  77. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  78. (_("Select two objects and no more. Currently the selection has objects: "),
  79. str(len(selected_objs))))
  80. return
  81. else:
  82. if isinstance(selected_objs[0].solid_geometry, list):
  83. try:
  84. selected_objs[0].solid_geometry = MultiPolygon(selected_objs[0].solid_geometry)
  85. except Exception:
  86. selected_objs[0].solid_geometry = unary_union(selected_objs[0].solid_geometry)
  87. try:
  88. selected_objs[1].solid_geometry = MultiPolygon(selected_objs[1].solid_geometry)
  89. except Exception:
  90. selected_objs[1].solid_geometry = unary_union(selected_objs[1].solid_geometry)
  91. first_pos, last_pos = nearest_points(selected_objs[0].solid_geometry, selected_objs[1].solid_geometry)
  92. elif self.app.call_source == 'geo_editor':
  93. selected_objs = self.app.geo_editor.selected
  94. if len(selected_objs) != 2:
  95. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  96. (_("Select two objects and no more. Currently the selection has objects: "),
  97. str(len(selected_objs))))
  98. return
  99. else:
  100. first_pos, last_pos = nearest_points(selected_objs[0].geo, selected_objs[1].geo)
  101. elif self.app.call_source == 'exc_editor':
  102. selected_objs = self.app.exc_editor.selected
  103. if len(selected_objs) != 2:
  104. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  105. (_("Select two objects and no more. Currently the selection has objects: "),
  106. str(len(selected_objs))))
  107. return
  108. else:
  109. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  110. xmin, ymin, xmax, ymax = selected_objs[0].geo.bounds
  111. first_geo_radius = (xmax - xmin) / 2
  112. first_geo_center = Point(xmin + first_geo_radius, ymin + first_geo_radius)
  113. first_geo = first_geo_center.buffer(first_geo_radius)
  114. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  115. xmin, ymin, xmax, ymax = selected_objs[1].geo.bounds
  116. last_geo_radius = (xmax - xmin) / 2
  117. last_geo_center = Point(xmin + last_geo_radius, ymin + last_geo_radius)
  118. last_geo = last_geo_center.buffer(last_geo_radius)
  119. first_pos, last_pos = nearest_points(first_geo, last_geo)
  120. elif self.app.call_source == 'grb_editor':
  121. selected_objs = self.app.grb_editor.selected
  122. if len(selected_objs) != 2:
  123. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  124. (_("Select two objects and no more. Currently the selection has objects: "),
  125. str(len(selected_objs))))
  126. return
  127. else:
  128. first_pos, last_pos = nearest_points(selected_objs[0].geo['solid'], selected_objs[1].geo['solid'])
  129. else:
  130. first_pos, last_pos = 0, 0
  131. self.ui.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, first_pos.x, self.decimals, first_pos.y))
  132. self.ui.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, last_pos.x, self.decimals, last_pos.y))
  133. dx = first_pos.x - last_pos.x
  134. dy = first_pos.y - last_pos.y
  135. self.ui.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  136. self.ui.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  137. try:
  138. angle = math.degrees(math.atan(dy / dx))
  139. self.ui.angle_entry.set_value('%.*f' % (self.decimals, angle))
  140. except Exception:
  141. pass
  142. d = math.sqrt(dx ** 2 + dy ** 2)
  143. self.ui.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  144. self.h_point = (min(first_pos.x, last_pos.x) + (abs(dx) / 2), min(first_pos.y, last_pos.y) + (abs(dy) / 2))
  145. if d != 0:
  146. self.ui.half_point_entry.set_value(
  147. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])
  148. )
  149. else:
  150. self.ui.half_point_entry.set_value(
  151. "(%.*f, %.*f)" % (self.decimals, 0.0, self.decimals, 0.0)
  152. )
  153. if d != 0:
  154. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  155. tx1=_("MEASURING"),
  156. tx2=_("Result"),
  157. tx3=_("Distance"),
  158. d_x='%*f' % (self.decimals, abs(dx)),
  159. d_y='%*f' % (self.decimals, abs(dy)),
  160. d_z='%*f' % (self.decimals, abs(d)))
  161. )
  162. else:
  163. self.app.inform.emit('[WARNING_NOTCL] %s: %s' %
  164. (_("Objects intersects or touch at"),
  165. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  166. def on_jump_to_half_point(self):
  167. self.app.on_jump_to(custom_location=self.h_point)
  168. self.app.inform.emit('[success] %s: %s' %
  169. (_("Jumped to the half point between the two selected objects"),
  170. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  171. # def set_meas_units(self, units):
  172. # self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  173. class DistMinUI:
  174. toolName = _("Minimum Distance Tool")
  175. def __init__(self, layout, app):
  176. self.app = app
  177. self.decimals = self.app.decimals
  178. self.layout = layout
  179. self.units = self.app.defaults['units'].lower()
  180. # ## Title
  181. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font><br>" % self.toolName)
  182. self.layout.addWidget(title_label)
  183. # ## Form Layout
  184. form_layout = QtWidgets.QFormLayout()
  185. self.layout.addLayout(form_layout)
  186. self.units_label = QtWidgets.QLabel('%s:' % _("Units"))
  187. self.units_label.setToolTip(_("Those are the units in which the distance is measured."))
  188. self.units_value = QtWidgets.QLabel("%s" % str({'mm': _("METRIC (mm)"), 'in': _("INCH (in)")}[self.units]))
  189. self.units_value.setDisabled(True)
  190. self.start_label = QtWidgets.QLabel("%s:" % _('First object point'))
  191. self.start_label.setToolTip(_("This is first object point coordinates.\n"
  192. "This is the start point for measuring distance."))
  193. self.stop_label = QtWidgets.QLabel("%s:" % _('Second object point'))
  194. self.stop_label.setToolTip(_("This is second object point coordinates.\n"
  195. "This is the end point for measuring distance."))
  196. self.distance_x_label = QtWidgets.QLabel('%s:' % _("Dx"))
  197. self.distance_x_label.setToolTip(_("This is the distance measured over the X axis."))
  198. self.distance_y_label = QtWidgets.QLabel('%s:' % _("Dy"))
  199. self.distance_y_label.setToolTip(_("This is the distance measured over the Y axis."))
  200. self.angle_label = QtWidgets.QLabel('%s:' % _("Angle"))
  201. self.angle_label.setToolTip(_("This is orientation angle of the measuring line."))
  202. self.total_distance_label = QtWidgets.QLabel("<b>%s:</b>" % _('DISTANCE'))
  203. self.total_distance_label.setToolTip(_("This is the point to point Euclidean distance."))
  204. self.half_point_label = QtWidgets.QLabel("<b>%s:</b>" % _('Half Point'))
  205. self.half_point_label.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  206. self.start_entry = FCEntry()
  207. self.start_entry.setReadOnly(True)
  208. self.start_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  209. self.start_entry.setToolTip(_("This is first object point coordinates.\n"
  210. "This is the start point for measuring distance."))
  211. self.stop_entry = FCEntry()
  212. self.stop_entry.setReadOnly(True)
  213. self.stop_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  214. self.stop_entry.setToolTip(_("This is second object point coordinates.\n"
  215. "This is the end point for measuring distance."))
  216. self.distance_x_entry = FCEntry()
  217. self.distance_x_entry.setReadOnly(True)
  218. self.distance_x_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  219. self.distance_x_entry.setToolTip(_("This is the distance measured over the X axis."))
  220. self.distance_y_entry = FCEntry()
  221. self.distance_y_entry.setReadOnly(True)
  222. self.distance_y_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  223. self.distance_y_entry.setToolTip(_("This is the distance measured over the Y axis."))
  224. self.angle_entry = FCEntry()
  225. self.angle_entry.setReadOnly(True)
  226. self.angle_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  227. self.angle_entry.setToolTip(_("This is orientation angle of the measuring line."))
  228. self.total_distance_entry = FCEntry()
  229. self.total_distance_entry.setReadOnly(True)
  230. self.total_distance_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  231. self.total_distance_entry.setToolTip(_("This is the point to point Euclidean distance."))
  232. self.half_point_entry = FCEntry()
  233. self.half_point_entry.setReadOnly(True)
  234. self.half_point_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  235. self.half_point_entry.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  236. self.measure_btn = QtWidgets.QPushButton(_("Measure"))
  237. self.layout.addWidget(self.measure_btn)
  238. self.jump_hp_btn = QtWidgets.QPushButton(_("Jump to Half Point"))
  239. self.layout.addWidget(self.jump_hp_btn)
  240. self.jump_hp_btn.setDisabled(True)
  241. form_layout.addRow(self.units_label, self.units_value)
  242. form_layout.addRow(self.start_label, self.start_entry)
  243. form_layout.addRow(self.stop_label, self.stop_entry)
  244. form_layout.addRow(self.distance_x_label, self.distance_x_entry)
  245. form_layout.addRow(self.distance_y_label, self.distance_y_entry)
  246. form_layout.addRow(self.angle_label, self.angle_entry)
  247. form_layout.addRow(self.total_distance_label, self.total_distance_entry)
  248. form_layout.addRow(self.half_point_label, self.half_point_entry)
  249. self.layout.addStretch()
  250. # #################################### FINSIHED GUI ###########################
  251. # #############################################################################
  252. def confirmation_message(self, accepted, minval, maxval):
  253. if accepted is False:
  254. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  255. self.decimals,
  256. minval,
  257. self.decimals,
  258. maxval), False)
  259. else:
  260. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  261. def confirmation_message_int(self, accepted, minval, maxval):
  262. if accepted is False:
  263. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  264. (_("Edited value is out of range"), minval, maxval), False)
  265. else:
  266. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)