FlatCAMGrbEditor.py 87 KB

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