FlatCAMGrbEditor.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  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.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.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.tools_table_exc.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_diameters =[]
  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. # build the self.points_edit dict {dimaters: [point_list]}
  650. for drill in self.gerber_obj.drills:
  651. if drill['tool'] in self.gerber_obj.tools:
  652. if self.units == 'IN':
  653. tool_dia = float('%.3f' % self.gerber_obj.tools[drill['tool']]['C'])
  654. else:
  655. tool_dia = float('%.2f' % self.gerber_obj.tools[drill['tool']]['C'])
  656. try:
  657. self.points_edit[tool_dia].append(drill['point'])
  658. except KeyError:
  659. self.points_edit[tool_dia] = [drill['point']]
  660. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  661. for key in self.points_edit:
  662. self.olddia_newdia[key] = key
  663. sort_temp = []
  664. for diam in self.olddia_newdia:
  665. sort_temp.append(float(diam))
  666. self.sorted_diameters = sorted(sort_temp)
  667. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  668. for i in range(len(self.sorted_diameters)):
  669. tt_dia = self.sorted_diameters[i]
  670. self.tool2tooldia[i + 1] = tt_dia
  671. def build_ui(self):
  672. try:
  673. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  674. self.tools_table_exc.itemChanged.disconnect()
  675. except:
  676. pass
  677. # updated units
  678. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  679. # make a new name for the new Excellon object (the one with edited content)
  680. self.edited_obj_name = self.gerber_obj.options['name']
  681. self.name_entry.set_value(self.edited_obj_name)
  682. if self.units == "IN":
  683. self.addtool_entry.set_value(0.039)
  684. else:
  685. self.addtool_entry.set_value(1.00)
  686. sort_temp = []
  687. for diam in self.olddia_newdia:
  688. sort_temp.append(float(diam))
  689. self.sorted_diameters = sorted(sort_temp)
  690. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  691. n = len(self.sorted_diameters)
  692. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  693. self.tools_table_exc.setRowCount(n + 2)
  694. self.tot_drill_cnt = 0
  695. self.tot_slot_cnt = 0
  696. self.tool_row = 0
  697. # this variable will serve as the real tool_number
  698. tool_id = 0
  699. for tool_no in self.sorted_diameters:
  700. tool_id += 1
  701. drill_cnt = 0 # variable to store the nr of drills per tool
  702. slot_cnt = 0 # variable to store the nr of slots per tool
  703. # Find no of drills for the current tool
  704. for tool_dia in self.points_edit:
  705. if float(tool_dia) == tool_no:
  706. drill_cnt = len(self.points_edit[tool_dia])
  707. self.tot_drill_cnt += drill_cnt
  708. try:
  709. # Find no of slots for the current tool
  710. for slot in self.slots:
  711. if slot['tool'] == tool_no:
  712. slot_cnt += 1
  713. self.tot_slot_cnt += slot_cnt
  714. except AttributeError:
  715. # log.debug("No slots in the Excellon file")
  716. # slot editing not implemented
  717. pass
  718. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  719. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  720. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  721. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  722. # There are no drill bits in MM with more than 3 decimals diameter
  723. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  724. if self.units == 'MM':
  725. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  726. else:
  727. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  728. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  729. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  730. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  731. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  732. if slot_cnt > 0:
  733. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  734. else:
  735. slot_count = QtWidgets.QTableWidgetItem('')
  736. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  737. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  738. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  739. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  740. self.tool_row += 1
  741. # make the diameter column editable
  742. for row in range(self.tool_row):
  743. self.tools_table_exc.item(row, 1).setFlags(
  744. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  745. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  746. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  747. # add a last row with the Total number of drills
  748. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  749. # it will have to have the foreground color (font color) white
  750. empty = QtWidgets.QTableWidgetItem('9998')
  751. empty.setForeground(QtGui.QColor(255, 255, 255))
  752. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  753. empty_b = QtWidgets.QTableWidgetItem('')
  754. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  755. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  756. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  757. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  758. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  759. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  760. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  761. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  762. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  763. font = QtGui.QFont()
  764. font.setBold(True)
  765. font.setWeight(75)
  766. for k in [1, 2]:
  767. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  768. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  769. self.tool_row += 1
  770. # add a last row with the Total number of slots
  771. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  772. # it will have to have the foreground color (font color) white
  773. empty_2 = QtWidgets.QTableWidgetItem('9999')
  774. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  775. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  776. empty_3 = QtWidgets.QTableWidgetItem('')
  777. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  778. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  779. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  780. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  781. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  782. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  783. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  784. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  785. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  786. for kl in [1, 2, 3]:
  787. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  788. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  789. # all the tools are selected by default
  790. self.tools_table_exc.selectColumn(0)
  791. #
  792. self.tools_table_exc.resizeColumnsToContents()
  793. self.tools_table_exc.resizeRowsToContents()
  794. vertical_header = self.tools_table_exc.verticalHeader()
  795. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  796. vertical_header.hide()
  797. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  798. horizontal_header = self.tools_table_exc.horizontalHeader()
  799. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  800. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  801. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  802. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  803. # horizontal_header.setStretchLastSection(True)
  804. # self.tools_table_exc.setSortingEnabled(True)
  805. # sort by tool diameter
  806. self.tools_table_exc.sortItems(1)
  807. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  808. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  809. # use them
  810. self.tool2tooldia.clear()
  811. for row in range(self.tools_table_exc.rowCount() - 2):
  812. tool = int(self.tools_table_exc.item(row, 0).text())
  813. diameter = float(self.tools_table_exc.item(row, 1).text())
  814. self.tool2tooldia[tool] = diameter
  815. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  816. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  817. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  818. self.tools_table_exc.clearSelection()
  819. # Remove anything else in the GUI Selected Tab
  820. self.app.ui.selected_scroll_area.takeWidget()
  821. # Put ourself in the GUI Selected Tab
  822. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  823. # Switch notebook to Selected page
  824. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  825. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  826. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  827. def on_tool_add(self, tooldia=None):
  828. self.is_modified = True
  829. if tooldia:
  830. tool_dia = tooldia
  831. else:
  832. try:
  833. tool_dia = float(self.addtool_entry.get_value())
  834. except ValueError:
  835. # try to convert comma to decimal point. if it's still not working error message and return
  836. try:
  837. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  838. except ValueError:
  839. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  840. "use a number.")
  841. )
  842. return
  843. if tool_dia not in self.olddia_newdia:
  844. storage_elem = FlatCAMGeoEditor.make_storage()
  845. self.storage_dict[tool_dia] = storage_elem
  846. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  847. # each time a tool diameter is edited or added
  848. self.olddia_newdia[tool_dia] = tool_dia
  849. else:
  850. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  851. "Save and reedit Excellon if you need to add this tool. ")
  852. )
  853. return
  854. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  855. # we add a new entry in the tool2tooldia dict
  856. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  857. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia), units=str(self.units)))
  858. self.build_ui()
  859. # make a quick sort through the tool2tooldia dict so we find which row to select
  860. row_to_be_selected = None
  861. for key in sorted(self.tool2tooldia):
  862. if self.tool2tooldia[key] == tool_dia:
  863. row_to_be_selected = int(key) - 1
  864. break
  865. self.tools_table_exc.selectRow(row_to_be_selected)
  866. def on_tool_delete(self, dia=None):
  867. self.is_modified = True
  868. deleted_tool_dia_list = []
  869. deleted_tool_offset_list = []
  870. try:
  871. if dia is None or dia is False:
  872. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  873. for index in self.tools_table_exc.selectionModel().selectedRows():
  874. row = index.row()
  875. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  876. else:
  877. if isinstance(dia, list):
  878. for dd in dia:
  879. deleted_tool_dia_list.append(float('%.4f' % dd))
  880. else:
  881. deleted_tool_dia_list.append(float('%.4f' % dia))
  882. except:
  883. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  884. return
  885. for deleted_tool_dia in deleted_tool_dia_list:
  886. # delete de tool offset
  887. self.gerber_obj.tool_offset.pop(float(deleted_tool_dia), None)
  888. # delete the storage used for that tool
  889. storage_elem = FlatCAMGeoEditor.make_storage()
  890. self.storage_dict[deleted_tool_dia] = storage_elem
  891. self.storage_dict.pop(deleted_tool_dia, None)
  892. # I've added this flag_del variable because dictionary don't like
  893. # having keys deleted while iterating through them
  894. flag_del = []
  895. # self.points_edit.pop(deleted_tool_dia, None)
  896. for deleted_tool in self.tool2tooldia:
  897. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  898. flag_del.append(deleted_tool)
  899. if flag_del:
  900. for tool_to_be_deleted in flag_del:
  901. # delete the tool
  902. self.tool2tooldia.pop(tool_to_be_deleted, None)
  903. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  904. # number of drills from before was deleter
  905. self.points_edit[deleted_tool_dia] = []
  906. flag_del = []
  907. self.olddia_newdia.pop(deleted_tool_dia, None)
  908. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(del_dia=str(deleted_tool_dia), units=str(self.units)))
  909. self.replot()
  910. # self.app.inform.emit("Could not delete selected tool")
  911. self.build_ui()
  912. def on_tool_edit(self, item_changed):
  913. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  914. self.tools_table_exc.itemChanged.disconnect()
  915. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  916. self.is_modified = True
  917. geometry = []
  918. current_table_dia_edited = None
  919. if self.tools_table_exc.currentItem() is not None:
  920. try:
  921. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  922. except ValueError as e:
  923. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  924. self.tools_table_exc.setCurrentItem(None)
  925. return
  926. row_of_item_changed = self.tools_table_exc.currentRow()
  927. # rows start with 0, tools start with 1 so we adjust the value by 1
  928. key_in_tool2tooldia = row_of_item_changed + 1
  929. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  930. # tool diameter is not used so we create a new tool with the desired diameter
  931. if current_table_dia_edited not in self.olddia_newdia.values():
  932. # update the dict that holds as keys our initial diameters and as values the edited diameters
  933. self.olddia_newdia[dia_changed] = current_table_dia_edited
  934. # update the dict that holds tool_no as key and tool_dia as value
  935. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  936. # update the tool offset
  937. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  938. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  939. self.replot()
  940. else:
  941. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  942. factor = current_table_dia_edited / dia_changed
  943. for shape in self.storage_dict[dia_changed].get_objects():
  944. geometry.append(DrawToolShape(
  945. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  946. self.points_edit[current_table_dia_edited].append((0, 0))
  947. self.add_exc_shape(geometry, self.storage_dict[current_table_dia_edited])
  948. self.on_tool_delete(dia=dia_changed)
  949. # delete the tool offset
  950. self.gerber_obj.tool_offset.pop(dia_changed, None)
  951. # we reactivate the signals after the after the tool editing
  952. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  953. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  954. def on_name_activate(self):
  955. self.edited_obj_name = self.name_entry.get_value()
  956. def activate(self):
  957. self.connect_canvas_event_handlers()
  958. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  959. self.shapes.enabled = True
  960. self.tool_shape.enabled = True
  961. # self.app.app_cursor.enabled = True
  962. self.app.ui.snap_max_dist_entry.setEnabled(True)
  963. self.app.ui.corner_snap_btn.setEnabled(True)
  964. self.app.ui.snap_magnet.setVisible(True)
  965. self.app.ui.corner_snap_btn.setVisible(True)
  966. self.app.ui.exc_editor_menu.setDisabled(False)
  967. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  968. self.app.ui.update_obj_btn.setEnabled(True)
  969. self.app.ui.e_editor_cmenu.setEnabled(True)
  970. self.app.ui.exc_edit_toolbar.setDisabled(False)
  971. self.app.ui.exc_edit_toolbar.setVisible(True)
  972. # self.app.ui.snap_toolbar.setDisabled(False)
  973. # start with GRID toolbar activated
  974. if self.app.ui.grid_snap_btn.isChecked() is False:
  975. self.app.ui.grid_snap_btn.trigger()
  976. # Tell the App that the editor is active
  977. self.editor_active = True
  978. def deactivate(self):
  979. self.disconnect_canvas_event_handlers()
  980. self.clear()
  981. self.app.ui.exc_edit_toolbar.setDisabled(True)
  982. settings = QSettings("Open Source", "FlatCAM")
  983. if settings.contains("layout"):
  984. layout = settings.value('layout', type=str)
  985. if layout == 'standard':
  986. # self.app.ui.exc_edit_toolbar.setVisible(False)
  987. self.app.ui.snap_max_dist_entry.setEnabled(False)
  988. self.app.ui.corner_snap_btn.setEnabled(False)
  989. self.app.ui.snap_magnet.setVisible(False)
  990. self.app.ui.corner_snap_btn.setVisible(False)
  991. elif layout == 'compact':
  992. # self.app.ui.exc_edit_toolbar.setVisible(True)
  993. self.app.ui.snap_max_dist_entry.setEnabled(False)
  994. self.app.ui.corner_snap_btn.setEnabled(False)
  995. self.app.ui.snap_magnet.setVisible(True)
  996. self.app.ui.corner_snap_btn.setVisible(True)
  997. else:
  998. # self.app.ui.exc_edit_toolbar.setVisible(False)
  999. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1000. self.app.ui.corner_snap_btn.setEnabled(False)
  1001. self.app.ui.snap_magnet.setVisible(False)
  1002. self.app.ui.corner_snap_btn.setVisible(False)
  1003. # set the Editor Toolbar visibility to what was before entering in the Editor
  1004. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1005. else self.app.ui.exc_edit_toolbar.setVisible(True)
  1006. # Disable visuals
  1007. self.shapes.enabled = False
  1008. self.tool_shape.enabled = False
  1009. # self.app.app_cursor.enabled = False
  1010. # Tell the app that the editor is no longer active
  1011. self.editor_active = False
  1012. self.app.ui.exc_editor_menu.setDisabled(True)
  1013. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  1014. self.app.ui.update_obj_btn.setEnabled(False)
  1015. self.app.ui.g_editor_cmenu.setEnabled(False)
  1016. self.app.ui.e_editor_cmenu.setEnabled(False)
  1017. # Show original geometry
  1018. if self.gerber_obj:
  1019. self.gerber_obj.visible = True
  1020. def connect_canvas_event_handlers(self):
  1021. ## Canvas events
  1022. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1023. # but those from FlatCAMGeoEditor
  1024. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1025. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1026. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1027. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1028. self.app.collection.view.clicked.disconnect()
  1029. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1030. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1031. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  1032. def disconnect_canvas_event_handlers(self):
  1033. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1034. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1035. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  1036. # we restore the key and mouse control to FlatCAMApp method
  1037. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1038. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1039. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1040. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1041. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1042. def clear(self):
  1043. self.active_tool = None
  1044. # self.shape_buffer = []
  1045. self.selected = []
  1046. self.points_edit = {}
  1047. self.new_tools = {}
  1048. self.new_drills = []
  1049. self.storage_dict = {}
  1050. self.shapes.clear(update=True)
  1051. self.tool_shape.clear(update=True)
  1052. # self.storage = FlatCAMExcEditor.make_storage()
  1053. self.replot()
  1054. def edit_fcgerber(self, exc_obj):
  1055. """
  1056. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  1057. into the editor.
  1058. :param fcgeometry: FlatCAMExcellon
  1059. :return: None
  1060. """
  1061. assert isinstance(exc_obj, Excellon), \
  1062. "Expected an Excellon Object, got %s" % type(exc_obj)
  1063. self.deactivate()
  1064. self.activate()
  1065. # Hide original geometry
  1066. self.gerber_obj = exc_obj
  1067. exc_obj.visible = False
  1068. # Set selection tolerance
  1069. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1070. self.select_tool("select")
  1071. self.set_ui()
  1072. # now that we hava data, create the GUI interface and add it to the Tool Tab
  1073. self.build_ui()
  1074. # we activate this after the initial build as we don't need to see the tool been populated
  1075. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1076. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  1077. # and then add it to the storage elements (each storage elements is a member of a list
  1078. for tool_dia in self.points_edit:
  1079. storage_elem = FlatCAMGeoEditor.make_storage()
  1080. for point in self.points_edit[tool_dia]:
  1081. # make a '+' sign, the line length is the tool diameter
  1082. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  1083. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  1084. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  1085. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  1086. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  1087. if shape is not None:
  1088. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  1089. self.storage_dict[tool_dia] = storage_elem
  1090. self.replot()
  1091. # add a first tool in the Tool Table but only if the Excellon Object is empty
  1092. if not self.tool2tooldia:
  1093. self.on_tool_add(tooldia=1.00)
  1094. def update_fcgerber(self, exc_obj):
  1095. """
  1096. Create a new Excellon object that contain the edited content of the source Excellon object
  1097. :param exc_obj: FlatCAMExcellon
  1098. :return: None
  1099. """
  1100. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  1101. # the values of this dict are coordinates of the holes (drills)
  1102. edited_points = {}
  1103. for storage_tooldia in self.storage_dict:
  1104. for x in self.storage_dict[storage_tooldia].get_objects():
  1105. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  1106. # each MultiLineString is made out of Linestrings
  1107. # select first Linestring object in the current MultiLineString
  1108. first_linestring = x.geo[0]
  1109. # get it's coordinates
  1110. first_linestring_coords = first_linestring.coords
  1111. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  1112. y_coord = first_linestring_coords[0][1]
  1113. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  1114. # edited_points dictionary
  1115. point = (x_coord, y_coord)
  1116. if not storage_tooldia in edited_points:
  1117. edited_points[storage_tooldia] = [point]
  1118. else:
  1119. edited_points[storage_tooldia].append(point)
  1120. # recreate the drills and tools to be added to the new Excellon edited object
  1121. # first, we look in the tool table if one of the tool diameters was changed then
  1122. # append that a tuple formed by (old_dia, edited_dia) to a list
  1123. changed_key = []
  1124. for initial_dia in self.olddia_newdia:
  1125. edited_dia = self.olddia_newdia[initial_dia]
  1126. if edited_dia != initial_dia:
  1127. for old_dia in edited_points:
  1128. if old_dia == initial_dia:
  1129. changed_key.append((old_dia, edited_dia))
  1130. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  1131. # (and we have to add it)
  1132. # because in case we have drill points it will have to be already added in edited_points
  1133. # if initial_dia not in edited_points.keys():
  1134. # edited_points[initial_dia] = []
  1135. for el in changed_key:
  1136. edited_points[el[1]] = edited_points.pop(el[0])
  1137. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  1138. # ordered_edited_points is a ordered list of tuples;
  1139. # element[0] of the tuple is the diameter and
  1140. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  1141. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  1142. current_tool = 0
  1143. for tool_dia in ordered_edited_points:
  1144. current_tool += 1
  1145. # create the self.tools for the new Excellon object (the one with edited content)
  1146. name = str(current_tool)
  1147. spec = {"C": float(tool_dia[0])}
  1148. self.new_tools[name] = spec
  1149. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  1150. self.new_tools[name]['solid_geometry'] = []
  1151. # create the self.drills for the new Excellon object (the one with edited content)
  1152. for point in tool_dia[1]:
  1153. self.new_drills.append(
  1154. {
  1155. 'point': Point(point),
  1156. 'tool': str(current_tool)
  1157. }
  1158. )
  1159. # repopulate the 'solid_geometry' for each tool
  1160. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  1161. self.new_tools[name]['solid_geometry'].append(poly)
  1162. if self.is_modified is True:
  1163. if "_edit" in self.edited_obj_name:
  1164. try:
  1165. id = int(self.edited_obj_name[-1]) + 1
  1166. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  1167. except ValueError:
  1168. self.edited_obj_name += "_1"
  1169. else:
  1170. self.edited_obj_name += "_edit"
  1171. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  1172. 'params': [self.edited_obj_name]})
  1173. if self.gerber_obj.slots:
  1174. self.new_slots = self.gerber_obj.slots
  1175. self.new_tool_offset = self.gerber_obj.tool_offset
  1176. # reset the tool table
  1177. self.tools_table_exc.clear()
  1178. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1179. self.last_tool_selected = None
  1180. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  1181. self.app.collection.set_active(self.gerber_obj.options['name'])
  1182. self.app.collection.delete_active()
  1183. # restore GUI to the Selected TAB
  1184. # Remove anything else in the GUI
  1185. self.app.ui.tool_scroll_area.takeWidget()
  1186. # Switch notebook to Selected page
  1187. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1188. def update_options(self, obj):
  1189. try:
  1190. if not obj.options:
  1191. obj.options = {}
  1192. obj.options['xmin'] = 0
  1193. obj.options['ymin'] = 0
  1194. obj.options['xmax'] = 0
  1195. obj.options['ymax'] = 0
  1196. return True
  1197. else:
  1198. return False
  1199. except AttributeError:
  1200. obj.options = {}
  1201. return True
  1202. def new_edited_excellon(self, outname):
  1203. """
  1204. Creates a new Excellon object for the edited Excellon. Thread-safe.
  1205. :param outname: Name of the resulting object. None causes the
  1206. name to be that of the file.
  1207. :type outname: str
  1208. :return: None
  1209. """
  1210. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  1211. self.gerber_obj.options['name'])
  1212. # How the object should be initialized
  1213. def obj_init(excellon_obj, app_obj):
  1214. # self.progress.emit(20)
  1215. excellon_obj.drills = self.new_drills
  1216. excellon_obj.tools = self.new_tools
  1217. excellon_obj.slots = self.new_slots
  1218. excellon_obj.tool_offset = self.new_tool_offset
  1219. excellon_obj.options['name'] = outname
  1220. try:
  1221. excellon_obj.create_geometry()
  1222. except KeyError:
  1223. self.app.inform.emit(
  1224. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  1225. )
  1226. except:
  1227. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1228. msg += traceback.format_exc()
  1229. app_obj.inform.emit(msg)
  1230. raise
  1231. # raise
  1232. with self.app.proc_container.new(_("Creating Excellon.")):
  1233. try:
  1234. self.app.new_object("excellon", outname, obj_init)
  1235. except Exception as e:
  1236. log.error("Error on object creation: %s" % str(e))
  1237. self.app.progress.emit(100)
  1238. return
  1239. self.app.inform.emit(_("[success] Excellon editing finished."))
  1240. # self.progress.emit(100)
  1241. def on_tool_select(self, tool):
  1242. """
  1243. Behavior of the toolbar. Tool initialization.
  1244. :rtype : None
  1245. """
  1246. current_tool = tool
  1247. self.app.log.debug("on_tool_select('%s')" % tool)
  1248. if self.last_tool_selected is None and current_tool is not 'select':
  1249. # self.draw_app.select_tool('select')
  1250. self.complete = True
  1251. current_tool = 'select'
  1252. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  1253. # This is to make the group behave as radio group
  1254. if current_tool in self.tools_exc:
  1255. if self.tools_exc[current_tool]["button"].isChecked():
  1256. self.app.log.debug("%s is checked." % current_tool)
  1257. for t in self.tools_exc:
  1258. if t != current_tool:
  1259. self.tools_exc[t]["button"].setChecked(False)
  1260. # this is where the Editor toolbar classes (button's) are instantiated
  1261. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  1262. # self.app.inform.emit(self.active_tool.start_msg)
  1263. else:
  1264. self.app.log.debug("%s is NOT checked." % current_tool)
  1265. for t in self.tools_exc:
  1266. self.tools_exc[t]["button"].setChecked(False)
  1267. self.active_tool = None
  1268. def on_row_selected(self):
  1269. self.selected = []
  1270. try:
  1271. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  1272. self.last_tool_selected = self.tools_table_exc.currentRow() + 1
  1273. for obj in self.storage_dict[selected_dia].get_objects():
  1274. self.selected.append(obj)
  1275. except Exception as e:
  1276. self.app.log.debug(str(e))
  1277. self.replot()
  1278. def toolbar_tool_toggle(self, key):
  1279. self.options[key] = self.sender().isChecked()
  1280. if self.options[key] == True:
  1281. return 1
  1282. else:
  1283. return 0
  1284. def on_canvas_click(self, event):
  1285. """
  1286. event.x and .y have canvas coordinates
  1287. event.xdaya and .ydata have plot coordinates
  1288. :param event: Event object dispatched by Matplotlib
  1289. :return: None
  1290. """
  1291. if event.button is 1:
  1292. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1293. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  1294. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1295. ### Snap coordinates
  1296. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  1297. self.pos = (x, y)
  1298. # print(self.active_tool)
  1299. # Selection with left mouse button
  1300. if self.active_tool is not None and event.button is 1:
  1301. # Dispatch event to active_tool
  1302. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1303. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  1304. # If it is a shape generating tool
  1305. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  1306. if self.current_storage is not None:
  1307. self.on_exc_shape_complete(self.current_storage)
  1308. self.build_ui()
  1309. # MS: always return to the Select Tool if modifier key is not pressed
  1310. # else return to the current tool
  1311. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1312. if self.app.defaults["global_mselect_key"] == 'Control':
  1313. modifier_to_use = Qt.ControlModifier
  1314. else:
  1315. modifier_to_use = Qt.ShiftModifier
  1316. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1317. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1318. if key_modifier == modifier_to_use:
  1319. self.select_tool(self.active_tool.name)
  1320. else:
  1321. self.select_tool("select")
  1322. return
  1323. if isinstance(self.active_tool, FCApertureSelect):
  1324. # self.app.log.debug("Replotting after click.")
  1325. self.replot()
  1326. else:
  1327. self.app.log.debug("No active tool to respond to click!")
  1328. def on_exc_shape_complete(self, storage):
  1329. self.app.log.debug("on_shape_complete()")
  1330. # Add shape
  1331. if type(storage) is list:
  1332. for item_storage in storage:
  1333. self.add_exc_shape(self.active_tool.geometry, item_storage)
  1334. else:
  1335. self.add_exc_shape(self.active_tool.geometry, storage)
  1336. # Remove any utility shapes
  1337. self.delete_utility_geometry()
  1338. self.tool_shape.clear(update=True)
  1339. # Replot and reset tool.
  1340. self.replot()
  1341. # self.active_tool = type(self.active_tool)(self)
  1342. def add_exc_shape(self, shape, storage):
  1343. """
  1344. Adds a shape to the shape storage.
  1345. :param shape: Shape to be added.
  1346. :type shape: DrawToolShape
  1347. :return: None
  1348. """
  1349. # List of DrawToolShape?
  1350. if isinstance(shape, list):
  1351. for subshape in shape:
  1352. self.add_exc_shape(subshape, storage)
  1353. return
  1354. assert isinstance(shape, DrawToolShape), \
  1355. "Expected a DrawToolShape, got %s" % str(type(shape))
  1356. assert shape.geo is not None, \
  1357. "Shape object has empty geometry (None)"
  1358. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1359. not isinstance(shape.geo, list), \
  1360. "Shape objects has empty geometry ([])"
  1361. if isinstance(shape, DrawToolUtilityShape):
  1362. self.utility.append(shape)
  1363. else:
  1364. storage.insert(shape) # TODO: Check performance
  1365. def add_shape(self, shape):
  1366. """
  1367. Adds a shape to the shape storage.
  1368. :param shape: Shape to be added.
  1369. :type shape: DrawToolShape
  1370. :return: None
  1371. """
  1372. # List of DrawToolShape?
  1373. if isinstance(shape, list):
  1374. for subshape in shape:
  1375. self.add_shape(subshape)
  1376. return
  1377. assert isinstance(shape, DrawToolShape), \
  1378. "Expected a DrawToolShape, got %s" % type(shape)
  1379. assert shape.geo is not None, \
  1380. "Shape object has empty geometry (None)"
  1381. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1382. not isinstance(shape.geo, list), \
  1383. "Shape objects has empty geometry ([])"
  1384. if isinstance(shape, DrawToolUtilityShape):
  1385. self.utility.append(shape)
  1386. else:
  1387. self.storage.insert(shape) # TODO: Check performance
  1388. def on_canvas_click_release(self, event):
  1389. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  1390. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  1391. if self.app.grid_status():
  1392. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  1393. else:
  1394. pos = (pos_canvas[0], pos_canvas[1])
  1395. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  1396. # canvas menu
  1397. try:
  1398. if event.button == 2: # right click
  1399. if self.app.panning_action is True:
  1400. self.app.panning_action = False
  1401. else:
  1402. self.app.cursor = QtGui.QCursor()
  1403. self.app.ui.popMenu.popup(self.app.cursor.pos())
  1404. except Exception as e:
  1405. log.warning("Error: %s" % str(e))
  1406. raise
  1407. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  1408. # selection and then select a type of selection ("enclosing" or "touching")
  1409. try:
  1410. if event.button == 1: # left click
  1411. if self.app.selection_type is not None:
  1412. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  1413. self.app.selection_type = None
  1414. elif isinstance(self.active_tool, FCApertureSelect):
  1415. # Dispatch event to active_tool
  1416. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1417. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  1418. # self.app.inform.emit(msg)
  1419. self.active_tool.click_release((self.pos[0], self.pos[1]))
  1420. self.replot()
  1421. except Exception as e:
  1422. log.warning("Error: %s" % str(e))
  1423. raise
  1424. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  1425. """
  1426. :param start_pos: mouse position when the selection LMB click was done
  1427. :param end_pos: mouse position when the left mouse button is released
  1428. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1429. :type Bool
  1430. :return:
  1431. """
  1432. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1433. self.app.delete_selection_shape()
  1434. for storage in self.storage_dict:
  1435. for obj in self.storage_dict[storage].get_objects():
  1436. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  1437. (sel_type is False and poly_selection.intersects(obj.geo)):
  1438. if self.key == self.app.defaults["global_mselect_key"]:
  1439. if obj in self.selected:
  1440. self.selected.remove(obj)
  1441. else:
  1442. # add the object to the selected shapes
  1443. self.selected.append(obj)
  1444. else:
  1445. self.selected.append(obj)
  1446. # select the diameter of the selected shape in the tool table
  1447. for storage in self.storage_dict:
  1448. for shape_s in self.selected:
  1449. if shape_s in self.storage_dict[storage].get_objects():
  1450. for key in self.tool2tooldia:
  1451. if self.tool2tooldia[key] == storage:
  1452. item = self.tools_table_exc.item((key - 1), 1)
  1453. self.tools_table_exc.setCurrentItem(item)
  1454. self.last_tool_selected = key
  1455. # item.setSelected(True)
  1456. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1457. self.replot()
  1458. def on_canvas_move(self, event):
  1459. """
  1460. Called on 'mouse_move' event
  1461. event.pos have canvas screen coordinates
  1462. :param event: Event object dispatched by VisPy SceneCavas
  1463. :return: None
  1464. """
  1465. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1466. event.xdata, event.ydata = pos[0], pos[1]
  1467. self.x = event.xdata
  1468. self.y = event.ydata
  1469. # Prevent updates on pan
  1470. # if len(event.buttons) > 0:
  1471. # return
  1472. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  1473. if event.button == 2:
  1474. self.app.panning_action = True
  1475. return
  1476. else:
  1477. self.app.panning_action = False
  1478. try:
  1479. x = float(event.xdata)
  1480. y = float(event.ydata)
  1481. except TypeError:
  1482. return
  1483. if self.active_tool is None:
  1484. return
  1485. ### Snap coordinates
  1486. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  1487. self.snap_x = x
  1488. self.snap_y = y
  1489. # update the position label in the infobar since the APP mouse event handlers are disconnected
  1490. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1491. "<b>Y</b>: %.4f" % (x, y))
  1492. if self.pos is None:
  1493. self.pos = (0, 0)
  1494. dx = x - self.pos[0]
  1495. dy = y - self.pos[1]
  1496. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  1497. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1498. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1499. ### Utility geometry (animated)
  1500. geo = self.active_tool.utility_geometry(data=(x, y))
  1501. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  1502. # Remove any previous utility shape
  1503. self.tool_shape.clear(update=True)
  1504. self.draw_utility_geometry(geo=geo)
  1505. ### Selection area on canvas section ###
  1506. dx = pos[0] - self.pos[0]
  1507. if event.is_dragging == 1 and event.button == 1:
  1508. self.app.delete_selection_shape()
  1509. if dx < 0:
  1510. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  1511. color=self.app.defaults["global_alt_sel_line"],
  1512. face_color=self.app.defaults['global_alt_sel_fill'])
  1513. self.app.selection_type = False
  1514. else:
  1515. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  1516. self.app.selection_type = True
  1517. else:
  1518. self.app.selection_type = None
  1519. # Update cursor
  1520. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  1521. def on_canvas_key_release(self, event):
  1522. self.key = None
  1523. def draw_utility_geometry(self, geo):
  1524. # Add the new utility shape
  1525. try:
  1526. # this case is for the Font Parse
  1527. for el in list(geo.geo):
  1528. if type(el) == MultiPolygon:
  1529. for poly in el:
  1530. self.tool_shape.add(
  1531. shape=poly,
  1532. color=(self.app.defaults["global_draw_color"] + '80'),
  1533. update=False,
  1534. layer=0,
  1535. tolerance=None
  1536. )
  1537. elif type(el) == MultiLineString:
  1538. for linestring in el:
  1539. self.tool_shape.add(
  1540. shape=linestring,
  1541. color=(self.app.defaults["global_draw_color"] + '80'),
  1542. update=False,
  1543. layer=0,
  1544. tolerance=None
  1545. )
  1546. else:
  1547. self.tool_shape.add(
  1548. shape=el,
  1549. color=(self.app.defaults["global_draw_color"] + '80'),
  1550. update=False,
  1551. layer=0,
  1552. tolerance=None
  1553. )
  1554. except TypeError:
  1555. self.tool_shape.add(
  1556. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  1557. update=False, layer=0, tolerance=None)
  1558. self.tool_shape.redraw()
  1559. def replot(self):
  1560. self.plot_all()
  1561. def plot_all(self):
  1562. """
  1563. Plots all shapes in the editor.
  1564. :return: None
  1565. :rtype: None
  1566. """
  1567. # self.app.log.debug("plot_all()")
  1568. self.shapes.clear(update=True)
  1569. for storage in self.storage_dict:
  1570. for shape_plus in self.storage_dict[storage].get_objects():
  1571. if shape_plus.geo is None:
  1572. continue
  1573. if shape_plus in self.selected:
  1574. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  1575. linewidth=2)
  1576. continue
  1577. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  1578. # for shape in self.storage.get_objects():
  1579. # if shape.geo is None: # TODO: This shouldn't have happened
  1580. # continue
  1581. #
  1582. # if shape in self.selected:
  1583. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  1584. # continue
  1585. #
  1586. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  1587. for shape in self.utility:
  1588. self.plot_shape(geometry=shape.geo, linewidth=1)
  1589. continue
  1590. self.shapes.redraw()
  1591. def plot_shape(self, geometry=None, color='black', linewidth=1):
  1592. """
  1593. Plots a geometric object or list of objects without rendering. Plotted objects
  1594. are returned as a list. This allows for efficient/animated rendering.
  1595. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  1596. :param color: Shape color
  1597. :param linewidth: Width of lines in # of pixels.
  1598. :return: List of plotted elements.
  1599. """
  1600. plot_elements = []
  1601. if geometry is None:
  1602. geometry = self.active_tool.geometry
  1603. try:
  1604. for geo in geometry:
  1605. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  1606. ## Non-iterable
  1607. except TypeError:
  1608. ## DrawToolShape
  1609. if isinstance(geometry, DrawToolShape):
  1610. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  1611. ## Polygon: Descend into exterior and each interior.
  1612. if type(geometry) == Polygon:
  1613. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  1614. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  1615. if type(geometry) == LineString or type(geometry) == LinearRing:
  1616. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  1617. if type(geometry) == Point:
  1618. pass
  1619. return plot_elements
  1620. def on_shape_complete(self):
  1621. self.app.log.debug("on_shape_complete()")
  1622. # Add shape
  1623. self.add_shape(self.active_tool.geometry)
  1624. # Remove any utility shapes
  1625. self.delete_utility_geometry()
  1626. self.tool_shape.clear(update=True)
  1627. # Replot and reset tool.
  1628. self.replot()
  1629. # self.active_tool = type(self.active_tool)(self)
  1630. def get_selected(self):
  1631. """
  1632. Returns list of shapes that are selected in the editor.
  1633. :return: List of shapes.
  1634. """
  1635. # return [shape for shape in self.shape_buffer if shape["selected"]]
  1636. return self.selected
  1637. def delete_selected(self):
  1638. temp_ref = [s for s in self.selected]
  1639. for shape_sel in temp_ref:
  1640. self.delete_shape(shape_sel)
  1641. self.selected = []
  1642. self.build_ui()
  1643. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  1644. def delete_shape(self, shape):
  1645. self.is_modified = True
  1646. if shape in self.utility:
  1647. self.utility.remove(shape)
  1648. return
  1649. for storage in self.storage_dict:
  1650. # try:
  1651. # self.storage_dict[storage].remove(shape)
  1652. # except:
  1653. # pass
  1654. if shape in self.storage_dict[storage].get_objects():
  1655. self.storage_dict[storage].remove(shape)
  1656. # a hack to make the tool_table display less drills per diameter
  1657. # self.points_edit it's only useful first time when we load the data into the storage
  1658. # but is still used as referecen when building tool_table in self.build_ui()
  1659. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  1660. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  1661. del self.points_edit[storage][0]
  1662. if shape in self.selected:
  1663. self.selected.remove(shape) # TODO: Check performance
  1664. def delete_utility_geometry(self):
  1665. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  1666. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  1667. for_deletion = [shape for shape in self.utility]
  1668. for shape in for_deletion:
  1669. self.delete_shape(shape)
  1670. self.tool_shape.clear(update=True)
  1671. self.tool_shape.redraw()
  1672. def on_delete_btn(self):
  1673. self.delete_selected()
  1674. self.replot()
  1675. def select_tool(self, toolname):
  1676. """
  1677. Selects a drawing tool. Impacts the object and GUI.
  1678. :param toolname: Name of the tool.
  1679. :return: None
  1680. """
  1681. self.tools_exc[toolname]["button"].setChecked(True)
  1682. self.on_tool_select(toolname)
  1683. def set_selected(self, shape):
  1684. # Remove and add to the end.
  1685. if shape in self.selected:
  1686. self.selected.remove(shape)
  1687. self.selected.append(shape)
  1688. def set_unselected(self, shape):
  1689. if shape in self.selected:
  1690. self.selected.remove(shape)
  1691. def on_array_type_combo(self):
  1692. if self.array_type_combo.currentIndex() == 0:
  1693. self.array_circular_frame.hide()
  1694. self.array_linear_frame.show()
  1695. else:
  1696. self.delete_utility_geometry()
  1697. self.array_circular_frame.show()
  1698. self.array_linear_frame.hide()
  1699. self.app.inform.emit(_("Click on the circular array Center position"))
  1700. def on_linear_angle_radio(self):
  1701. val = self.drill_axis_radio.get_value()
  1702. if val == 'A':
  1703. self.linear_angle_spinner.show()
  1704. self.linear_angle_label.show()
  1705. else:
  1706. self.linear_angle_spinner.hide()
  1707. self.linear_angle_label.hide()
  1708. def exc_add_drill(self):
  1709. self.select_tool('add')
  1710. return
  1711. def exc_add_drill_array(self):
  1712. self.select_tool('add_array')
  1713. return
  1714. def exc_resize_drills(self):
  1715. self.select_tool('resize')
  1716. return
  1717. def exc_copy_drills(self):
  1718. self.select_tool('copy')
  1719. return
  1720. def exc_move_drills(self):
  1721. self.select_tool('move')
  1722. return