FlatCAMExcEditor.py 103 KB

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