FlatCAMGrbEditor.py 89 KB

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