FlatCAMExcEditor.py 109 KB

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