FlatCAMExcEditor.py 112 KB

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