FlatCAMExcEditor.py 103 KB

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