FlatCAMExcEditor.py 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, QSettings
  3. from shapely.geometry import LineString, LinearRing, MultiLineString
  4. from shapely.ops import cascaded_union
  5. import shapely.affinity as affinity
  6. from numpy import arctan2, Inf, array, sqrt, sign, dot
  7. from rtree import index as rtindex
  8. from camlib import *
  9. from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, LengthEntry, RadioSet, SpinBoxDelegate
  10. from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
  11. from copy import copy, deepcopy
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. fcTranslate.apply_language('strings')
  15. import builtins
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class FCDrillAdd(FCShapeTool):
  19. """
  20. Resulting type: MultiLineString
  21. """
  22. def __init__(self, draw_app):
  23. DrawTool.__init__(self, draw_app)
  24. self.name = 'drill_add'
  25. self.selected_dia = None
  26. try:
  27. self.draw_app.app.inform.emit(self.start_msg)
  28. # self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.tools_table_exc.currentRow() + 1]
  29. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  30. # as a visual marker, select again in tooltable the actual tool that we are using
  31. # remember that it was deselected when clicking on canvas
  32. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  33. self.draw_app.tools_table_exc.setCurrentItem(item)
  34. except KeyError:
  35. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  36. self.draw_app.select_tool("select")
  37. return
  38. try:
  39. QtGui.QGuiApplication.restoreOverrideCursor()
  40. except:
  41. pass
  42. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill.png'))
  43. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  44. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  45. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  46. self.draw_app.draw_utility_geometry(geo=geo)
  47. self.draw_app.app.inform.emit(_("Click on target location ..."))
  48. # Switch notebook to Selected page
  49. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  50. def click(self, point):
  51. self.make()
  52. return "Done."
  53. def utility_geometry(self, data=None):
  54. self.points = data
  55. return DrawToolUtilityShape(self.util_shape(data))
  56. def util_shape(self, point):
  57. if point[0] is None and point[1] is None:
  58. point_x = self.draw_app.x
  59. point_y = self.draw_app.y
  60. else:
  61. point_x = point[0]
  62. point_y = point[1]
  63. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  64. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  65. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  66. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  67. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  68. def make(self):
  69. try:
  70. QtGui.QGuiApplication.restoreOverrideCursor()
  71. except:
  72. pass
  73. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  74. # to the value, as a list of itself
  75. if self.selected_dia in self.draw_app.points_edit:
  76. self.draw_app.points_edit[self.selected_dia].append(self.points)
  77. else:
  78. self.draw_app.points_edit[self.selected_dia] = [self.points]
  79. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  80. self.geometry = DrawToolShape(self.util_shape(self.points))
  81. self.complete = True
  82. self.draw_app.app.inform.emit(_("[success] Done. Drill added."))
  83. class FCDrillArray(FCShapeTool):
  84. """
  85. Resulting type: MultiLineString
  86. """
  87. def __init__(self, draw_app):
  88. DrawTool.__init__(self, draw_app)
  89. self.name = 'drill_array'
  90. self.draw_app.array_frame.show()
  91. self.selected_dia = None
  92. self.drill_axis = 'X'
  93. self.drill_array = 'linear'
  94. self.drill_array_size = None
  95. self.drill_pitch = None
  96. self.drill_linear_angle = None
  97. self.drill_angle = None
  98. self.drill_direction = None
  99. self.drill_radius = None
  100. self.origin = None
  101. self.destination = None
  102. self.flag_for_circ_array = None
  103. self.last_dx = 0
  104. self.last_dy = 0
  105. self.pt = []
  106. try:
  107. self.draw_app.app.inform.emit(self.start_msg)
  108. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  109. # as a visual marker, select again in tooltable the actual tool that we are using
  110. # remember that it was deselected when clicking on canvas
  111. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  112. self.draw_app.tools_table_exc.setCurrentItem(item)
  113. except KeyError:
  114. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  115. return
  116. try:
  117. QtGui.QGuiApplication.restoreOverrideCursor()
  118. except:
  119. pass
  120. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill_array.png'))
  121. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  122. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  123. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  124. self.draw_app.draw_utility_geometry(geo=geo)
  125. self.draw_app.app.inform.emit(_("Click on target location ..."))
  126. # Switch notebook to Selected page
  127. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  128. def click(self, point):
  129. if self.drill_array == 'Linear':
  130. self.make()
  131. return
  132. else:
  133. if self.flag_for_circ_array is None:
  134. self.draw_app.in_action = True
  135. self.pt.append(point)
  136. self.flag_for_circ_array = True
  137. self.set_origin(point)
  138. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  139. else:
  140. self.destination = point
  141. self.make()
  142. self.flag_for_circ_array = None
  143. return
  144. def set_origin(self, origin):
  145. self.origin = origin
  146. def utility_geometry(self, data=None, static=None):
  147. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  148. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  149. self.drill_array = self.draw_app.array_type_combo.get_value()
  150. try:
  151. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  152. try:
  153. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  154. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  155. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  156. except TypeError:
  157. self.draw_app.app.inform.emit(
  158. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  159. return
  160. except Exception as e:
  161. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  162. return
  163. if self.drill_array == 'Linear':
  164. if data[0] is None and data[1] is None:
  165. dx = self.draw_app.x
  166. dy = self.draw_app.y
  167. else:
  168. dx = data[0]
  169. dy = data[1]
  170. geo_list = []
  171. geo = None
  172. self.points = [dx, dy]
  173. for item in range(self.drill_array_size):
  174. if self.drill_axis == 'X':
  175. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  176. if self.drill_axis == 'Y':
  177. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  178. if self.drill_axis == 'A':
  179. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  180. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  181. geo = self.util_shape(
  182. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  183. )
  184. if static is None or static is False:
  185. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  186. else:
  187. geo_list.append(geo)
  188. # self.origin = data
  189. self.last_dx = dx
  190. self.last_dy = dy
  191. return DrawToolUtilityShape(geo_list)
  192. else:
  193. if data[0] is None and data[1] is None:
  194. cdx = self.draw_app.x
  195. cdy = self.draw_app.y
  196. else:
  197. cdx = data[0]
  198. cdy = data[1]
  199. if len(self.pt) > 0:
  200. temp_points = [x for x in self.pt]
  201. temp_points.append([cdx, cdy])
  202. return DrawToolUtilityShape(LineString(temp_points))
  203. def util_shape(self, point):
  204. if point[0] is None and point[1] is None:
  205. point_x = self.draw_app.x
  206. point_y = self.draw_app.y
  207. else:
  208. point_x = point[0]
  209. point_y = point[1]
  210. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  211. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  212. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  213. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  214. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  215. def make(self):
  216. self.geometry = []
  217. geo = None
  218. try:
  219. QtGui.QGuiApplication.restoreOverrideCursor()
  220. except:
  221. pass
  222. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  223. # to the value, as a list of itself
  224. if self.selected_dia not in self.draw_app.points_edit:
  225. self.draw_app.points_edit[self.selected_dia] = []
  226. for i in range(self.drill_array_size):
  227. self.draw_app.points_edit[self.selected_dia].append(self.points)
  228. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  229. if self.drill_array == 'Linear':
  230. for item in range(self.drill_array_size):
  231. if self.drill_axis == 'X':
  232. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  233. if self.drill_axis == 'Y':
  234. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  235. if self.drill_axis == 'A':
  236. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  237. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  238. geo = self.util_shape(
  239. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  240. )
  241. self.geometry.append(DrawToolShape(geo))
  242. else:
  243. if (self.drill_angle * self.drill_array_size) > 360:
  244. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many drills for the selected spacing angle."))
  245. return
  246. radius = distance(self.destination, self.origin)
  247. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  248. for i in range(self.drill_array_size):
  249. angle_radians = math.radians(self.drill_angle * i)
  250. if self.drill_direction == 'CW':
  251. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  252. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  253. else:
  254. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  255. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  256. geo = self.util_shape((x, y))
  257. self.geometry.append(DrawToolShape(geo))
  258. self.complete = True
  259. self.draw_app.app.inform.emit(_("[success] Done. Drill Array added."))
  260. self.draw_app.in_action = True
  261. self.draw_app.array_frame.hide()
  262. return
  263. class FCDrillResize(FCShapeTool):
  264. def __init__(self, draw_app):
  265. DrawTool.__init__(self, draw_app)
  266. self.name = 'drill_resize'
  267. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  268. self.resize_dia = None
  269. self.draw_app.resize_frame.show()
  270. self.points = None
  271. self.selected_dia_list = []
  272. self.current_storage = None
  273. self.geometry = []
  274. self.destination_storage = None
  275. self.draw_app.resize_btn.clicked.connect(self.make)
  276. # Switch notebook to Selected page
  277. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  278. def make(self):
  279. self.draw_app.is_modified = True
  280. try:
  281. new_dia = self.draw_app.resdrill_entry.get_value()
  282. except:
  283. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Resize drill(s) failed. Please enter a diameter for resize."))
  284. return
  285. if new_dia not in self.draw_app.olddia_newdia:
  286. self.destination_storage = FlatCAMGeoEditor.make_storage()
  287. self.draw_app.storage_dict[new_dia] = self.destination_storage
  288. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  289. # each time a tool diameter is edited or added
  290. self.draw_app.olddia_newdia[new_dia] = new_dia
  291. else:
  292. self.destination_storage = self.draw_app.storage_dict[new_dia]
  293. for index in self.draw_app.tools_table_exc.selectedIndexes():
  294. row = index.row()
  295. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  296. # therefore below we convert to float
  297. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  298. self.selected_dia_list.append(float(dia_on_row))
  299. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  300. # we add a new entry in the tool2tooldia dict
  301. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  302. sel_shapes_to_be_deleted = []
  303. if self.selected_dia_list:
  304. for sel_dia in self.selected_dia_list:
  305. self.current_storage = self.draw_app.storage_dict[sel_dia]
  306. for select_shape in self.draw_app.get_selected():
  307. if select_shape in self.current_storage.get_objects():
  308. factor = new_dia / sel_dia
  309. self.geometry.append(
  310. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  311. )
  312. self.current_storage.remove(select_shape)
  313. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  314. # self.points_edit it's only useful first time when we load the data into the storage
  315. # but is still used as reference when building tool_table in self.build_ui()
  316. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  317. # deleting self.points_edit elements (doesn't matter who but just the number)
  318. # solved the display issue.
  319. del self.draw_app.points_edit[sel_dia][0]
  320. sel_shapes_to_be_deleted.append(select_shape)
  321. self.draw_app.on_exc_shape_complete(self.destination_storage)
  322. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  323. # self.points_edit it's only useful first time when we load the data into the storage
  324. # but is still used as reference when building tool_table in self.build_ui()
  325. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  326. # deleting self.points_edit elements (doesn't matter who but just the number)
  327. # solved the display issue.
  328. if new_dia not in self.draw_app.points_edit:
  329. self.draw_app.points_edit[new_dia] = [(0, 0)]
  330. else:
  331. self.draw_app.points_edit[new_dia].append((0,0))
  332. self.geometry = []
  333. # if following the resize of the drills there will be no more drills for the selected tool then
  334. # delete that tool
  335. if not self.draw_app.points_edit[sel_dia]:
  336. self.draw_app.on_tool_delete(sel_dia)
  337. for shp in sel_shapes_to_be_deleted:
  338. self.draw_app.selected.remove(shp)
  339. sel_shapes_to_be_deleted = []
  340. self.draw_app.build_ui()
  341. self.draw_app.replot()
  342. self.draw_app.app.inform.emit(_("[success] Done. Drill Resize completed."))
  343. else:
  344. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No drills selected for resize ..."))
  345. self.draw_app.resize_frame.hide()
  346. self.complete = True
  347. # MS: always return to the Select Tool
  348. self.draw_app.select_tool("select")
  349. class FCDrillMove(FCShapeTool):
  350. def __init__(self, draw_app):
  351. DrawTool.__init__(self, draw_app)
  352. self.name = 'drill_move'
  353. # self.shape_buffer = self.draw_app.shape_buffer
  354. self.origin = None
  355. self.destination = None
  356. self.selected_dia_list = []
  357. if self.draw_app.launched_from_shortcuts is True:
  358. self.draw_app.launched_from_shortcuts = False
  359. self.draw_app.app.inform.emit(_("Click on target location ..."))
  360. else:
  361. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  362. self.current_storage = None
  363. self.geometry = []
  364. for index in self.draw_app.tools_table_exc.selectedIndexes():
  365. row = index.row()
  366. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  367. # therefore below we convert to float
  368. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  369. self.selected_dia_list.append(float(dia_on_row))
  370. # Switch notebook to Selected page
  371. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  372. def set_origin(self, origin):
  373. self.origin = origin
  374. def click(self, point):
  375. if len(self.draw_app.get_selected()) == 0:
  376. return "Nothing to move."
  377. if self.origin is None:
  378. self.set_origin(point)
  379. self.draw_app.app.inform.emit(_("Click on target location ..."))
  380. return
  381. else:
  382. self.destination = point
  383. self.make()
  384. # MS: always return to the Select Tool
  385. self.draw_app.select_tool("select")
  386. return
  387. def make(self):
  388. # Create new geometry
  389. dx = self.destination[0] - self.origin[0]
  390. dy = self.destination[1] - self.origin[1]
  391. sel_shapes_to_be_deleted = []
  392. for sel_dia in self.selected_dia_list:
  393. self.current_storage = self.draw_app.storage_dict[sel_dia]
  394. for select_shape in self.draw_app.get_selected():
  395. if select_shape in self.current_storage.get_objects():
  396. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  397. self.current_storage.remove(select_shape)
  398. sel_shapes_to_be_deleted.append(select_shape)
  399. self.draw_app.on_exc_shape_complete(self.current_storage)
  400. self.geometry = []
  401. for shp in sel_shapes_to_be_deleted:
  402. self.draw_app.selected.remove(shp)
  403. sel_shapes_to_be_deleted = []
  404. self.draw_app.build_ui()
  405. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) Move completed."))
  406. def utility_geometry(self, data=None):
  407. """
  408. Temporary geometry on screen while using this tool.
  409. :param data:
  410. :return:
  411. """
  412. geo_list = []
  413. if self.origin is None:
  414. return None
  415. if len(self.draw_app.get_selected()) == 0:
  416. return None
  417. dx = data[0] - self.origin[0]
  418. dy = data[1] - self.origin[1]
  419. for geom in self.draw_app.get_selected():
  420. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  421. return DrawToolUtilityShape(geo_list)
  422. class FCDrillCopy(FCDrillMove):
  423. def __init__(self, draw_app):
  424. FCDrillMove.__init__(self, draw_app)
  425. self.name = 'drill_copy'
  426. def make(self):
  427. # Create new geometry
  428. dx = self.destination[0] - self.origin[0]
  429. dy = self.destination[1] - self.origin[1]
  430. sel_shapes_to_be_deleted = []
  431. for sel_dia in self.selected_dia_list:
  432. self.current_storage = self.draw_app.storage_dict[sel_dia]
  433. for select_shape in self.draw_app.get_selected():
  434. if select_shape in self.current_storage.get_objects():
  435. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  436. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  437. self.draw_app.points_edit[sel_dia].append((0, 0))
  438. sel_shapes_to_be_deleted.append(select_shape)
  439. self.draw_app.on_exc_shape_complete(self.current_storage)
  440. self.geometry = []
  441. for shp in sel_shapes_to_be_deleted:
  442. self.draw_app.selected.remove(shp)
  443. sel_shapes_to_be_deleted = []
  444. self.draw_app.build_ui()
  445. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) copied."))
  446. class FCDrillSelect(DrawTool):
  447. def __init__(self, exc_editor_app):
  448. DrawTool.__init__(self, exc_editor_app)
  449. self.name = 'drill_select'
  450. try:
  451. QtGui.QGuiApplication.restoreOverrideCursor()
  452. except:
  453. pass
  454. self.exc_editor_app = exc_editor_app
  455. self.storage = self.exc_editor_app.storage_dict
  456. # self.selected = self.exc_editor_app.selected
  457. # here we store all shapes that were selected so we can search for the nearest to our click location
  458. self.sel_storage = FlatCAMExcEditor.make_storage()
  459. self.exc_editor_app.resize_frame.hide()
  460. self.exc_editor_app.array_frame.hide()
  461. def click(self, point):
  462. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  463. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  464. if key_modifier == Qt.ControlModifier:
  465. pass
  466. else:
  467. self.exc_editor_app.selected = []
  468. else:
  469. if key_modifier == Qt.ShiftModifier:
  470. pass
  471. else:
  472. self.exc_editor_app.selected = []
  473. def click_release(self, pos):
  474. self.exc_editor_app.tools_table_exc.clearSelection()
  475. try:
  476. for storage in self.exc_editor_app.storage_dict:
  477. for shape in self.exc_editor_app.storage_dict[storage].get_objects():
  478. self.sel_storage.insert(shape)
  479. _, closest_shape = self.sel_storage.nearest(pos)
  480. # constrain selection to happen only within a certain bounding box
  481. x_coord, y_coord = closest_shape.geo[0].xy
  482. delta = (x_coord[1] - x_coord[0])
  483. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  484. xmin = x_coord[0] - (0.7 * delta)
  485. xmax = x_coord[0] + (1.7 * delta)
  486. ymin = y_coord[0] - (0.7 * delta)
  487. ymax = y_coord[0] + (1.7 * delta)
  488. except StopIteration:
  489. return ""
  490. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  491. self.exc_editor_app.selected = []
  492. else:
  493. modifiers = QtWidgets.QApplication.keyboardModifiers()
  494. mod_key = 'Control'
  495. if modifiers == QtCore.Qt.ShiftModifier:
  496. mod_key = 'Shift'
  497. elif modifiers == QtCore.Qt.ControlModifier:
  498. mod_key = 'Control'
  499. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  500. if closest_shape in self.exc_editor_app.selected:
  501. self.exc_editor_app.selected.remove(closest_shape)
  502. else:
  503. self.exc_editor_app.selected.append(closest_shape)
  504. else:
  505. self.draw_app.selected = []
  506. self.draw_app.selected.append(closest_shape)
  507. # select the diameter of the selected shape in the tool table
  508. try:
  509. self.draw_app.tools_table_exc.cellPressed.disconnect()
  510. except:
  511. pass
  512. sel_tools = set()
  513. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  514. for shape_s in self.exc_editor_app.selected:
  515. for storage in self.exc_editor_app.storage_dict:
  516. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  517. sel_tools.add(storage)
  518. for storage in sel_tools:
  519. self.exc_editor_app.tools_table_exc.selectRow(int(storage) - 1)
  520. self.draw_app.last_tool_selected = int(storage)
  521. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  522. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  523. # delete whatever is in selection storage, there is no longer need for those shapes
  524. self.sel_storage = FlatCAMExcEditor.make_storage()
  525. return ""
  526. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  527. # for storage in self.exc_editor_app.storage_dict:
  528. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  529. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  530. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  531. # over_shape_list.append(obj_shape)
  532. #
  533. # try:
  534. # # if there is no shape under our click then deselect all shapes
  535. # if not over_shape_list:
  536. # self.exc_editor_app.selected = []
  537. # FlatCAMExcEditor.draw_shape_idx = -1
  538. # self.exc_editor_app.tools_table_exc.clearSelection()
  539. # else:
  540. # # if there are shapes under our click then advance through the list of them, one at the time in a
  541. # # circular way
  542. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  543. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  544. #
  545. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  546. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  547. # if obj_to_add in self.exc_editor_app.selected:
  548. # self.exc_editor_app.selected.remove(obj_to_add)
  549. # else:
  550. # self.exc_editor_app.selected.append(obj_to_add)
  551. # else:
  552. # self.exc_editor_app.selected = []
  553. # self.exc_editor_app.selected.append(obj_to_add)
  554. # else:
  555. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  556. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  557. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  558. # if obj_to_add in self.exc_editor_app.selected:
  559. # self.exc_editor_app.selected.remove(obj_to_add)
  560. # else:
  561. # self.exc_editor_app.selected.append(obj_to_add)
  562. # else:
  563. # self.exc_editor_app.selected = []
  564. # self.exc_editor_app.selected.append(obj_to_add)
  565. #
  566. # for storage in self.exc_editor_app.storage_dict:
  567. # for shape in self.exc_editor_app.selected:
  568. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  569. # for key in self.exc_editor_app.tool2tooldia:
  570. # if self.exc_editor_app.tool2tooldia[key] == storage:
  571. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  572. # item.setSelected(True)
  573. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  574. #
  575. # except Exception as e:
  576. # log.error("[ERROR] Something went bad. %s" % str(e))
  577. # raise
  578. class FlatCAMExcEditor(QtCore.QObject):
  579. draw_shape_idx = -1
  580. def __init__(self, app):
  581. assert isinstance(app, FlatCAMApp.App), \
  582. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  583. super(FlatCAMExcEditor, self).__init__()
  584. self.app = app
  585. self.canvas = self.app.plotcanvas
  586. ## Current application units in Upper Case
  587. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  588. self.exc_edit_widget = QtWidgets.QWidget()
  589. ## Box for custom widgets
  590. # This gets populated in offspring implementations.
  591. layout = QtWidgets.QVBoxLayout()
  592. self.exc_edit_widget.setLayout(layout)
  593. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  594. # this way I can hide/show the frame
  595. self.drills_frame = QtWidgets.QFrame()
  596. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  597. layout.addWidget(self.drills_frame)
  598. self.tools_box = QtWidgets.QVBoxLayout()
  599. self.tools_box.setContentsMargins(0, 0, 0, 0)
  600. self.drills_frame.setLayout(self.tools_box)
  601. ## Page Title box (spacing between children)
  602. self.title_box = QtWidgets.QHBoxLayout()
  603. self.tools_box.addLayout(self.title_box)
  604. ## Page Title icon
  605. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  606. self.icon = QtWidgets.QLabel()
  607. self.icon.setPixmap(pixmap)
  608. self.title_box.addWidget(self.icon, stretch=0)
  609. ## Title label
  610. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  611. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  612. self.title_box.addWidget(self.title_label, stretch=1)
  613. ## Object name
  614. self.name_box = QtWidgets.QHBoxLayout()
  615. self.tools_box.addLayout(self.name_box)
  616. name_label = QtWidgets.QLabel(_("Name:"))
  617. self.name_box.addWidget(name_label)
  618. self.name_entry = FCEntry()
  619. self.name_box.addWidget(self.name_entry)
  620. #### Tools Drills ####
  621. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  622. self.tools_table_label.setToolTip(
  623. _( "Tools in this Excellon object\n"
  624. "when are used for drilling.")
  625. )
  626. self.tools_box.addWidget(self.tools_table_label)
  627. self.tools_table_exc = FCTable()
  628. # delegate = SpinBoxDelegate(units=self.units)
  629. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  630. self.tools_box.addWidget(self.tools_table_exc)
  631. self.tools_table_exc.setColumnCount(4)
  632. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  633. self.tools_table_exc.setSortingEnabled(False)
  634. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  635. self.empty_label = QtWidgets.QLabel('')
  636. self.tools_box.addWidget(self.empty_label)
  637. #### Add a new Tool ####
  638. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  639. self.addtool_label.setToolTip(
  640. _("Add/Delete a tool to the tool list\n"
  641. "for this Excellon object.")
  642. )
  643. self.tools_box.addWidget(self.addtool_label)
  644. grid1 = QtWidgets.QGridLayout()
  645. self.tools_box.addLayout(grid1)
  646. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  647. addtool_entry_lbl.setToolTip(
  648. _("Diameter for the new tool")
  649. )
  650. grid1.addWidget(addtool_entry_lbl, 0, 0)
  651. hlay = QtWidgets.QHBoxLayout()
  652. self.addtool_entry = FCEntry()
  653. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  654. hlay.addWidget(self.addtool_entry)
  655. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  656. self.addtool_btn.setToolTip(
  657. _( "Add a new tool to the tool list\n"
  658. "with the diameter specified above.")
  659. )
  660. self.addtool_btn.setFixedWidth(80)
  661. hlay.addWidget(self.addtool_btn)
  662. grid1.addLayout(hlay, 0, 1)
  663. grid2 = QtWidgets.QGridLayout()
  664. self.tools_box.addLayout(grid2)
  665. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  666. self.deltool_btn.setToolTip(
  667. _( "Delete a tool in the tool list\n"
  668. "by selecting a row in the tool table.")
  669. )
  670. grid2.addWidget(self.deltool_btn, 0, 1)
  671. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  672. # this way I can hide/show the frame
  673. self.resize_frame = QtWidgets.QFrame()
  674. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  675. self.tools_box.addWidget(self.resize_frame)
  676. self.resize_box = QtWidgets.QVBoxLayout()
  677. self.resize_box.setContentsMargins(0, 0, 0, 0)
  678. self.resize_frame.setLayout(self.resize_box)
  679. #### Resize a drill ####
  680. self.emptyresize_label = QtWidgets.QLabel('')
  681. self.resize_box.addWidget(self.emptyresize_label)
  682. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  683. self.drillresize_label.setToolTip(
  684. _("Resize a drill or a selection of drills.")
  685. )
  686. self.resize_box.addWidget(self.drillresize_label)
  687. grid3 = QtWidgets.QGridLayout()
  688. self.resize_box.addLayout(grid3)
  689. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  690. res_entry_lbl.setToolTip(
  691. _( "Diameter to resize to.")
  692. )
  693. grid3.addWidget(res_entry_lbl, 0, 0)
  694. hlay2 = QtWidgets.QHBoxLayout()
  695. self.resdrill_entry = LengthEntry()
  696. hlay2.addWidget(self.resdrill_entry)
  697. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  698. self.resize_btn.setToolTip(
  699. _("Resize drill(s)")
  700. )
  701. self.resize_btn.setFixedWidth(80)
  702. hlay2.addWidget(self.resize_btn)
  703. grid3.addLayout(hlay2, 0, 1)
  704. self.resize_frame.hide()
  705. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  706. # all the add drill array widgets
  707. # this way I can hide/show the frame
  708. self.array_frame = QtWidgets.QFrame()
  709. self.array_frame.setContentsMargins(0, 0, 0, 0)
  710. self.tools_box.addWidget(self.array_frame)
  711. self.array_box = QtWidgets.QVBoxLayout()
  712. self.array_box.setContentsMargins(0, 0, 0, 0)
  713. self.array_frame.setLayout(self.array_box)
  714. #### Add DRILL Array ####
  715. self.emptyarray_label = QtWidgets.QLabel('')
  716. self.array_box.addWidget(self.emptyarray_label)
  717. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  718. self.drillarray_label.setToolTip(
  719. _("Add an array of drills (linear or circular array)")
  720. )
  721. self.array_box.addWidget(self.drillarray_label)
  722. self.array_type_combo = FCComboBox()
  723. self.array_type_combo.setToolTip(
  724. _( "Select the type of drills array to create.\n"
  725. "It can be Linear X(Y) or Circular")
  726. )
  727. self.array_type_combo.addItem(_("Linear"))
  728. self.array_type_combo.addItem(_("Circular"))
  729. self.array_box.addWidget(self.array_type_combo)
  730. self.array_form = QtWidgets.QFormLayout()
  731. self.array_box.addLayout(self.array_form)
  732. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  733. self.drill_array_size_label.setToolTip(
  734. _("Specify how many drills to be in the array.")
  735. )
  736. self.drill_array_size_label.setFixedWidth(100)
  737. self.drill_array_size_entry = LengthEntry()
  738. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  739. self.array_linear_frame = QtWidgets.QFrame()
  740. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  741. self.array_box.addWidget(self.array_linear_frame)
  742. self.linear_box = QtWidgets.QVBoxLayout()
  743. self.linear_box.setContentsMargins(0, 0, 0, 0)
  744. self.array_linear_frame.setLayout(self.linear_box)
  745. self.linear_form = QtWidgets.QFormLayout()
  746. self.linear_box.addLayout(self.linear_form)
  747. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  748. self.drill_axis_label.setToolTip(
  749. _("Direction on which the linear array is oriented:\n"
  750. "- 'X' - horizontal axis \n"
  751. "- 'Y' - vertical axis or \n"
  752. "- 'Angle' - a custom angle for the array inclination")
  753. )
  754. self.drill_axis_label.setFixedWidth(100)
  755. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  756. {'label': 'Y', 'value': 'Y'},
  757. {'label': _('Angle'), 'value': 'A'}])
  758. self.drill_axis_radio.set_value('X')
  759. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  760. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  761. self.drill_pitch_label.setToolTip(
  762. _("Pitch = Distance between elements of the array.")
  763. )
  764. self.drill_pitch_label.setFixedWidth(100)
  765. self.drill_pitch_entry = LengthEntry()
  766. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  767. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  768. self.linear_angle_label.setToolTip(
  769. _( "Angle at which the linear array is placed.\n"
  770. "The precision is of max 2 decimals.\n"
  771. "Min value is: -359.99 degrees.\n"
  772. "Max value is: 360.00 degrees.")
  773. )
  774. self.linear_angle_label.setFixedWidth(100)
  775. self.linear_angle_spinner = FCDoubleSpinner()
  776. self.linear_angle_spinner.set_precision(2)
  777. self.linear_angle_spinner.setRange(-359.99, 360.00)
  778. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  779. self.array_circular_frame = QtWidgets.QFrame()
  780. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  781. self.array_box.addWidget(self.array_circular_frame)
  782. self.circular_box = QtWidgets.QVBoxLayout()
  783. self.circular_box.setContentsMargins(0, 0, 0, 0)
  784. self.array_circular_frame.setLayout(self.circular_box)
  785. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  786. self.drill_direction_label.setToolTip(
  787. _( "Direction for circular array."
  788. "Can be CW = clockwise or CCW = counter clockwise.")
  789. )
  790. self.drill_direction_label.setFixedWidth(100)
  791. self.circular_form = QtWidgets.QFormLayout()
  792. self.circular_box.addLayout(self.circular_form)
  793. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  794. {'label': 'CCW.', 'value': 'CCW'}])
  795. self.drill_direction_radio.set_value('CW')
  796. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  797. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  798. self.drill_angle_label.setToolTip(
  799. _("Angle at which each element in circular array is placed.")
  800. )
  801. self.drill_angle_label.setFixedWidth(100)
  802. self.drill_angle_entry = LengthEntry()
  803. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  804. self.array_circular_frame.hide()
  805. self.linear_angle_spinner.hide()
  806. self.linear_angle_label.hide()
  807. self.array_frame.hide()
  808. self.tools_box.addStretch()
  809. ## Toolbar events and properties
  810. self.tools_exc = {
  811. "select": {"button": self.app.ui.select_drill_btn,
  812. "constructor": FCDrillSelect},
  813. "drill_add": {"button": self.app.ui.add_drill_btn,
  814. "constructor": FCDrillAdd},
  815. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  816. "constructor": FCDrillArray},
  817. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  818. "constructor": FCDrillResize},
  819. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  820. "constructor": FCDrillCopy},
  821. "drill_move": {"button": self.app.ui.move_drill_btn,
  822. "constructor": FCDrillMove},
  823. }
  824. ### Data
  825. self.active_tool = None
  826. self.storage_dict = {}
  827. self.current_storage = []
  828. # build the data from the Excellon point into a dictionary
  829. # {tool_dia: [geometry_in_points]}
  830. self.points_edit = {}
  831. self.sorted_diameters =[]
  832. self.new_drills = []
  833. self.new_tools = {}
  834. self.new_slots = {}
  835. self.new_tool_offset = {}
  836. # dictionary to store the tool_row and diameters in Tool_table
  837. # it will be updated everytime self.build_ui() is called
  838. self.olddia_newdia = {}
  839. self.tool2tooldia = {}
  840. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  841. # is cleared but as a side effect also the selected tool is cleared
  842. self.last_tool_selected = None
  843. self.utility = []
  844. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  845. self.launched_from_shortcuts = False
  846. # this var will store the state of the toolbar before starting the editor
  847. self.toolbar_old_state = False
  848. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  849. self.name_entry.returnPressed.connect(self.on_name_activate)
  850. self.addtool_btn.clicked.connect(self.on_tool_add)
  851. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  852. self.deltool_btn.clicked.connect(self.on_tool_delete)
  853. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  854. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  855. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  856. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  857. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  858. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  859. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  860. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  861. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  862. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  863. # Init GUI
  864. self.drill_array_size_entry.set_value(5)
  865. self.drill_pitch_entry.set_value(2.54)
  866. self.drill_angle_entry.set_value(12)
  867. self.drill_direction_radio.set_value('CW')
  868. self.drill_axis_radio.set_value('X')
  869. self.exc_obj = None
  870. # VisPy Visuals
  871. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  872. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  873. self.app.pool_recreated.connect(self.pool_recreated)
  874. # Remove from scene
  875. self.shapes.enabled = False
  876. self.tool_shape.enabled = False
  877. ## List of selected shapes.
  878. self.selected = []
  879. self.move_timer = QtCore.QTimer()
  880. self.move_timer.setSingleShot(True)
  881. self.key = None # Currently pressed key
  882. self.modifiers = None
  883. self.x = None # Current mouse cursor pos
  884. self.y = None
  885. # Current snapped mouse pos
  886. self.snap_x = None
  887. self.snap_y = None
  888. self.pos = None
  889. def make_callback(thetool):
  890. def f():
  891. self.on_tool_select(thetool)
  892. return f
  893. for tool in self.tools_exc:
  894. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  895. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  896. self.options = {
  897. "global_gridx": 0.1,
  898. "global_gridy": 0.1,
  899. "snap_max": 0.05,
  900. "grid_snap": True,
  901. "corner_snap": False,
  902. "grid_gap_link": True
  903. }
  904. self.app.options_read_form()
  905. for option in self.options:
  906. if option in self.app.options:
  907. self.options[option] = self.app.options[option]
  908. self.rtree_exc_index = rtindex.Index()
  909. # flag to show if the object was modified
  910. self.is_modified = False
  911. self.edited_obj_name = ""
  912. # variable to store the total amount of drills per job
  913. self.tot_drill_cnt = 0
  914. self.tool_row = 0
  915. # variable to store the total amount of slots per job
  916. self.tot_slot_cnt = 0
  917. self.tool_row_slots = 0
  918. self.tool_row = 0
  919. # store the status of the editor so the Delete at object level will not work until the edit is finished
  920. self.editor_active = False
  921. def entry2option(option, entry):
  922. self.options[option] = float(entry.text())
  923. # store the status of the editor so the Delete at object level will not work until the edit is finished
  924. self.editor_active = False
  925. def pool_recreated(self, pool):
  926. self.shapes.pool = pool
  927. self.tool_shape.pool = pool
  928. @staticmethod
  929. def make_storage():
  930. ## Shape storage.
  931. storage = FlatCAMRTreeStorage()
  932. storage.get_points = DrawToolShape.get_pts
  933. return storage
  934. def set_ui(self):
  935. # updated units
  936. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  937. self.olddia_newdia.clear()
  938. self.tool2tooldia.clear()
  939. # build the self.points_edit dict {dimaters: [point_list]}
  940. for drill in self.exc_obj.drills:
  941. if drill['tool'] in self.exc_obj.tools:
  942. if self.units == 'IN':
  943. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  944. else:
  945. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  946. try:
  947. self.points_edit[tool_dia].append(drill['point'])
  948. except KeyError:
  949. self.points_edit[tool_dia] = [drill['point']]
  950. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  951. for key in self.points_edit:
  952. self.olddia_newdia[key] = key
  953. sort_temp = []
  954. for diam in self.olddia_newdia:
  955. sort_temp.append(float(diam))
  956. self.sorted_diameters = sorted(sort_temp)
  957. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  958. if self.exc_obj.diameterless is False:
  959. for i in range(len(self.sorted_diameters)):
  960. tt_dia = self.sorted_diameters[i]
  961. self.tool2tooldia[i + 1] = tt_dia
  962. else:
  963. # the Excellon object has diameters that are bogus information, added by the application because the
  964. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  965. # but use the real order found in the exc_obj.tools
  966. for k, v in self.exc_obj.tools.items():
  967. if self.units == 'IN':
  968. tool_dia = float('%.3f' % v['C'])
  969. else:
  970. tool_dia = float('%.2f' % v['C'])
  971. self.tool2tooldia[int(k)] = tool_dia
  972. def build_ui(self, first_run=None):
  973. try:
  974. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  975. self.tools_table_exc.itemChanged.disconnect()
  976. except:
  977. pass
  978. try:
  979. self.tools_table_exc.cellPressed.disconnect()
  980. except:
  981. pass
  982. # updated units
  983. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  984. # make a new name for the new Excellon object (the one with edited content)
  985. self.edited_obj_name = self.exc_obj.options['name']
  986. self.name_entry.set_value(self.edited_obj_name)
  987. if self.units == "IN":
  988. self.addtool_entry.set_value(0.039)
  989. else:
  990. self.addtool_entry.set_value(1.00)
  991. sort_temp = []
  992. for diam in self.olddia_newdia:
  993. sort_temp.append(float(diam))
  994. self.sorted_diameters = sorted(sort_temp)
  995. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  996. n = len(self.sorted_diameters)
  997. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  998. self.tools_table_exc.setRowCount(n + 2)
  999. self.tot_drill_cnt = 0
  1000. self.tot_slot_cnt = 0
  1001. self.tool_row = 0
  1002. # this variable will serve as the real tool_number
  1003. tool_id = 0
  1004. for tool_no in self.sorted_diameters:
  1005. tool_id += 1
  1006. drill_cnt = 0 # variable to store the nr of drills per tool
  1007. slot_cnt = 0 # variable to store the nr of slots per tool
  1008. # Find no of drills for the current tool
  1009. for tool_dia in self.points_edit:
  1010. if float(tool_dia) == tool_no:
  1011. drill_cnt = len(self.points_edit[tool_dia])
  1012. self.tot_drill_cnt += drill_cnt
  1013. try:
  1014. # Find no of slots for the current tool
  1015. for slot in self.slots:
  1016. if slot['tool'] == tool_no:
  1017. slot_cnt += 1
  1018. self.tot_slot_cnt += slot_cnt
  1019. except AttributeError:
  1020. # log.debug("No slots in the Excellon file")
  1021. # slot editing not implemented
  1022. pass
  1023. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1024. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1025. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  1026. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1027. # There are no drill bits in MM with more than 3 decimals diameter
  1028. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1029. if self.units == 'MM':
  1030. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1031. else:
  1032. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  1033. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1034. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1035. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1036. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1037. if slot_cnt > 0:
  1038. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1039. else:
  1040. slot_count = QtWidgets.QTableWidgetItem('')
  1041. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1042. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1043. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1044. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1045. if first_run is True:
  1046. # set now the last tool selected
  1047. self.last_tool_selected = int(tool_id)
  1048. self.tool_row += 1
  1049. # make the diameter column editable
  1050. for row in range(self.tool_row):
  1051. self.tools_table_exc.item(row, 1).setFlags(
  1052. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1053. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1054. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1055. # add a last row with the Total number of drills
  1056. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1057. # it will have to have the foreground color (font color) white
  1058. empty = QtWidgets.QTableWidgetItem('9998')
  1059. empty.setForeground(QtGui.QColor(255, 255, 255))
  1060. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1061. empty_b = QtWidgets.QTableWidgetItem('')
  1062. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1063. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1064. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1065. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1066. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1067. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1068. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1069. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1070. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1071. font = QtGui.QFont()
  1072. font.setBold(True)
  1073. font.setWeight(75)
  1074. for k in [1, 2]:
  1075. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1076. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1077. self.tool_row += 1
  1078. # add a last row with the Total number of slots
  1079. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1080. # it will have to have the foreground color (font color) white
  1081. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1082. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1083. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1084. empty_3 = QtWidgets.QTableWidgetItem('')
  1085. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1086. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1087. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1088. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1089. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1090. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1091. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1092. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1093. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1094. for kl in [1, 2, 3]:
  1095. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1096. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1097. # all the tools are selected by default
  1098. self.tools_table_exc.selectColumn(0)
  1099. #
  1100. self.tools_table_exc.resizeColumnsToContents()
  1101. self.tools_table_exc.resizeRowsToContents()
  1102. vertical_header = self.tools_table_exc.verticalHeader()
  1103. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1104. vertical_header.hide()
  1105. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1106. horizontal_header = self.tools_table_exc.horizontalHeader()
  1107. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1108. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1109. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1110. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1111. # horizontal_header.setStretchLastSection(True)
  1112. # self.tools_table_exc.setSortingEnabled(True)
  1113. # sort by tool diameter
  1114. self.tools_table_exc.sortItems(1)
  1115. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1116. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1117. # use them
  1118. self.tool2tooldia.clear()
  1119. for row in range(self.tools_table_exc.rowCount() - 2):
  1120. tool = int(self.tools_table_exc.item(row, 0).text())
  1121. diameter = float(self.tools_table_exc.item(row, 1).text())
  1122. self.tool2tooldia[tool] = diameter
  1123. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1124. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1125. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1126. self.tools_table_exc.clearSelection()
  1127. # Remove anything else in the GUI Selected Tab
  1128. self.app.ui.selected_scroll_area.takeWidget()
  1129. # Put ourself in the GUI Selected Tab
  1130. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1131. # Switch notebook to Selected page
  1132. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1133. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1134. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1135. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1136. def on_tool_add(self, tooldia=None):
  1137. self.is_modified = True
  1138. if tooldia:
  1139. tool_dia = tooldia
  1140. else:
  1141. try:
  1142. tool_dia = float(self.addtool_entry.get_value())
  1143. except ValueError:
  1144. # try to convert comma to decimal point. if it's still not working error message and return
  1145. try:
  1146. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1147. except ValueError:
  1148. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1149. "use a number.")
  1150. )
  1151. return
  1152. if tool_dia not in self.olddia_newdia:
  1153. storage_elem = FlatCAMGeoEditor.make_storage()
  1154. self.storage_dict[tool_dia] = storage_elem
  1155. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1156. # each time a tool diameter is edited or added
  1157. self.olddia_newdia[tool_dia] = tool_dia
  1158. else:
  1159. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1160. "Save and reedit Excellon if you need to add this tool. ")
  1161. )
  1162. return
  1163. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1164. # we add a new entry in the tool2tooldia dict
  1165. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1166. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia), units=str(self.units)))
  1167. self.build_ui()
  1168. # make a quick sort through the tool2tooldia dict so we find which row to select
  1169. row_to_be_selected = None
  1170. for key in sorted(self.tool2tooldia):
  1171. if self.tool2tooldia[key] == tool_dia:
  1172. row_to_be_selected = int(key) - 1
  1173. self.last_tool_selected = int(key)
  1174. break
  1175. self.tools_table_exc.selectRow(row_to_be_selected)
  1176. def on_tool_delete(self, dia=None):
  1177. self.is_modified = True
  1178. deleted_tool_dia_list = []
  1179. deleted_tool_offset_list = []
  1180. try:
  1181. if dia is None or dia is False:
  1182. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1183. for index in self.tools_table_exc.selectionModel().selectedRows():
  1184. row = index.row()
  1185. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1186. else:
  1187. if isinstance(dia, list):
  1188. for dd in dia:
  1189. deleted_tool_dia_list.append(float('%.4f' % dd))
  1190. else:
  1191. deleted_tool_dia_list.append(float('%.4f' % dia))
  1192. except:
  1193. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1194. return
  1195. for deleted_tool_dia in deleted_tool_dia_list:
  1196. # delete de tool offset
  1197. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1198. # delete the storage used for that tool
  1199. storage_elem = FlatCAMGeoEditor.make_storage()
  1200. self.storage_dict[deleted_tool_dia] = storage_elem
  1201. self.storage_dict.pop(deleted_tool_dia, None)
  1202. # I've added this flag_del variable because dictionary don't like
  1203. # having keys deleted while iterating through them
  1204. flag_del = []
  1205. # self.points_edit.pop(deleted_tool_dia, None)
  1206. for deleted_tool in self.tool2tooldia:
  1207. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1208. flag_del.append(deleted_tool)
  1209. if flag_del:
  1210. for tool_to_be_deleted in flag_del:
  1211. # delete the tool
  1212. self.tool2tooldia.pop(tool_to_be_deleted, None)
  1213. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  1214. # number of drills from before was deleter
  1215. self.points_edit[deleted_tool_dia] = []
  1216. flag_del = []
  1217. self.olddia_newdia.pop(deleted_tool_dia, None)
  1218. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(del_dia=str(deleted_tool_dia), units=str(self.units)))
  1219. self.replot()
  1220. # self.app.inform.emit("Could not delete selected tool")
  1221. self.build_ui()
  1222. def on_tool_edit(self, item_changed):
  1223. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1224. self.tools_table_exc.itemChanged.disconnect()
  1225. self.tools_table_exc.cellPressed.disconnect()
  1226. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1227. self.is_modified = True
  1228. geometry = []
  1229. current_table_dia_edited = None
  1230. if self.tools_table_exc.currentItem() is not None:
  1231. try:
  1232. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  1233. except ValueError as e:
  1234. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1235. self.tools_table_exc.setCurrentItem(None)
  1236. return
  1237. row_of_item_changed = self.tools_table_exc.currentRow()
  1238. # rows start with 0, tools start with 1 so we adjust the value by 1
  1239. key_in_tool2tooldia = row_of_item_changed + 1
  1240. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1241. # tool diameter is not used so we create a new tool with the desired diameter
  1242. if current_table_dia_edited not in self.olddia_newdia.values():
  1243. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1244. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1245. # update the dict that holds tool_no as key and tool_dia as value
  1246. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1247. # update the tool offset
  1248. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  1249. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  1250. self.replot()
  1251. else:
  1252. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  1253. factor = current_table_dia_edited / dia_changed
  1254. geometry = []
  1255. for shape in self.storage_dict[dia_changed].get_objects():
  1256. geometry.append(DrawToolShape(
  1257. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center')
  1258. for subgeo in shape.geo])))
  1259. # add bogus drill points (for total count of drills)
  1260. for k, v in self.olddia_newdia.items():
  1261. if v == current_table_dia_edited:
  1262. self.points_edit[k].append((0, 0))
  1263. break
  1264. # search for the oldia that correspond to the newdia and add the drills in it's storage
  1265. # everything will be sort out later, when the edited excellon is updated
  1266. for k, v in self.olddia_newdia.items():
  1267. if v == current_table_dia_edited:
  1268. self.add_exc_shape(geometry, self.storage_dict[k])
  1269. break
  1270. # delete the old tool from which we moved the drills
  1271. self.on_tool_delete(dia=dia_changed)
  1272. # delete the tool offset
  1273. self.exc_obj.tool_offset.pop(dia_changed, None)
  1274. # we reactivate the signals after the after the tool editing
  1275. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1276. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1277. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1278. def on_name_activate(self):
  1279. self.edited_obj_name = self.name_entry.get_value()
  1280. def activate(self):
  1281. # adjust the status of the menu entries related to the editor
  1282. self.app.ui.menueditedit.setDisabled(True)
  1283. self.app.ui.menueditok.setDisabled(False)
  1284. # adjust the visibility of some of the canvas context menu
  1285. self.app.ui.popmenu_edit.setVisible(False)
  1286. self.app.ui.popmenu_save.setVisible(True)
  1287. self.connect_canvas_event_handlers()
  1288. # initialize working objects
  1289. self.storage_dict = {}
  1290. self.current_storage = []
  1291. self.points_edit = {}
  1292. self.sorted_diameters = []
  1293. self.new_drills = []
  1294. self.new_tools = {}
  1295. self.new_slots = {}
  1296. self.new_tool_offset = {}
  1297. self.olddia_newdia = {}
  1298. self.shapes.enabled = True
  1299. self.tool_shape.enabled = True
  1300. # self.app.app_cursor.enabled = True
  1301. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1302. self.app.ui.corner_snap_btn.setEnabled(True)
  1303. self.app.ui.snap_magnet.setVisible(True)
  1304. self.app.ui.corner_snap_btn.setVisible(True)
  1305. self.app.ui.exc_editor_menu.setDisabled(False)
  1306. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  1307. self.app.ui.update_obj_btn.setEnabled(True)
  1308. self.app.ui.e_editor_cmenu.setEnabled(True)
  1309. self.app.ui.exc_edit_toolbar.setDisabled(False)
  1310. self.app.ui.exc_edit_toolbar.setVisible(True)
  1311. # self.app.ui.snap_toolbar.setDisabled(False)
  1312. # start with GRID toolbar activated
  1313. if self.app.ui.grid_snap_btn.isChecked() is False:
  1314. self.app.ui.grid_snap_btn.trigger()
  1315. self.app.ui.popmenu_disable.setVisible(False)
  1316. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  1317. self.app.ui.popmenu_properties.setVisible(False)
  1318. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  1319. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1320. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1321. # Tell the App that the editor is active
  1322. self.editor_active = True
  1323. # show the UI
  1324. self.drills_frame.show()
  1325. def deactivate(self):
  1326. try:
  1327. QtGui.QGuiApplication.restoreOverrideCursor()
  1328. except:
  1329. pass
  1330. # adjust the status of the menu entries related to the editor
  1331. self.app.ui.menueditedit.setDisabled(False)
  1332. self.app.ui.menueditok.setDisabled(True)
  1333. # adjust the visibility of some of the canvas context menu
  1334. self.app.ui.popmenu_edit.setVisible(True)
  1335. self.app.ui.popmenu_save.setVisible(False)
  1336. self.disconnect_canvas_event_handlers()
  1337. self.clear()
  1338. self.app.ui.exc_edit_toolbar.setDisabled(True)
  1339. settings = QSettings("Open Source", "FlatCAM")
  1340. if settings.contains("layout"):
  1341. layout = settings.value('layout', type=str)
  1342. if layout == 'standard':
  1343. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1344. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1345. self.app.ui.corner_snap_btn.setEnabled(False)
  1346. self.app.ui.snap_magnet.setVisible(False)
  1347. self.app.ui.corner_snap_btn.setVisible(False)
  1348. elif layout == 'compact':
  1349. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1350. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1351. self.app.ui.corner_snap_btn.setEnabled(False)
  1352. self.app.ui.snap_magnet.setVisible(True)
  1353. self.app.ui.corner_snap_btn.setVisible(True)
  1354. else:
  1355. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1356. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1357. self.app.ui.corner_snap_btn.setEnabled(False)
  1358. self.app.ui.snap_magnet.setVisible(False)
  1359. self.app.ui.corner_snap_btn.setVisible(False)
  1360. # set the Editor Toolbar visibility to what was before entering in the Editor
  1361. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1362. else self.app.ui.exc_edit_toolbar.setVisible(True)
  1363. # Disable visuals
  1364. self.shapes.enabled = False
  1365. self.tool_shape.enabled = False
  1366. # self.app.app_cursor.enabled = False
  1367. # Tell the app that the editor is no longer active
  1368. self.editor_active = False
  1369. self.app.ui.exc_editor_menu.setDisabled(True)
  1370. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  1371. self.app.ui.update_obj_btn.setEnabled(False)
  1372. self.app.ui.popmenu_disable.setVisible(True)
  1373. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  1374. self.app.ui.popmenu_properties.setVisible(True)
  1375. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1376. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  1377. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1378. # Show original geometry
  1379. if self.exc_obj:
  1380. self.exc_obj.visible = True
  1381. # hide the UI
  1382. self.drills_frame.hide()
  1383. def connect_canvas_event_handlers(self):
  1384. ## Canvas events
  1385. # first connect to new, then disconnect the old handlers
  1386. # don't ask why but if there is nothing connected I've seen issues
  1387. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1388. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1389. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  1390. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1391. # but those from FlatCAMGeoEditor
  1392. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1393. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1394. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1395. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1396. self.app.collection.view.clicked.disconnect()
  1397. self.app.ui.popmenu_copy.triggered.disconnect()
  1398. self.app.ui.popmenu_delete.triggered.disconnect()
  1399. self.app.ui.popmenu_move.triggered.disconnect()
  1400. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  1401. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  1402. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  1403. # Excellon Editor
  1404. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  1405. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  1406. def disconnect_canvas_event_handlers(self):
  1407. # we restore the key and mouse control to FlatCAMApp method
  1408. # first connect to new, then disconnect the old handlers
  1409. # don't ask why but if there is nothing connected I've seen issues
  1410. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1411. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1412. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1413. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1414. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1415. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1416. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1417. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  1418. try:
  1419. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  1420. except TypeError:
  1421. pass
  1422. try:
  1423. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  1424. except TypeError:
  1425. pass
  1426. try:
  1427. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  1428. except TypeError:
  1429. pass
  1430. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  1431. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  1432. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  1433. # Excellon Editor
  1434. try:
  1435. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  1436. except TypeError:
  1437. pass
  1438. try:
  1439. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  1440. except TypeError:
  1441. pass
  1442. def clear(self):
  1443. self.active_tool = None
  1444. # self.shape_buffer = []
  1445. self.selected = []
  1446. self.points_edit = {}
  1447. self.new_tools = {}
  1448. self.new_drills = []
  1449. # self.storage_dict = {}
  1450. self.shapes.clear(update=True)
  1451. self.tool_shape.clear(update=True)
  1452. # self.storage = FlatCAMExcEditor.make_storage()
  1453. self.replot()
  1454. def edit_fcexcellon(self, exc_obj):
  1455. """
  1456. Imports the geometry from the given FlatCAM Excellon object
  1457. into the editor.
  1458. :param fcgeometry: FlatCAMExcellon
  1459. :return: None
  1460. """
  1461. assert isinstance(exc_obj, Excellon), \
  1462. "Expected an Excellon Object, got %s" % type(exc_obj)
  1463. self.deactivate()
  1464. self.activate()
  1465. # Hide original geometry
  1466. self.exc_obj = exc_obj
  1467. exc_obj.visible = False
  1468. # Set selection tolerance
  1469. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1470. self.select_tool("select")
  1471. self.set_ui()
  1472. # now that we hava data, create the GUI interface and add it to the Tool Tab
  1473. self.build_ui(first_run=True)
  1474. # we activate this after the initial build as we don't need to see the tool been populated
  1475. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1476. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  1477. # and then add it to the storage elements (each storage elements is a member of a list
  1478. for tool_dia in self.points_edit:
  1479. storage_elem = FlatCAMGeoEditor.make_storage()
  1480. for point in self.points_edit[tool_dia]:
  1481. # make a '+' sign, the line length is the tool diameter
  1482. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  1483. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  1484. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  1485. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  1486. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  1487. if shape is not None:
  1488. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  1489. self.storage_dict[tool_dia] = storage_elem
  1490. self.replot()
  1491. # add a first tool in the Tool Table but only if the Excellon Object is empty
  1492. if not self.tool2tooldia:
  1493. self.on_tool_add(tooldia=1.00)
  1494. def update_fcexcellon(self, exc_obj):
  1495. """
  1496. Create a new Excellon object that contain the edited content of the source Excellon object
  1497. :param exc_obj: FlatCAMExcellon
  1498. :return: None
  1499. """
  1500. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  1501. # the values of this dict are coordinates of the holes (drills)
  1502. edited_points = {}
  1503. for storage_tooldia in self.storage_dict:
  1504. for x in self.storage_dict[storage_tooldia].get_objects():
  1505. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  1506. # each MultiLineString is made out of Linestrings
  1507. # select first Linestring object in the current MultiLineString
  1508. first_linestring = x.geo[0]
  1509. # get it's coordinates
  1510. first_linestring_coords = first_linestring.coords
  1511. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  1512. y_coord = first_linestring_coords[0][1]
  1513. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  1514. # edited_points dictionary
  1515. point = (x_coord, y_coord)
  1516. if not storage_tooldia in edited_points:
  1517. edited_points[storage_tooldia] = [point]
  1518. else:
  1519. edited_points[storage_tooldia].append(point)
  1520. # recreate the drills and tools to be added to the new Excellon edited object
  1521. # first, we look in the tool table if one of the tool diameters was changed then
  1522. # append that a tuple formed by (old_dia, edited_dia) to a list
  1523. changed_key = []
  1524. for initial_dia in self.olddia_newdia:
  1525. edited_dia = self.olddia_newdia[initial_dia]
  1526. if edited_dia != initial_dia:
  1527. for old_dia in edited_points:
  1528. if old_dia == initial_dia:
  1529. changed_key.append((old_dia, edited_dia))
  1530. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  1531. # (and we have to add it)
  1532. # because in case we have drill points it will have to be already added in edited_points
  1533. # if initial_dia not in edited_points.keys():
  1534. # edited_points[initial_dia] = []
  1535. for el in changed_key:
  1536. edited_points[el[1]] = edited_points.pop(el[0])
  1537. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  1538. # ordered_edited_points is a ordered list of tuples;
  1539. # element[0] of the tuple is the diameter and
  1540. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  1541. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  1542. current_tool = 0
  1543. for tool_dia in ordered_edited_points:
  1544. current_tool += 1
  1545. # create the self.tools for the new Excellon object (the one with edited content)
  1546. name = str(current_tool)
  1547. spec = {"C": float(tool_dia[0])}
  1548. self.new_tools[name] = spec
  1549. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  1550. self.new_tools[name]['solid_geometry'] = []
  1551. # create the self.drills for the new Excellon object (the one with edited content)
  1552. for point in tool_dia[1]:
  1553. self.new_drills.append(
  1554. {
  1555. 'point': Point(point),
  1556. 'tool': str(current_tool)
  1557. }
  1558. )
  1559. # repopulate the 'solid_geometry' for each tool
  1560. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  1561. self.new_tools[name]['solid_geometry'].append(poly)
  1562. if self.is_modified is True:
  1563. if "_edit" in self.edited_obj_name:
  1564. try:
  1565. id = int(self.edited_obj_name[-1]) + 1
  1566. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  1567. except ValueError:
  1568. self.edited_obj_name += "_1"
  1569. else:
  1570. self.edited_obj_name += "_edit"
  1571. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  1572. 'params': [self.edited_obj_name]})
  1573. if self.exc_obj.slots:
  1574. self.new_slots = self.exc_obj.slots
  1575. self.new_tool_offset = self.exc_obj.tool_offset
  1576. # reset the tool table
  1577. self.tools_table_exc.clear()
  1578. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1579. self.last_tool_selected = None
  1580. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  1581. self.app.collection.set_active(self.exc_obj.options['name'])
  1582. self.app.collection.delete_active()
  1583. # restore GUI to the Selected TAB
  1584. # Remove anything else in the GUI
  1585. self.app.ui.tool_scroll_area.takeWidget()
  1586. # Switch notebook to Selected page
  1587. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1588. def update_options(self, obj):
  1589. try:
  1590. if not obj.options:
  1591. obj.options = {}
  1592. obj.options['xmin'] = 0
  1593. obj.options['ymin'] = 0
  1594. obj.options['xmax'] = 0
  1595. obj.options['ymax'] = 0
  1596. return True
  1597. else:
  1598. return False
  1599. except AttributeError:
  1600. obj.options = {}
  1601. return True
  1602. def new_edited_excellon(self, outname):
  1603. """
  1604. Creates a new Excellon object for the edited Excellon. Thread-safe.
  1605. :param outname: Name of the resulting object. None causes the
  1606. name to be that of the file.
  1607. :type outname: str
  1608. :return: None
  1609. """
  1610. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  1611. self.exc_obj.options['name'])
  1612. # How the object should be initialized
  1613. def obj_init(excellon_obj, app_obj):
  1614. # self.progress.emit(20)
  1615. excellon_obj.drills = self.new_drills
  1616. excellon_obj.tools = self.new_tools
  1617. excellon_obj.slots = self.new_slots
  1618. excellon_obj.tool_offset = self.new_tool_offset
  1619. excellon_obj.options['name'] = outname
  1620. try:
  1621. excellon_obj.create_geometry()
  1622. except KeyError:
  1623. self.app.inform.emit(
  1624. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  1625. )
  1626. except:
  1627. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1628. msg += traceback.format_exc()
  1629. app_obj.inform.emit(msg)
  1630. raise
  1631. # raise
  1632. with self.app.proc_container.new(_("Creating Excellon.")):
  1633. try:
  1634. self.app.new_object("excellon", outname, obj_init)
  1635. except Exception as e:
  1636. log.error("Error on object creation: %s" % str(e))
  1637. self.app.progress.emit(100)
  1638. return
  1639. self.app.inform.emit(_("[success] Excellon editing finished."))
  1640. # self.progress.emit(100)
  1641. def on_tool_select(self, tool):
  1642. """
  1643. Behavior of the toolbar. Tool initialization.
  1644. :rtype : None
  1645. """
  1646. current_tool = tool
  1647. self.app.log.debug("on_tool_select('%s')" % tool)
  1648. if self.last_tool_selected is None and current_tool is not 'select':
  1649. # self.draw_app.select_tool('select')
  1650. self.complete = True
  1651. current_tool = 'select'
  1652. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  1653. # This is to make the group behave as radio group
  1654. if current_tool in self.tools_exc:
  1655. if self.tools_exc[current_tool]["button"].isChecked():
  1656. self.app.log.debug("%s is checked." % current_tool)
  1657. for t in self.tools_exc:
  1658. if t != current_tool:
  1659. self.tools_exc[t]["button"].setChecked(False)
  1660. # this is where the Editor toolbar classes (button's) are instantiated
  1661. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  1662. # self.app.inform.emit(self.active_tool.start_msg)
  1663. else:
  1664. self.app.log.debug("%s is NOT checked." % current_tool)
  1665. for t in self.tools_exc:
  1666. self.tools_exc[t]["button"].setChecked(False)
  1667. self.select_tool('select')
  1668. self.active_tool = FCDrillSelect(self)
  1669. def on_row_selected(self, row, col):
  1670. if col == 0:
  1671. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1672. if self.app.defaults["global_mselect_key"] == 'Control':
  1673. modifier_to_use = Qt.ControlModifier
  1674. else:
  1675. modifier_to_use = Qt.ShiftModifier
  1676. if key_modifier == modifier_to_use:
  1677. pass
  1678. else:
  1679. self.selected = []
  1680. try:
  1681. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  1682. self.last_tool_selected = copy(self.tools_table_exc.currentRow()) + 1
  1683. for obj in self.storage_dict[selected_dia].get_objects():
  1684. self.selected.append(obj)
  1685. except Exception as e:
  1686. self.app.log.debug(str(e))
  1687. self.replot()
  1688. def toolbar_tool_toggle(self, key):
  1689. self.options[key] = self.sender().isChecked()
  1690. if self.options[key] == True:
  1691. return 1
  1692. else:
  1693. return 0
  1694. def on_canvas_click(self, event):
  1695. """
  1696. event.x and .y have canvas coordinates
  1697. event.xdaya and .ydata have plot coordinates
  1698. :param event: Event object dispatched by Matplotlib
  1699. :return: None
  1700. """
  1701. if event.button is 1:
  1702. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1703. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  1704. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1705. # Snap coordinates
  1706. if self.app.grid_status():
  1707. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  1708. self.app.app_cursor.enabled = True
  1709. # Update cursor
  1710. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  1711. size=20)
  1712. else:
  1713. self.pos = (self.pos[0], self.pos[1])
  1714. self.app.app_cursor.enabled = False
  1715. # Selection with left mouse button
  1716. if self.active_tool is not None and event.button is 1:
  1717. # Dispatch event to active_tool
  1718. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1719. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  1720. # If it is a shape generating tool
  1721. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  1722. if self.current_storage is not None:
  1723. self.on_exc_shape_complete(self.current_storage)
  1724. self.build_ui()
  1725. # MS: always return to the Select Tool if modifier key is not pressed
  1726. # else return to the current tool
  1727. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1728. if self.app.defaults["global_mselect_key"] == 'Control':
  1729. modifier_to_use = Qt.ControlModifier
  1730. else:
  1731. modifier_to_use = Qt.ShiftModifier
  1732. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1733. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1734. if key_modifier == modifier_to_use:
  1735. self.select_tool(self.active_tool.name)
  1736. else:
  1737. self.select_tool("select")
  1738. return
  1739. if isinstance(self.active_tool, FCDrillSelect):
  1740. # self.app.log.debug("Replotting after click.")
  1741. self.replot()
  1742. else:
  1743. self.app.log.debug("No active tool to respond to click!")
  1744. def on_exc_shape_complete(self, storage):
  1745. self.app.log.debug("on_shape_complete()")
  1746. # Add shape
  1747. if type(storage) is list:
  1748. for item_storage in storage:
  1749. self.add_exc_shape(self.active_tool.geometry, item_storage)
  1750. else:
  1751. self.add_exc_shape(self.active_tool.geometry, storage)
  1752. # Remove any utility shapes
  1753. self.delete_utility_geometry()
  1754. self.tool_shape.clear(update=True)
  1755. # Replot and reset tool.
  1756. self.replot()
  1757. # self.active_tool = type(self.active_tool)(self)
  1758. def add_exc_shape(self, shape, storage):
  1759. """
  1760. Adds a shape to the shape storage.
  1761. :param shape: Shape to be added.
  1762. :type shape: DrawToolShape
  1763. :return: None
  1764. """
  1765. # List of DrawToolShape?
  1766. if isinstance(shape, list):
  1767. for subshape in shape:
  1768. self.add_exc_shape(subshape, storage)
  1769. return
  1770. assert isinstance(shape, DrawToolShape), \
  1771. "Expected a DrawToolShape, got %s" % str(type(shape))
  1772. assert shape.geo is not None, \
  1773. "Shape object has empty geometry (None)"
  1774. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1775. not isinstance(shape.geo, list), \
  1776. "Shape objects has empty geometry ([])"
  1777. if isinstance(shape, DrawToolUtilityShape):
  1778. self.utility.append(shape)
  1779. else:
  1780. storage.insert(shape) # TODO: Check performance
  1781. def add_shape(self, shape):
  1782. """
  1783. Adds a shape to the shape storage.
  1784. :param shape: Shape to be added.
  1785. :type shape: DrawToolShape
  1786. :return: None
  1787. """
  1788. # List of DrawToolShape?
  1789. if isinstance(shape, list):
  1790. for subshape in shape:
  1791. self.add_shape(subshape)
  1792. return
  1793. assert isinstance(shape, DrawToolShape), \
  1794. "Expected a DrawToolShape, got %s" % type(shape)
  1795. assert shape.geo is not None, \
  1796. "Shape object has empty geometry (None)"
  1797. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1798. not isinstance(shape.geo, list), \
  1799. "Shape objects has empty geometry ([])"
  1800. if isinstance(shape, DrawToolUtilityShape):
  1801. self.utility.append(shape)
  1802. else:
  1803. self.storage.insert(shape) # TODO: Check performance
  1804. def on_exc_click_release(self, event):
  1805. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  1806. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  1807. if self.app.grid_status():
  1808. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  1809. else:
  1810. pos = (pos_canvas[0], pos_canvas[1])
  1811. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  1812. # canvas menu
  1813. try:
  1814. if event.button == 2: # right click
  1815. if self.app.panning_action is True:
  1816. self.app.panning_action = False
  1817. else:
  1818. self.app.cursor = QtGui.QCursor()
  1819. self.app.populate_cmenu_grids()
  1820. self.app.ui.popMenu.popup(self.app.cursor.pos())
  1821. except Exception as e:
  1822. log.warning("Error: %s" % str(e))
  1823. raise
  1824. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  1825. # selection and then select a type of selection ("enclosing" or "touching")
  1826. try:
  1827. if event.button == 1: # left click
  1828. if self.app.selection_type is not None:
  1829. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  1830. self.app.selection_type = None
  1831. elif isinstance(self.active_tool, FCDrillSelect):
  1832. # Dispatch event to active_tool
  1833. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1834. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  1835. # self.app.inform.emit(msg)
  1836. self.active_tool.click_release((self.pos[0], self.pos[1]))
  1837. self.replot()
  1838. except Exception as e:
  1839. log.warning("Error: %s" % str(e))
  1840. raise
  1841. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  1842. """
  1843. :param start_pos: mouse position when the selection LMB click was done
  1844. :param end_pos: mouse position when the left mouse button is released
  1845. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1846. :type Bool
  1847. :return:
  1848. """
  1849. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1850. self.app.delete_selection_shape()
  1851. for storage in self.storage_dict:
  1852. for obj in self.storage_dict[storage].get_objects():
  1853. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  1854. (sel_type is False and poly_selection.intersects(obj.geo)):
  1855. if self.key == self.app.defaults["global_mselect_key"]:
  1856. if obj in self.selected:
  1857. self.selected.remove(obj)
  1858. else:
  1859. # add the object to the selected shapes
  1860. self.selected.append(obj)
  1861. else:
  1862. self.selected.append(obj)
  1863. try:
  1864. self.tools_table_exc.cellPressed.disconnect()
  1865. except:
  1866. pass
  1867. # select the diameter of the selected shape in the tool table
  1868. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1869. for storage in self.storage_dict:
  1870. for shape_s in self.selected:
  1871. if shape_s in self.storage_dict[storage].get_objects():
  1872. for key in self.tool2tooldia:
  1873. if self.tool2tooldia[key] == storage:
  1874. item = self.tools_table_exc.item((key - 1), 1)
  1875. self.tools_table_exc.setCurrentItem(item)
  1876. self.last_tool_selected = key
  1877. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1878. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1879. self.replot()
  1880. def on_canvas_move(self, event):
  1881. """
  1882. Called on 'mouse_move' event
  1883. event.pos have canvas screen coordinates
  1884. :param event: Event object dispatched by VisPy SceneCavas
  1885. :return: None
  1886. """
  1887. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1888. event.xdata, event.ydata = pos[0], pos[1]
  1889. self.x = event.xdata
  1890. self.y = event.ydata
  1891. # Prevent updates on pan
  1892. # if len(event.buttons) > 0:
  1893. # return
  1894. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  1895. if event.button == 2:
  1896. self.app.panning_action = True
  1897. return
  1898. else:
  1899. self.app.panning_action = False
  1900. try:
  1901. x = float(event.xdata)
  1902. y = float(event.ydata)
  1903. except TypeError:
  1904. return
  1905. if self.active_tool is None:
  1906. return
  1907. ### Snap coordinates
  1908. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  1909. self.snap_x = x
  1910. self.snap_y = y
  1911. # update the position label in the infobar since the APP mouse event handlers are disconnected
  1912. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1913. "<b>Y</b>: %.4f" % (x, y))
  1914. if self.pos is None:
  1915. self.pos = (0, 0)
  1916. dx = x - self.pos[0]
  1917. dy = y - self.pos[1]
  1918. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  1919. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1920. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1921. ### Utility geometry (animated)
  1922. geo = self.active_tool.utility_geometry(data=(x, y))
  1923. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  1924. # Remove any previous utility shape
  1925. self.tool_shape.clear(update=True)
  1926. self.draw_utility_geometry(geo=geo)
  1927. ### Selection area on canvas section ###
  1928. dx = pos[0] - self.pos[0]
  1929. if event.is_dragging == 1 and event.button == 1:
  1930. self.app.delete_selection_shape()
  1931. if dx < 0:
  1932. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  1933. color=self.app.defaults["global_alt_sel_line"],
  1934. face_color=self.app.defaults['global_alt_sel_fill'])
  1935. self.app.selection_type = False
  1936. else:
  1937. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  1938. self.app.selection_type = True
  1939. else:
  1940. self.app.selection_type = None
  1941. # Update cursor
  1942. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  1943. def on_canvas_key_release(self, event):
  1944. self.key = None
  1945. def draw_utility_geometry(self, geo):
  1946. # Add the new utility shape
  1947. try:
  1948. # this case is for the Font Parse
  1949. for el in list(geo.geo):
  1950. if type(el) == MultiPolygon:
  1951. for poly in el:
  1952. self.tool_shape.add(
  1953. shape=poly,
  1954. color=(self.app.defaults["global_draw_color"] + '80'),
  1955. update=False,
  1956. layer=0,
  1957. tolerance=None
  1958. )
  1959. elif type(el) == MultiLineString:
  1960. for linestring in el:
  1961. self.tool_shape.add(
  1962. shape=linestring,
  1963. color=(self.app.defaults["global_draw_color"] + '80'),
  1964. update=False,
  1965. layer=0,
  1966. tolerance=None
  1967. )
  1968. else:
  1969. self.tool_shape.add(
  1970. shape=el,
  1971. color=(self.app.defaults["global_draw_color"] + '80'),
  1972. update=False,
  1973. layer=0,
  1974. tolerance=None
  1975. )
  1976. except TypeError:
  1977. self.tool_shape.add(
  1978. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  1979. update=False, layer=0, tolerance=None)
  1980. self.tool_shape.redraw()
  1981. def replot(self):
  1982. self.plot_all()
  1983. def plot_all(self):
  1984. """
  1985. Plots all shapes in the editor.
  1986. :return: None
  1987. :rtype: None
  1988. """
  1989. # self.app.log.debug("plot_all()")
  1990. self.shapes.clear(update=True)
  1991. for storage in self.storage_dict:
  1992. for shape_plus in self.storage_dict[storage].get_objects():
  1993. if shape_plus.geo is None:
  1994. continue
  1995. if shape_plus in self.selected:
  1996. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  1997. linewidth=2)
  1998. continue
  1999. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  2000. # for shape in self.storage.get_objects():
  2001. # if shape.geo is None: # TODO: This shouldn't have happened
  2002. # continue
  2003. #
  2004. # if shape in self.selected:
  2005. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2006. # continue
  2007. #
  2008. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2009. for shape in self.utility:
  2010. self.plot_shape(geometry=shape.geo, linewidth=1)
  2011. continue
  2012. self.shapes.redraw()
  2013. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2014. """
  2015. Plots a geometric object or list of objects without rendering. Plotted objects
  2016. are returned as a list. This allows for efficient/animated rendering.
  2017. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2018. :param color: Shape color
  2019. :param linewidth: Width of lines in # of pixels.
  2020. :return: List of plotted elements.
  2021. """
  2022. plot_elements = []
  2023. if geometry is None:
  2024. geometry = self.active_tool.geometry
  2025. try:
  2026. for geo in geometry:
  2027. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2028. ## Non-iterable
  2029. except TypeError:
  2030. ## DrawToolShape
  2031. if isinstance(geometry, DrawToolShape):
  2032. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2033. ## Polygon: Descend into exterior and each interior.
  2034. if type(geometry) == Polygon:
  2035. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2036. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2037. if type(geometry) == LineString or type(geometry) == LinearRing:
  2038. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  2039. if type(geometry) == Point:
  2040. pass
  2041. return plot_elements
  2042. def on_shape_complete(self):
  2043. self.app.log.debug("on_shape_complete()")
  2044. # Add shape
  2045. self.add_shape(self.active_tool.geometry)
  2046. # Remove any utility shapes
  2047. self.delete_utility_geometry()
  2048. self.tool_shape.clear(update=True)
  2049. # Replot and reset tool.
  2050. self.replot()
  2051. # self.active_tool = type(self.active_tool)(self)
  2052. def get_selected(self):
  2053. """
  2054. Returns list of shapes that are selected in the editor.
  2055. :return: List of shapes.
  2056. """
  2057. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2058. return self.selected
  2059. def delete_selected(self):
  2060. temp_ref = [s for s in self.selected]
  2061. for shape_sel in temp_ref:
  2062. self.delete_shape(shape_sel)
  2063. self.selected = []
  2064. self.build_ui()
  2065. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  2066. def delete_shape(self, shape):
  2067. self.is_modified = True
  2068. if shape in self.utility:
  2069. self.utility.remove(shape)
  2070. return
  2071. for storage in self.storage_dict:
  2072. # try:
  2073. # self.storage_dict[storage].remove(shape)
  2074. # except:
  2075. # pass
  2076. if shape in self.storage_dict[storage].get_objects():
  2077. self.storage_dict[storage].remove(shape)
  2078. # a hack to make the tool_table display less drills per diameter
  2079. # self.points_edit it's only useful first time when we load the data into the storage
  2080. # but is still used as referecen when building tool_table in self.build_ui()
  2081. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2082. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  2083. del self.points_edit[storage][0]
  2084. if shape in self.selected:
  2085. self.selected.remove(shape) # TODO: Check performance
  2086. def delete_utility_geometry(self):
  2087. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2088. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2089. for_deletion = [shape for shape in self.utility]
  2090. for shape in for_deletion:
  2091. self.delete_shape(shape)
  2092. self.tool_shape.clear(update=True)
  2093. self.tool_shape.redraw()
  2094. def on_delete_btn(self):
  2095. self.delete_selected()
  2096. self.replot()
  2097. def select_tool(self, toolname):
  2098. """
  2099. Selects a drawing tool. Impacts the object and GUI.
  2100. :param toolname: Name of the tool.
  2101. :return: None
  2102. """
  2103. self.tools_exc[toolname]["button"].setChecked(True)
  2104. self.on_tool_select(toolname)
  2105. def set_selected(self, shape):
  2106. # Remove and add to the end.
  2107. if shape in self.selected:
  2108. self.selected.remove(shape)
  2109. self.selected.append(shape)
  2110. def set_unselected(self, shape):
  2111. if shape in self.selected:
  2112. self.selected.remove(shape)
  2113. def on_array_type_combo(self):
  2114. if self.array_type_combo.currentIndex() == 0:
  2115. self.array_circular_frame.hide()
  2116. self.array_linear_frame.show()
  2117. else:
  2118. self.delete_utility_geometry()
  2119. self.array_circular_frame.show()
  2120. self.array_linear_frame.hide()
  2121. self.app.inform.emit(_("Click on the circular array Center position"))
  2122. def on_linear_angle_radio(self):
  2123. val = self.drill_axis_radio.get_value()
  2124. if val == 'A':
  2125. self.linear_angle_spinner.show()
  2126. self.linear_angle_label.show()
  2127. else:
  2128. self.linear_angle_spinner.hide()
  2129. self.linear_angle_label.hide()
  2130. def exc_add_drill(self):
  2131. self.select_tool('drill_add')
  2132. return
  2133. def exc_add_drill_array(self):
  2134. self.select_tool('drill_array')
  2135. return
  2136. def exc_resize_drills(self):
  2137. self.select_tool('drill_resize')
  2138. return
  2139. def exc_copy_drills(self):
  2140. self.select_tool('drill_copy')
  2141. return
  2142. def exc_move_drills(self):
  2143. self.select_tool('drill_move')
  2144. return