FlatCAMGrbEditor.py 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  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 Apertures 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.apertures_table.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.apertures_table.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.apertures_table.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.apertures_table.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, grb_editor_app):
  199. DrawTool.__init__(self, grb_editor_app)
  200. self.name = 'drill_select'
  201. self.grb_editor_app = grb_editor_app
  202. self.storage = self.grb_editor_app.storage_dict
  203. # self.selected = self.grb_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.grb_editor_app.resize_frame.hide()
  207. self.grb_editor_app.array_frame.hide()
  208. def click(self, point):
  209. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  210. if self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control':
  211. if key_modifier == Qt.ControlModifier:
  212. pass
  213. else:
  214. self.grb_editor_app.selected = []
  215. else:
  216. if key_modifier == Qt.ShiftModifier:
  217. pass
  218. else:
  219. self.grb_editor_app.selected = []
  220. def click_release(self, point):
  221. self.select_shapes(point)
  222. return ""
  223. def select_shapes(self, pos):
  224. self.grb_editor_app.apertures_table.clearSelection()
  225. try:
  226. # for storage in self.grb_editor_app.storage_dict:
  227. # _, partial_closest_shape = self.grb_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.grb_editor_app.storage_dict:
  233. for shape in self.grb_editor_app.storage_dict[storage].get_objects():
  234. self.sel_storage.insert(DrawToolShape(LineString(shape.geo.exterior)))
  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.grb_editor_app.selected = []
  248. else:
  249. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  250. if self.grb_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.grb_editor_app.selected:
  255. self.grb_editor_app.selected.remove(closest_shape)
  256. else:
  257. self.grb_editor_app.selected.append(closest_shape)
  258. else:
  259. self.grb_editor_app.selected = []
  260. self.grb_editor_app.selected.append(closest_shape)
  261. else:
  262. if key_modifier == Qt.ShiftModifier:
  263. if closest_shape in self.grb_editor_app.selected:
  264. self.grb_editor_app.selected.remove(closest_shape)
  265. else:
  266. self.grb_editor_app.selected.append(closest_shape)
  267. else:
  268. self.grb_editor_app.selected = []
  269. self.grb_editor_app.selected.append(closest_shape)
  270. # select the diameter of the selected shape in the tool table
  271. for storage in self.grb_editor_app.storage_dict:
  272. for shape_s in self.grb_editor_app.selected:
  273. if shape_s in self.grb_editor_app.storage_dict[storage].get_objects():
  274. for key in self.grb_editor_app.tool2tooldia:
  275. if self.grb_editor_app.tool2tooldia[key] == storage:
  276. item = self.grb_editor_app.apertures_table.item((key - 1), 1)
  277. self.grb_editor_app.apertures_table.setCurrentItem(item)
  278. # item.setSelected(True)
  279. # self.grb_editor_app.apertures_table.selectItem(key - 1)
  280. # midx = self.grb_editor_app.apertures_table.model().index((key - 1), 0)
  281. # self.grb_editor_app.apertures_table.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.grb_edit_widget = QtWidgets.QWidget()
  297. layout = QtWidgets.QVBoxLayout()
  298. self.grb_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 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.apertures_frame = QtWidgets.QFrame()
  325. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  326. self.custom_box.addWidget(self.apertures_frame)
  327. self.apertures_box = QtWidgets.QVBoxLayout()
  328. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  329. self.apertures_frame.setLayout(self.apertures_box)
  330. #### Gerber Apertures ####
  331. self.apertures_table_label = QtWidgets.QLabel(_('<b>Apertures:</b>'))
  332. self.apertures_table_label.setToolTip(
  333. _("Apertures Table for the Gerber Object.")
  334. )
  335. self.apertures_box.addWidget(self.apertures_table_label)
  336. self.apertures_table = FCTable()
  337. # delegate = SpinBoxDelegate(units=self.units)
  338. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  339. self.apertures_box.addWidget(self.apertures_table)
  340. self.apertures_table.setColumnCount(5)
  341. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  342. self.apertures_table.setSortingEnabled(False)
  343. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  344. _("Index"))
  345. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  346. _("Aperture Code"))
  347. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  348. _("Type of aperture: circular, rectangle, macros etc"))
  349. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  350. _("Aperture Size:"))
  351. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  352. _("Aperture Dimensions:\n"
  353. " - (width, height) for R, O type.\n"
  354. " - (dia, nVertices) for P type"))
  355. self.empty_label = QtWidgets.QLabel('')
  356. self.apertures_box.addWidget(self.empty_label)
  357. #### Add a new Tool ####
  358. self.addaperture_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Aperture'))
  359. self.addaperture_label.setToolTip(
  360. _("Add/Delete an aperture to the aperture list")
  361. )
  362. self.apertures_box.addWidget(self.addaperture_label)
  363. grid1 = QtWidgets.QGridLayout()
  364. self.apertures_box.addLayout(grid1)
  365. addaperture_entry_lbl = QtWidgets.QLabel(_('Aperture Size:'))
  366. addaperture_entry_lbl.setToolTip(
  367. _("Size for the new aperture")
  368. )
  369. grid1.addWidget(addaperture_entry_lbl, 0, 0)
  370. hlay = QtWidgets.QHBoxLayout()
  371. self.addtool_entry = FCEntry()
  372. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  373. hlay.addWidget(self.addtool_entry)
  374. self.addaperture_btn = QtWidgets.QPushButton(_('Add Aperture'))
  375. self.addaperture_btn.setToolTip(
  376. _( "Add a new aperture to the aperture list")
  377. )
  378. self.addaperture_btn.setFixedWidth(80)
  379. hlay.addWidget(self.addaperture_btn)
  380. grid1.addLayout(hlay, 0, 1)
  381. grid2 = QtWidgets.QGridLayout()
  382. self.apertures_box.addLayout(grid2)
  383. self.delaperture_btn = QtWidgets.QPushButton(_('Delete Aperture'))
  384. self.delaperture_btn.setToolTip(
  385. _( "Delete a aperture in the aperture list")
  386. )
  387. grid2.addWidget(self.delaperture_btn, 0, 1)
  388. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the aperture widgets
  389. # this way I can hide/show the frame
  390. self.resize_frame = QtWidgets.QFrame()
  391. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  392. self.apertures_box.addWidget(self.resize_frame)
  393. self.resize_box = QtWidgets.QVBoxLayout()
  394. self.resize_box.setContentsMargins(0, 0, 0, 0)
  395. self.resize_frame.setLayout(self.resize_box)
  396. #### Resize a aperture ####
  397. self.emptyresize_label = QtWidgets.QLabel('')
  398. self.resize_box.addWidget(self.emptyresize_label)
  399. self.apertureresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Aperture"))
  400. self.apertureresize_label.setToolTip(
  401. _("Resize a aperture or a selection of apertures.")
  402. )
  403. self.resize_box.addWidget(self.apertureresize_label)
  404. grid3 = QtWidgets.QGridLayout()
  405. self.resize_box.addLayout(grid3)
  406. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  407. res_entry_lbl.setToolTip(
  408. _( "Size to resize to.")
  409. )
  410. grid3.addWidget(res_entry_lbl, 0, 0)
  411. hlay2 = QtWidgets.QHBoxLayout()
  412. self.resdrill_entry = LengthEntry()
  413. hlay2.addWidget(self.resdrill_entry)
  414. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  415. self.resize_btn.setToolTip(
  416. _("Resize drill(s)")
  417. )
  418. self.resize_btn.setFixedWidth(80)
  419. hlay2.addWidget(self.resize_btn)
  420. grid3.addLayout(hlay2, 0, 1)
  421. self.resize_frame.hide()
  422. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  423. # all the add drill array widgets
  424. # this way I can hide/show the frame
  425. self.array_frame = QtWidgets.QFrame()
  426. self.array_frame.setContentsMargins(0, 0, 0, 0)
  427. self.apertures_box.addWidget(self.array_frame)
  428. self.array_box = QtWidgets.QVBoxLayout()
  429. self.array_box.setContentsMargins(0, 0, 0, 0)
  430. self.array_frame.setLayout(self.array_box)
  431. #### Add DRILL Array ####
  432. self.emptyarray_label = QtWidgets.QLabel('')
  433. self.array_box.addWidget(self.emptyarray_label)
  434. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  435. self.drillarray_label.setToolTip(
  436. _("Add an array of drills (linear or circular array)")
  437. )
  438. self.array_box.addWidget(self.drillarray_label)
  439. self.array_type_combo = FCComboBox()
  440. self.array_type_combo.setToolTip(
  441. _( "Select the type of drills array to create.\n"
  442. "It can be Linear X(Y) or Circular")
  443. )
  444. self.array_type_combo.addItem(_("Linear"))
  445. self.array_type_combo.addItem(_("Circular"))
  446. self.array_box.addWidget(self.array_type_combo)
  447. self.array_form = QtWidgets.QFormLayout()
  448. self.array_box.addLayout(self.array_form)
  449. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  450. self.drill_array_size_label.setToolTip(
  451. _("Specify how many drills to be in the array.")
  452. )
  453. self.drill_array_size_label.setFixedWidth(100)
  454. self.drill_array_size_entry = LengthEntry()
  455. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  456. self.array_linear_frame = QtWidgets.QFrame()
  457. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  458. self.array_box.addWidget(self.array_linear_frame)
  459. self.linear_box = QtWidgets.QVBoxLayout()
  460. self.linear_box.setContentsMargins(0, 0, 0, 0)
  461. self.array_linear_frame.setLayout(self.linear_box)
  462. self.linear_form = QtWidgets.QFormLayout()
  463. self.linear_box.addLayout(self.linear_form)
  464. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  465. self.drill_axis_label.setToolTip(
  466. _("Direction on which the linear array is oriented:\n"
  467. "- 'X' - horizontal axis \n"
  468. "- 'Y' - vertical axis or \n"
  469. "- 'Angle' - a custom angle for the array inclination")
  470. )
  471. self.drill_axis_label.setFixedWidth(100)
  472. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  473. {'label': 'Y', 'value': 'Y'},
  474. {'label': _('Angle'), 'value': 'A'}])
  475. self.drill_axis_radio.set_value('X')
  476. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  477. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  478. self.drill_pitch_label.setToolTip(
  479. _("Pitch = Distance between elements of the array.")
  480. )
  481. self.drill_pitch_label.setFixedWidth(100)
  482. self.drill_pitch_entry = LengthEntry()
  483. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  484. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  485. self.linear_angle_label.setToolTip(
  486. _( "Angle at which the linear array is placed.\n"
  487. "The precision is of max 2 decimals.\n"
  488. "Min value is: -359.99 degrees.\n"
  489. "Max value is: 360.00 degrees.")
  490. )
  491. self.linear_angle_label.setFixedWidth(100)
  492. self.linear_angle_spinner = FCDoubleSpinner()
  493. self.linear_angle_spinner.set_precision(2)
  494. self.linear_angle_spinner.setRange(-359.99, 360.00)
  495. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  496. self.array_circular_frame = QtWidgets.QFrame()
  497. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  498. self.array_box.addWidget(self.array_circular_frame)
  499. self.circular_box = QtWidgets.QVBoxLayout()
  500. self.circular_box.setContentsMargins(0, 0, 0, 0)
  501. self.array_circular_frame.setLayout(self.circular_box)
  502. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  503. self.drill_direction_label.setToolTip(
  504. _( "Direction for circular array."
  505. "Can be CW = clockwise or CCW = counter clockwise.")
  506. )
  507. self.drill_direction_label.setFixedWidth(100)
  508. self.circular_form = QtWidgets.QFormLayout()
  509. self.circular_box.addLayout(self.circular_form)
  510. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  511. {'label': 'CCW.', 'value': 'CCW'}])
  512. self.drill_direction_radio.set_value('CW')
  513. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  514. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  515. self.drill_angle_label.setToolTip(
  516. _("Angle at which each element in circular array is placed.")
  517. )
  518. self.drill_angle_label.setFixedWidth(100)
  519. self.drill_angle_entry = LengthEntry()
  520. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  521. self.array_circular_frame.hide()
  522. self.linear_angle_spinner.hide()
  523. self.linear_angle_label.hide()
  524. self.array_frame.hide()
  525. self.apertures_box.addStretch()
  526. ## Toolbar events and properties
  527. self.tools_exc = {
  528. "select": {"button": self.app.ui.select_drill_btn,
  529. "constructor": FCApertureSelect},
  530. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  531. "constructor": FCApertureResize},
  532. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  533. "constructor": FCApertureCopy},
  534. "drill_move": {"button": self.app.ui.move_drill_btn,
  535. "constructor": FCApertureMove},
  536. }
  537. ### Data
  538. self.active_tool = None
  539. self.storage_dict = {}
  540. self.current_storage = []
  541. # build the data from the Excellon point into a dictionary
  542. # {tool_dia: [geometry_in_points]}
  543. self.points_edit = {}
  544. self.sorted_apid =[]
  545. self.new_drills = []
  546. self.new_tools = {}
  547. self.new_slots = {}
  548. self.new_tool_offset = {}
  549. # dictionary to store the tool_row and diameters in Tool_table
  550. # it will be updated everytime self.build_ui() is called
  551. self.olddia_newdia = {}
  552. self.tool2tooldia = {}
  553. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  554. # is cleared but as a side effect also the selected tool is cleared
  555. self.last_tool_selected = None
  556. self.utility = []
  557. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  558. self.launched_from_shortcuts = False
  559. # this var will store the state of the toolbar before starting the editor
  560. self.toolbar_old_state = False
  561. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  562. self.name_entry.returnPressed.connect(self.on_name_activate)
  563. self.addaperture_btn.clicked.connect(self.on_tool_add)
  564. # self.addtool_entry.editingFinished.connect(self.on_tool_add)
  565. self.delaperture_btn.clicked.connect(self.on_tool_delete)
  566. self.apertures_table.selectionModel().currentChanged.connect(self.on_row_selected)
  567. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  568. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  569. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  570. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  571. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  572. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  573. # Init GUI
  574. self.drill_array_size_entry.set_value(5)
  575. self.drill_pitch_entry.set_value(2.54)
  576. self.drill_angle_entry.set_value(12)
  577. self.drill_direction_radio.set_value('CW')
  578. self.drill_axis_radio.set_value('X')
  579. self.gerber_obj = None
  580. # VisPy Visuals
  581. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  582. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  583. self.app.pool_recreated.connect(self.pool_recreated)
  584. # Remove from scene
  585. self.shapes.enabled = False
  586. self.tool_shape.enabled = False
  587. ## List of selected shapes.
  588. self.selected = []
  589. self.move_timer = QtCore.QTimer()
  590. self.move_timer.setSingleShot(True)
  591. self.key = None # Currently pressed key
  592. self.modifiers = None
  593. self.x = None # Current mouse cursor pos
  594. self.y = None
  595. # Current snapped mouse pos
  596. self.snap_x = None
  597. self.snap_y = None
  598. self.pos = None
  599. def make_callback(thetool):
  600. def f():
  601. self.on_tool_select(thetool)
  602. return f
  603. for tool in self.tools_exc:
  604. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  605. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  606. self.options = {
  607. "global_gridx": 0.1,
  608. "global_gridy": 0.1,
  609. "snap_max": 0.05,
  610. "grid_snap": True,
  611. "corner_snap": False,
  612. "grid_gap_link": True
  613. }
  614. self.app.options_read_form()
  615. for option in self.options:
  616. if option in self.app.options:
  617. self.options[option] = self.app.options[option]
  618. self.rtree_exc_index = rtindex.Index()
  619. # flag to show if the object was modified
  620. self.is_modified = False
  621. self.edited_obj_name = ""
  622. # variable to store the total amount of drills per job
  623. self.tot_drill_cnt = 0
  624. self.tool_row = 0
  625. # variable to store the total amount of slots per job
  626. self.tot_slot_cnt = 0
  627. self.tool_row_slots = 0
  628. self.tool_row = 0
  629. # store the status of the editor so the Delete at object level will not work until the edit is finished
  630. self.editor_active = False
  631. def entry2option(option, entry):
  632. self.options[option] = float(entry.text())
  633. # store the status of the editor so the Delete at object level will not work until the edit is finished
  634. self.editor_active = False
  635. def pool_recreated(self, pool):
  636. self.shapes.pool = pool
  637. self.tool_shape.pool = pool
  638. @staticmethod
  639. def make_storage():
  640. ## Shape storage.
  641. storage = FlatCAMRTreeStorage()
  642. storage.get_points = DrawToolShape.get_pts
  643. return storage
  644. def set_ui(self):
  645. # updated units
  646. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  647. self.olddia_newdia.clear()
  648. self.tool2tooldia.clear()
  649. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  650. # for key in self.points_edit:
  651. # self.olddia_newdia[key] = key
  652. # sort_temp = []
  653. # for diam in self.olddia_newdia:
  654. # sort_temp.append(float(diam))
  655. # self.sorted_apid = sorted(sort_temp)
  656. #
  657. # # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  658. # for i in range(len(self.sorted_apid)):
  659. # tt_dia = self.sorted_apid[i]
  660. # self.tool2tooldia[i + 1] = tt_dia
  661. def build_ui(self):
  662. try:
  663. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  664. self.apertures_table.itemChanged.disconnect()
  665. except:
  666. pass
  667. # updated units
  668. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  669. # make a new name for the new Excellon object (the one with edited content)
  670. self.edited_obj_name = self.gerber_obj.options['name']
  671. self.name_entry.set_value(self.edited_obj_name)
  672. if self.units == "IN":
  673. self.addtool_entry.set_value(0.039)
  674. else:
  675. self.addtool_entry.set_value(1.00)
  676. self.apertures_row = 0
  677. aper_no = self.apertures_row + 1
  678. sort = []
  679. for k, v in list(self.gerber_obj.apertures.items()):
  680. sort.append(int(k))
  681. sorted_apertures = sorted(sort)
  682. sort = []
  683. for k, v in list(self.gerber_obj.aperture_macros.items()):
  684. sort.append(k)
  685. sorted_macros = sorted(sort)
  686. n = len(sorted_apertures) + len(sorted_macros)
  687. self.apertures_table.setRowCount(n)
  688. for ap_code in sorted_apertures:
  689. ap_code = str(ap_code)
  690. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  691. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  692. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  693. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  694. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  695. ap_type_item = QtWidgets.QTableWidgetItem(str(self.gerber_obj.apertures[ap_code]['type']))
  696. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  697. if str(self.gerber_obj.apertures[ap_code]['type']) == 'R' or str(self.gerber_obj.apertures[ap_code]['type']) == 'O':
  698. ap_dim_item = QtWidgets.QTableWidgetItem(
  699. '%.4f, %.4f' % (self.gerber_obj.apertures[ap_code]['width'] * self.gerber_obj.file_units_factor,
  700. self.gerber_obj.apertures[ap_code]['height'] * self.gerber_obj.file_units_factor
  701. )
  702. )
  703. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  704. elif str(self.gerber_obj.apertures[ap_code]['type']) == 'P':
  705. ap_dim_item = QtWidgets.QTableWidgetItem(
  706. '%.4f, %.4f' % (self.gerber_obj.apertures[ap_code]['diam'] * self.gerber_obj.file_units_factor,
  707. self.gerber_obj.apertures[ap_code]['nVertices'] * self.gerber_obj.file_units_factor)
  708. )
  709. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  710. else:
  711. ap_dim_item = QtWidgets.QTableWidgetItem('')
  712. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  713. try:
  714. if self.gerber_obj.apertures[ap_code]['size'] is not None:
  715. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  716. float(self.gerber_obj.apertures[ap_code]['size'] *
  717. self.gerber_obj.file_units_factor))
  718. else:
  719. ap_size_item = QtWidgets.QTableWidgetItem('')
  720. except KeyError:
  721. ap_size_item = QtWidgets.QTableWidgetItem('')
  722. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  723. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  724. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  725. self.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  726. self.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  727. self.apertures_row += 1
  728. for ap_code in sorted_macros:
  729. ap_code = str(ap_code)
  730. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  731. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  732. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  733. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  734. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  735. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  736. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  737. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  738. self.apertures_row += 1
  739. self.apertures_table.selectColumn(0)
  740. self.apertures_table.resizeColumnsToContents()
  741. self.apertures_table.resizeRowsToContents()
  742. vertical_header = self.apertures_table.verticalHeader()
  743. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  744. vertical_header.hide()
  745. self.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  746. horizontal_header = self.apertures_table.horizontalHeader()
  747. horizontal_header.setMinimumSectionSize(10)
  748. horizontal_header.setDefaultSectionSize(70)
  749. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  750. horizontal_header.resizeSection(0, 20)
  751. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  752. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  753. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  754. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  755. self.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  756. self.apertures_table.setSortingEnabled(False)
  757. self.apertures_table.setMinimumHeight(self.apertures_table.getHeight())
  758. self.apertures_table.setMaximumHeight(self.apertures_table.getHeight())
  759. def on_tool_add(self, tooldia=None):
  760. self.is_modified = True
  761. if tooldia:
  762. tool_dia = tooldia
  763. else:
  764. try:
  765. tool_dia = float(self.addtool_entry.get_value())
  766. except ValueError:
  767. # try to convert comma to decimal point. if it's still not working error message and return
  768. try:
  769. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  770. except ValueError:
  771. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  772. "use a number.")
  773. )
  774. return
  775. if tool_dia not in self.olddia_newdia:
  776. storage_elem = FlatCAMGeoEditor.make_storage()
  777. self.storage_dict[tool_dia] = storage_elem
  778. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  779. # each time a tool diameter is edited or added
  780. self.olddia_newdia[tool_dia] = tool_dia
  781. else:
  782. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  783. "Save and reedit Excellon if you need to add this tool. ")
  784. )
  785. return
  786. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  787. # we add a new entry in the tool2tooldia dict
  788. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  789. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia), units=str(self.units)))
  790. self.build_ui()
  791. # make a quick sort through the tool2tooldia dict so we find which row to select
  792. row_to_be_selected = None
  793. for key in sorted(self.tool2tooldia):
  794. if self.tool2tooldia[key] == tool_dia:
  795. row_to_be_selected = int(key) - 1
  796. break
  797. self.apertures_table.selectRow(row_to_be_selected)
  798. def on_tool_delete(self, dia=None):
  799. self.is_modified = True
  800. deleted_tool_dia_list = []
  801. deleted_tool_offset_list = []
  802. try:
  803. if dia is None or dia is False:
  804. # deleted_tool_dia = float(self.apertures_table.item(self.apertures_table.currentRow(), 1).text())
  805. for index in self.apertures_table.selectionModel().selectedRows():
  806. row = index.row()
  807. deleted_tool_dia_list.append(float(self.apertures_table.item(row, 1).text()))
  808. else:
  809. if isinstance(dia, list):
  810. for dd in dia:
  811. deleted_tool_dia_list.append(float('%.4f' % dd))
  812. else:
  813. deleted_tool_dia_list.append(float('%.4f' % dia))
  814. except:
  815. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  816. return
  817. for deleted_tool_dia in deleted_tool_dia_list:
  818. # delete de tool offset
  819. self.gerber_obj.tool_offset.pop(float(deleted_tool_dia), None)
  820. # delete the storage used for that tool
  821. storage_elem = FlatCAMGeoEditor.make_storage()
  822. self.storage_dict[deleted_tool_dia] = storage_elem
  823. self.storage_dict.pop(deleted_tool_dia, None)
  824. # I've added this flag_del variable because dictionary don't like
  825. # having keys deleted while iterating through them
  826. flag_del = []
  827. # self.points_edit.pop(deleted_tool_dia, None)
  828. for deleted_tool in self.tool2tooldia:
  829. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  830. flag_del.append(deleted_tool)
  831. if flag_del:
  832. for tool_to_be_deleted in flag_del:
  833. # delete the tool
  834. self.tool2tooldia.pop(tool_to_be_deleted, None)
  835. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  836. # number of drills from before was deleter
  837. self.points_edit[deleted_tool_dia] = []
  838. flag_del = []
  839. self.olddia_newdia.pop(deleted_tool_dia, None)
  840. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(del_dia=str(deleted_tool_dia), units=str(self.units)))
  841. self.replot()
  842. # self.app.inform.emit("Could not delete selected tool")
  843. self.build_ui()
  844. def on_tool_edit(self, item_changed):
  845. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  846. self.apertures_table.itemChanged.disconnect()
  847. # self.apertures_table.selectionModel().currentChanged.disconnect()
  848. self.is_modified = True
  849. geometry = []
  850. current_table_dia_edited = None
  851. if self.apertures_table.currentItem() is not None:
  852. try:
  853. current_table_dia_edited = float(self.apertures_table.currentItem().text())
  854. except ValueError as e:
  855. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  856. self.apertures_table.setCurrentItem(None)
  857. return
  858. row_of_item_changed = self.apertures_table.currentRow()
  859. # rows start with 0, tools start with 1 so we adjust the value by 1
  860. key_in_tool2tooldia = row_of_item_changed + 1
  861. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  862. # tool diameter is not used so we create a new tool with the desired diameter
  863. if current_table_dia_edited not in self.olddia_newdia.values():
  864. # update the dict that holds as keys our initial diameters and as values the edited diameters
  865. self.olddia_newdia[dia_changed] = current_table_dia_edited
  866. # update the dict that holds tool_no as key and tool_dia as value
  867. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  868. # update the tool offset
  869. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  870. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  871. self.replot()
  872. else:
  873. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  874. factor = current_table_dia_edited / dia_changed
  875. for shape in self.storage_dict[dia_changed].get_objects():
  876. geometry.append(DrawToolShape(
  877. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  878. self.points_edit[current_table_dia_edited].append((0, 0))
  879. self.add_gerber_shape(geometry, self.storage_dict[current_table_dia_edited])
  880. self.on_tool_delete(dia=dia_changed)
  881. # delete the tool offset
  882. self.gerber_obj.tool_offset.pop(dia_changed, None)
  883. # we reactivate the signals after the after the tool editing
  884. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  885. # self.apertures_table.selectionModel().currentChanged.connect(self.on_row_selected)
  886. def on_name_activate(self):
  887. self.edited_obj_name = self.name_entry.get_value()
  888. def activate(self):
  889. self.connect_canvas_event_handlers()
  890. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  891. self.shapes.enabled = True
  892. self.tool_shape.enabled = True
  893. # self.app.app_cursor.enabled = True
  894. self.app.ui.snap_max_dist_entry.setEnabled(True)
  895. self.app.ui.corner_snap_btn.setEnabled(True)
  896. self.app.ui.snap_magnet.setVisible(True)
  897. self.app.ui.corner_snap_btn.setVisible(True)
  898. self.app.ui.exc_editor_menu.setDisabled(False)
  899. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  900. self.app.ui.update_obj_btn.setEnabled(True)
  901. self.app.ui.e_editor_cmenu.setEnabled(True)
  902. self.app.ui.exc_edit_toolbar.setDisabled(False)
  903. self.app.ui.exc_edit_toolbar.setVisible(True)
  904. # self.app.ui.snap_toolbar.setDisabled(False)
  905. # start with GRID toolbar activated
  906. if self.app.ui.grid_snap_btn.isChecked() is False:
  907. self.app.ui.grid_snap_btn.trigger()
  908. # Tell the App that the editor is active
  909. self.editor_active = True
  910. def deactivate(self):
  911. self.disconnect_canvas_event_handlers()
  912. self.clear()
  913. self.app.ui.exc_edit_toolbar.setDisabled(True)
  914. settings = QSettings("Open Source", "FlatCAM")
  915. if settings.contains("layout"):
  916. layout = settings.value('layout', type=str)
  917. if layout == 'standard':
  918. # self.app.ui.exc_edit_toolbar.setVisible(False)
  919. self.app.ui.snap_max_dist_entry.setEnabled(False)
  920. self.app.ui.corner_snap_btn.setEnabled(False)
  921. self.app.ui.snap_magnet.setVisible(False)
  922. self.app.ui.corner_snap_btn.setVisible(False)
  923. elif layout == 'compact':
  924. # self.app.ui.exc_edit_toolbar.setVisible(True)
  925. self.app.ui.snap_max_dist_entry.setEnabled(False)
  926. self.app.ui.corner_snap_btn.setEnabled(False)
  927. self.app.ui.snap_magnet.setVisible(True)
  928. self.app.ui.corner_snap_btn.setVisible(True)
  929. else:
  930. # self.app.ui.exc_edit_toolbar.setVisible(False)
  931. self.app.ui.snap_max_dist_entry.setEnabled(False)
  932. self.app.ui.corner_snap_btn.setEnabled(False)
  933. self.app.ui.snap_magnet.setVisible(False)
  934. self.app.ui.corner_snap_btn.setVisible(False)
  935. # set the Editor Toolbar visibility to what was before entering in the Editor
  936. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  937. else self.app.ui.exc_edit_toolbar.setVisible(True)
  938. # Disable visuals
  939. self.shapes.enabled = False
  940. self.tool_shape.enabled = False
  941. # self.app.app_cursor.enabled = False
  942. # Tell the app that the editor is no longer active
  943. self.editor_active = False
  944. self.app.ui.exc_editor_menu.setDisabled(True)
  945. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  946. self.app.ui.update_obj_btn.setEnabled(False)
  947. self.app.ui.g_editor_cmenu.setEnabled(False)
  948. self.app.ui.e_editor_cmenu.setEnabled(False)
  949. # Show original geometry
  950. if self.gerber_obj:
  951. self.gerber_obj.visible = True
  952. def connect_canvas_event_handlers(self):
  953. ## Canvas events
  954. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  955. # but those from FlatCAMGeoEditor
  956. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  957. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  958. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  959. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  960. self.app.collection.view.clicked.disconnect()
  961. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  962. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  963. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  964. def disconnect_canvas_event_handlers(self):
  965. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  966. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  967. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  968. # we restore the key and mouse control to FlatCAMApp method
  969. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  970. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  971. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  972. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  973. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  974. def clear(self):
  975. self.active_tool = None
  976. # self.shape_buffer = []
  977. self.selected = []
  978. self.points_edit = {}
  979. self.new_tools = {}
  980. self.new_drills = []
  981. self.storage_dict = {}
  982. self.shapes.clear(update=True)
  983. self.tool_shape.clear(update=True)
  984. # self.storage = FlatCAMExcEditor.make_storage()
  985. self.replot()
  986. def edit_fcgerber(self, exc_obj):
  987. """
  988. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  989. into the editor.
  990. :param fcgeometry: FlatCAMExcellon
  991. :return: None
  992. """
  993. assert isinstance(exc_obj, Gerber), \
  994. "Expected an Excellon Object, got %s" % type(exc_obj)
  995. self.deactivate()
  996. self.activate()
  997. # Hide original geometry
  998. self.gerber_obj = exc_obj
  999. exc_obj.visible = False
  1000. # Set selection tolerance
  1001. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1002. self.select_tool("select")
  1003. self.set_ui()
  1004. # now that we hava data, create the GUI interface and add it to the Tool Tab
  1005. self.build_ui()
  1006. # we activate this after the initial build as we don't need to see the tool been populated
  1007. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1008. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  1009. # and then add it to the storage elements (each storage elements is a member of a list
  1010. for apid in self.gerber_obj.apertures:
  1011. storage_elem = FlatCAMGeoEditor.make_storage()
  1012. for geo in self.gerber_obj.apertures[apid]['solid_geometry']:
  1013. if geo is not None:
  1014. self.add_gerber_shape(DrawToolShape(geo), storage_elem)
  1015. self.storage_dict[apid] = storage_elem
  1016. self.replot()
  1017. # add a first tool in the Tool Table but only if the Excellon Object is empty
  1018. # if not self.tool2tooldia:
  1019. # self.on_tool_add(tooldia=1.00)
  1020. def update_fcgerber(self, exc_obj):
  1021. """
  1022. Create a new Excellon object that contain the edited content of the source Excellon object
  1023. :param exc_obj: FlatCAMExcellon
  1024. :return: None
  1025. """
  1026. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  1027. # the values of this dict are coordinates of the holes (drills)
  1028. edited_points = {}
  1029. for storage_tooldia in self.storage_dict:
  1030. for x in self.storage_dict[storage_tooldia].get_objects():
  1031. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  1032. # each MultiLineString is made out of Linestrings
  1033. # select first Linestring object in the current MultiLineString
  1034. first_linestring = x.geo[0]
  1035. # get it's coordinates
  1036. first_linestring_coords = first_linestring.coords
  1037. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  1038. y_coord = first_linestring_coords[0][1]
  1039. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  1040. # edited_points dictionary
  1041. point = (x_coord, y_coord)
  1042. if not storage_tooldia in edited_points:
  1043. edited_points[storage_tooldia] = [point]
  1044. else:
  1045. edited_points[storage_tooldia].append(point)
  1046. # recreate the drills and tools to be added to the new Excellon edited object
  1047. # first, we look in the tool table if one of the tool diameters was changed then
  1048. # append that a tuple formed by (old_dia, edited_dia) to a list
  1049. changed_key = []
  1050. for initial_dia in self.olddia_newdia:
  1051. edited_dia = self.olddia_newdia[initial_dia]
  1052. if edited_dia != initial_dia:
  1053. for old_dia in edited_points:
  1054. if old_dia == initial_dia:
  1055. changed_key.append((old_dia, edited_dia))
  1056. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  1057. # (and we have to add it)
  1058. # because in case we have drill points it will have to be already added in edited_points
  1059. # if initial_dia not in edited_points.keys():
  1060. # edited_points[initial_dia] = []
  1061. for el in changed_key:
  1062. edited_points[el[1]] = edited_points.pop(el[0])
  1063. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  1064. # ordered_edited_points is a ordered list of tuples;
  1065. # element[0] of the tuple is the diameter and
  1066. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  1067. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  1068. current_tool = 0
  1069. for tool_dia in ordered_edited_points:
  1070. current_tool += 1
  1071. # create the self.tools for the new Excellon object (the one with edited content)
  1072. name = str(current_tool)
  1073. spec = {"C": float(tool_dia[0])}
  1074. self.new_tools[name] = spec
  1075. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  1076. self.new_tools[name]['solid_geometry'] = []
  1077. # create the self.drills for the new Excellon object (the one with edited content)
  1078. for point in tool_dia[1]:
  1079. self.new_drills.append(
  1080. {
  1081. 'point': Point(point),
  1082. 'tool': str(current_tool)
  1083. }
  1084. )
  1085. # repopulate the 'solid_geometry' for each tool
  1086. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  1087. self.new_tools[name]['solid_geometry'].append(poly)
  1088. if self.is_modified is True:
  1089. if "_edit" in self.edited_obj_name:
  1090. try:
  1091. id = int(self.edited_obj_name[-1]) + 1
  1092. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  1093. except ValueError:
  1094. self.edited_obj_name += "_1"
  1095. else:
  1096. self.edited_obj_name += "_edit"
  1097. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  1098. 'params': [self.edited_obj_name]})
  1099. if self.gerber_obj.slots:
  1100. self.new_slots = self.gerber_obj.slots
  1101. self.new_tool_offset = self.gerber_obj.tool_offset
  1102. # reset the tool table
  1103. self.apertures_table.clear()
  1104. self.apertures_table.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1105. self.last_tool_selected = None
  1106. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  1107. self.app.collection.set_active(self.gerber_obj.options['name'])
  1108. self.app.collection.delete_active()
  1109. # restore GUI to the Selected TAB
  1110. # Remove anything else in the GUI
  1111. self.app.ui.tool_scroll_area.takeWidget()
  1112. # Switch notebook to Selected page
  1113. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1114. def update_options(self, obj):
  1115. try:
  1116. if not obj.options:
  1117. obj.options = {}
  1118. obj.options['xmin'] = 0
  1119. obj.options['ymin'] = 0
  1120. obj.options['xmax'] = 0
  1121. obj.options['ymax'] = 0
  1122. return True
  1123. else:
  1124. return False
  1125. except AttributeError:
  1126. obj.options = {}
  1127. return True
  1128. def new_edited_excellon(self, outname):
  1129. """
  1130. Creates a new Excellon object for the edited Excellon. Thread-safe.
  1131. :param outname: Name of the resulting object. None causes the
  1132. name to be that of the file.
  1133. :type outname: str
  1134. :return: None
  1135. """
  1136. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  1137. self.gerber_obj.options['name'])
  1138. # How the object should be initialized
  1139. def obj_init(excellon_obj, app_obj):
  1140. # self.progress.emit(20)
  1141. excellon_obj.drills = self.new_drills
  1142. excellon_obj.tools = self.new_tools
  1143. excellon_obj.slots = self.new_slots
  1144. excellon_obj.tool_offset = self.new_tool_offset
  1145. excellon_obj.options['name'] = outname
  1146. try:
  1147. excellon_obj.create_geometry()
  1148. except KeyError:
  1149. self.app.inform.emit(
  1150. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  1151. )
  1152. except:
  1153. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1154. msg += traceback.format_exc()
  1155. app_obj.inform.emit(msg)
  1156. raise
  1157. # raise
  1158. with self.app.proc_container.new(_("Creating Excellon.")):
  1159. try:
  1160. self.app.new_object("excellon", outname, obj_init)
  1161. except Exception as e:
  1162. log.error("Error on object creation: %s" % str(e))
  1163. self.app.progress.emit(100)
  1164. return
  1165. self.app.inform.emit(_("[success] Excellon editing finished."))
  1166. # self.progress.emit(100)
  1167. def on_tool_select(self, tool):
  1168. """
  1169. Behavior of the toolbar. Tool initialization.
  1170. :rtype : None
  1171. """
  1172. current_tool = tool
  1173. self.app.log.debug("on_tool_select('%s')" % tool)
  1174. if self.last_tool_selected is None and current_tool is not 'select':
  1175. # self.draw_app.select_tool('select')
  1176. self.complete = True
  1177. current_tool = 'select'
  1178. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  1179. # This is to make the group behave as radio group
  1180. if current_tool in self.tools_exc:
  1181. if self.tools_exc[current_tool]["button"].isChecked():
  1182. self.app.log.debug("%s is checked." % current_tool)
  1183. for t in self.tools_exc:
  1184. if t != current_tool:
  1185. self.tools_exc[t]["button"].setChecked(False)
  1186. # this is where the Editor toolbar classes (button's) are instantiated
  1187. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  1188. # self.app.inform.emit(self.active_tool.start_msg)
  1189. else:
  1190. self.app.log.debug("%s is NOT checked." % current_tool)
  1191. for t in self.tools_exc:
  1192. self.tools_exc[t]["button"].setChecked(False)
  1193. self.active_tool = None
  1194. def on_row_selected(self):
  1195. self.selected = []
  1196. try:
  1197. selected_dia = self.tool2tooldia[self.apertures_table.currentRow() + 1]
  1198. self.last_tool_selected = self.apertures_table.currentRow() + 1
  1199. for obj in self.storage_dict[selected_dia].get_objects():
  1200. self.selected.append(obj)
  1201. except Exception as e:
  1202. self.app.log.debug(str(e))
  1203. self.replot()
  1204. def toolbar_tool_toggle(self, key):
  1205. self.options[key] = self.sender().isChecked()
  1206. if self.options[key] == True:
  1207. return 1
  1208. else:
  1209. return 0
  1210. def on_canvas_click(self, event):
  1211. """
  1212. event.x and .y have canvas coordinates
  1213. event.xdaya and .ydata have plot coordinates
  1214. :param event: Event object dispatched by Matplotlib
  1215. :return: None
  1216. """
  1217. if event.button is 1:
  1218. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1219. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  1220. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1221. ### Snap coordinates
  1222. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  1223. self.pos = (x, y)
  1224. # print(self.active_tool)
  1225. # Selection with left mouse button
  1226. if self.active_tool is not None and event.button is 1:
  1227. # Dispatch event to active_tool
  1228. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1229. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  1230. # If it is a shape generating tool
  1231. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  1232. if self.current_storage is not None:
  1233. self.on_exc_shape_complete(self.current_storage)
  1234. self.build_ui()
  1235. # MS: always return to the Select Tool if modifier key is not pressed
  1236. # else return to the current tool
  1237. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1238. if self.app.defaults["global_mselect_key"] == 'Control':
  1239. modifier_to_use = Qt.ControlModifier
  1240. else:
  1241. modifier_to_use = Qt.ShiftModifier
  1242. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1243. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1244. if key_modifier == modifier_to_use:
  1245. self.select_tool(self.active_tool.name)
  1246. else:
  1247. self.select_tool("select")
  1248. return
  1249. if isinstance(self.active_tool, FCApertureSelect):
  1250. # self.app.log.debug("Replotting after click.")
  1251. self.replot()
  1252. else:
  1253. self.app.log.debug("No active tool to respond to click!")
  1254. def on_exc_shape_complete(self, storage):
  1255. self.app.log.debug("on_shape_complete()")
  1256. # Add shape
  1257. if type(storage) is list:
  1258. for item_storage in storage:
  1259. self.add_gerber_shape(self.active_tool.geometry, item_storage)
  1260. else:
  1261. self.add_gerber_shape(self.active_tool.geometry, storage)
  1262. # Remove any utility shapes
  1263. self.delete_utility_geometry()
  1264. self.tool_shape.clear(update=True)
  1265. # Replot and reset tool.
  1266. self.replot()
  1267. # self.active_tool = type(self.active_tool)(self)
  1268. def add_gerber_shape(self, shape, storage):
  1269. """
  1270. Adds a shape to the shape storage.
  1271. :param shape: Shape to be added.
  1272. :type shape: DrawToolShape
  1273. :return: None
  1274. """
  1275. # List of DrawToolShape?
  1276. if isinstance(shape, list):
  1277. for subshape in shape:
  1278. self.add_gerber_shape(subshape, storage)
  1279. return
  1280. assert isinstance(shape, DrawToolShape), \
  1281. "Expected a DrawToolShape, got %s" % str(type(shape))
  1282. assert shape.geo is not None, \
  1283. "Shape object has empty geometry (None)"
  1284. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1285. not isinstance(shape.geo, list), \
  1286. "Shape objects has empty geometry ([])"
  1287. if isinstance(shape, DrawToolUtilityShape):
  1288. self.utility.append(shape)
  1289. else:
  1290. storage.insert(shape) # TODO: Check performance
  1291. def add_shape(self, shape):
  1292. """
  1293. Adds a shape to the shape storage.
  1294. :param shape: Shape to be added.
  1295. :type shape: DrawToolShape
  1296. :return: None
  1297. """
  1298. # List of DrawToolShape?
  1299. if isinstance(shape, list):
  1300. for subshape in shape:
  1301. self.add_shape(subshape)
  1302. return
  1303. assert isinstance(shape, DrawToolShape), \
  1304. "Expected a DrawToolShape, got %s" % type(shape)
  1305. assert shape.geo is not None, \
  1306. "Shape object has empty geometry (None)"
  1307. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1308. not isinstance(shape.geo, list), \
  1309. "Shape objects has empty geometry ([])"
  1310. if isinstance(shape, DrawToolUtilityShape):
  1311. self.utility.append(shape)
  1312. else:
  1313. self.storage.insert(shape) # TODO: Check performance
  1314. def on_canvas_click_release(self, event):
  1315. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  1316. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  1317. if self.app.grid_status():
  1318. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  1319. else:
  1320. pos = (pos_canvas[0], pos_canvas[1])
  1321. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  1322. # canvas menu
  1323. try:
  1324. if event.button == 2: # right click
  1325. if self.app.panning_action is True:
  1326. self.app.panning_action = False
  1327. else:
  1328. self.app.cursor = QtGui.QCursor()
  1329. self.app.ui.popMenu.popup(self.app.cursor.pos())
  1330. except Exception as e:
  1331. log.warning("Error: %s" % str(e))
  1332. raise
  1333. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  1334. # selection and then select a type of selection ("enclosing" or "touching")
  1335. try:
  1336. if event.button == 1: # left click
  1337. if self.app.selection_type is not None:
  1338. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  1339. self.app.selection_type = None
  1340. elif isinstance(self.active_tool, FCApertureSelect):
  1341. # Dispatch event to active_tool
  1342. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1343. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  1344. # self.app.inform.emit(msg)
  1345. self.active_tool.click_release((self.pos[0], self.pos[1]))
  1346. self.replot()
  1347. except Exception as e:
  1348. log.warning("Error: %s" % str(e))
  1349. raise
  1350. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  1351. """
  1352. :param start_pos: mouse position when the selection LMB click was done
  1353. :param end_pos: mouse position when the left mouse button is released
  1354. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1355. :type Bool
  1356. :return:
  1357. """
  1358. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1359. self.app.delete_selection_shape()
  1360. for storage in self.storage_dict:
  1361. for obj in self.storage_dict[storage].get_objects():
  1362. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  1363. (sel_type is False and poly_selection.intersects(obj.geo)):
  1364. if self.key == self.app.defaults["global_mselect_key"]:
  1365. if obj in self.selected:
  1366. self.selected.remove(obj)
  1367. else:
  1368. # add the object to the selected shapes
  1369. self.selected.append(obj)
  1370. else:
  1371. self.selected.append(obj)
  1372. # select the diameter of the selected shape in the tool table
  1373. for storage in self.storage_dict:
  1374. for shape_s in self.selected:
  1375. if shape_s in self.storage_dict[storage].get_objects():
  1376. for key in self.tool2tooldia:
  1377. if self.tool2tooldia[key] == storage:
  1378. item = self.apertures_table.item((key - 1), 1)
  1379. self.apertures_table.setCurrentItem(item)
  1380. self.last_tool_selected = key
  1381. # item.setSelected(True)
  1382. # self.grb_editor_app.apertures_table.selectItem(key - 1)
  1383. self.replot()
  1384. def on_canvas_move(self, event):
  1385. """
  1386. Called on 'mouse_move' event
  1387. event.pos have canvas screen coordinates
  1388. :param event: Event object dispatched by VisPy SceneCavas
  1389. :return: None
  1390. """
  1391. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1392. event.xdata, event.ydata = pos[0], pos[1]
  1393. self.x = event.xdata
  1394. self.y = event.ydata
  1395. # Prevent updates on pan
  1396. # if len(event.buttons) > 0:
  1397. # return
  1398. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  1399. if event.button == 2:
  1400. self.app.panning_action = True
  1401. return
  1402. else:
  1403. self.app.panning_action = False
  1404. try:
  1405. x = float(event.xdata)
  1406. y = float(event.ydata)
  1407. except TypeError:
  1408. return
  1409. if self.active_tool is None:
  1410. return
  1411. ### Snap coordinates
  1412. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  1413. self.snap_x = x
  1414. self.snap_y = y
  1415. # update the position label in the infobar since the APP mouse event handlers are disconnected
  1416. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1417. "<b>Y</b>: %.4f" % (x, y))
  1418. if self.pos is None:
  1419. self.pos = (0, 0)
  1420. dx = x - self.pos[0]
  1421. dy = y - self.pos[1]
  1422. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  1423. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1424. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1425. ### Utility geometry (animated)
  1426. geo = self.active_tool.utility_geometry(data=(x, y))
  1427. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  1428. # Remove any previous utility shape
  1429. self.tool_shape.clear(update=True)
  1430. self.draw_utility_geometry(geo=geo)
  1431. ### Selection area on canvas section ###
  1432. dx = pos[0] - self.pos[0]
  1433. if event.is_dragging == 1 and event.button == 1:
  1434. self.app.delete_selection_shape()
  1435. if dx < 0:
  1436. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  1437. color=self.app.defaults["global_alt_sel_line"],
  1438. face_color=self.app.defaults['global_alt_sel_fill'])
  1439. self.app.selection_type = False
  1440. else:
  1441. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  1442. self.app.selection_type = True
  1443. else:
  1444. self.app.selection_type = None
  1445. # Update cursor
  1446. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  1447. def on_canvas_key_release(self, event):
  1448. self.key = None
  1449. def draw_utility_geometry(self, geo):
  1450. # Add the new utility shape
  1451. try:
  1452. # this case is for the Font Parse
  1453. for el in list(geo.geo):
  1454. if type(el) == MultiPolygon:
  1455. for poly in el:
  1456. self.tool_shape.add(
  1457. shape=poly,
  1458. color=(self.app.defaults["global_draw_color"] + '80'),
  1459. update=False,
  1460. layer=0,
  1461. tolerance=None
  1462. )
  1463. elif type(el) == MultiLineString:
  1464. for linestring in el:
  1465. self.tool_shape.add(
  1466. shape=linestring,
  1467. color=(self.app.defaults["global_draw_color"] + '80'),
  1468. update=False,
  1469. layer=0,
  1470. tolerance=None
  1471. )
  1472. else:
  1473. self.tool_shape.add(
  1474. shape=el,
  1475. color=(self.app.defaults["global_draw_color"] + '80'),
  1476. update=False,
  1477. layer=0,
  1478. tolerance=None
  1479. )
  1480. except TypeError:
  1481. self.tool_shape.add(
  1482. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  1483. update=False, layer=0, tolerance=None)
  1484. self.tool_shape.redraw()
  1485. def replot(self):
  1486. self.plot_all()
  1487. def plot_all(self):
  1488. """
  1489. Plots all shapes in the editor.
  1490. :return: None
  1491. :rtype: None
  1492. """
  1493. # self.app.log.debug("plot_all()")
  1494. self.shapes.clear(update=True)
  1495. for storage in self.storage_dict:
  1496. for shape_plus in self.storage_dict[storage].get_objects():
  1497. if shape_plus.geo is None:
  1498. continue
  1499. if shape_plus in self.selected:
  1500. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  1501. linewidth=2)
  1502. continue
  1503. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  1504. # for shape in self.storage.get_objects():
  1505. # if shape.geo is None: # TODO: This shouldn't have happened
  1506. # continue
  1507. #
  1508. # if shape in self.selected:
  1509. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  1510. # continue
  1511. #
  1512. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  1513. for shape in self.utility:
  1514. self.plot_shape(geometry=shape.geo, linewidth=1)
  1515. continue
  1516. self.shapes.redraw()
  1517. def plot_shape(self, geometry=None, color='black', linewidth=1):
  1518. """
  1519. Plots a geometric object or list of objects without rendering. Plotted objects
  1520. are returned as a list. This allows for efficient/animated rendering.
  1521. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  1522. :param color: Shape color
  1523. :param linewidth: Width of lines in # of pixels.
  1524. :return: List of plotted elements.
  1525. """
  1526. plot_elements = []
  1527. if geometry is None:
  1528. geometry = self.active_tool.geometry
  1529. try:
  1530. for geo in geometry:
  1531. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  1532. ## Non-iterable
  1533. except TypeError:
  1534. ## DrawToolShape
  1535. if isinstance(geometry, DrawToolShape):
  1536. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  1537. ## Polygon: Descend into exterior and each interior.
  1538. if type(geometry) == Polygon:
  1539. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  1540. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  1541. if type(geometry) == LineString or type(geometry) == LinearRing:
  1542. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  1543. if type(geometry) == Point:
  1544. pass
  1545. return plot_elements
  1546. def on_shape_complete(self):
  1547. self.app.log.debug("on_shape_complete()")
  1548. # Add shape
  1549. self.add_shape(self.active_tool.geometry)
  1550. # Remove any utility shapes
  1551. self.delete_utility_geometry()
  1552. self.tool_shape.clear(update=True)
  1553. # Replot and reset tool.
  1554. self.replot()
  1555. # self.active_tool = type(self.active_tool)(self)
  1556. def get_selected(self):
  1557. """
  1558. Returns list of shapes that are selected in the editor.
  1559. :return: List of shapes.
  1560. """
  1561. # return [shape for shape in self.shape_buffer if shape["selected"]]
  1562. return self.selected
  1563. def delete_selected(self):
  1564. temp_ref = [s for s in self.selected]
  1565. for shape_sel in temp_ref:
  1566. self.delete_shape(shape_sel)
  1567. self.selected = []
  1568. self.build_ui()
  1569. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  1570. def delete_shape(self, shape):
  1571. self.is_modified = True
  1572. if shape in self.utility:
  1573. self.utility.remove(shape)
  1574. return
  1575. for storage in self.storage_dict:
  1576. # try:
  1577. # self.storage_dict[storage].remove(shape)
  1578. # except:
  1579. # pass
  1580. if shape in self.storage_dict[storage].get_objects():
  1581. self.storage_dict[storage].remove(shape)
  1582. # a hack to make the tool_table display less drills per diameter
  1583. # self.points_edit it's only useful first time when we load the data into the storage
  1584. # but is still used as referecen when building tool_table in self.build_ui()
  1585. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  1586. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  1587. del self.points_edit[storage][0]
  1588. if shape in self.selected:
  1589. self.selected.remove(shape) # TODO: Check performance
  1590. def delete_utility_geometry(self):
  1591. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  1592. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  1593. for_deletion = [shape for shape in self.utility]
  1594. for shape in for_deletion:
  1595. self.delete_shape(shape)
  1596. self.tool_shape.clear(update=True)
  1597. self.tool_shape.redraw()
  1598. def on_delete_btn(self):
  1599. self.delete_selected()
  1600. self.replot()
  1601. def select_tool(self, toolname):
  1602. """
  1603. Selects a drawing tool. Impacts the object and GUI.
  1604. :param toolname: Name of the tool.
  1605. :return: None
  1606. """
  1607. self.tools_exc[toolname]["button"].setChecked(True)
  1608. self.on_tool_select(toolname)
  1609. def set_selected(self, shape):
  1610. # Remove and add to the end.
  1611. if shape in self.selected:
  1612. self.selected.remove(shape)
  1613. self.selected.append(shape)
  1614. def set_unselected(self, shape):
  1615. if shape in self.selected:
  1616. self.selected.remove(shape)
  1617. def on_array_type_combo(self):
  1618. if self.array_type_combo.currentIndex() == 0:
  1619. self.array_circular_frame.hide()
  1620. self.array_linear_frame.show()
  1621. else:
  1622. self.delete_utility_geometry()
  1623. self.array_circular_frame.show()
  1624. self.array_linear_frame.hide()
  1625. self.app.inform.emit(_("Click on the circular array Center position"))
  1626. def on_linear_angle_radio(self):
  1627. val = self.drill_axis_radio.get_value()
  1628. if val == 'A':
  1629. self.linear_angle_spinner.show()
  1630. self.linear_angle_label.show()
  1631. else:
  1632. self.linear_angle_spinner.hide()
  1633. self.linear_angle_label.hide()
  1634. def exc_add_drill(self):
  1635. self.select_tool('add')
  1636. return
  1637. def exc_add_drill_array(self):
  1638. self.select_tool('add_array')
  1639. return
  1640. def exc_resize_drills(self):
  1641. self.select_tool('resize')
  1642. return
  1643. def exc_copy_drills(self):
  1644. self.select_tool('copy')
  1645. return
  1646. def exc_move_drills(self):
  1647. self.select_tool('move')
  1648. return