FlatCAMExcEditor.py 110 KB

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