FlatCAMGrbEditor.py 88 KB

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