FlatCAMGrbEditor.py 82 KB

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