FlatCAMGrbEditor.py 82 KB

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