FlatCAMGrbEditor.py 83 KB

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