FlatCAMExcEditor.py 101 KB

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