FlatCAMExcEditor.py 103 KB

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