FlatCAMExcEditor.py 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607
  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. from copy import copy, deepcopy
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. fcTranslate.apply_language('strings')
  15. import builtins
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class FCDrillAdd(FCShapeTool):
  19. """
  20. Resulting type: MultiLineString
  21. """
  22. def __init__(self, draw_app):
  23. DrawTool.__init__(self, draw_app)
  24. self.name = 'drill_add'
  25. self.selected_dia = None
  26. try:
  27. self.draw_app.app.inform.emit(self.start_msg)
  28. # self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.tools_table_exc.currentRow() + 1]
  29. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  30. # as a visual marker, select again in tooltable the actual tool that we are using
  31. # remember that it was deselected when clicking on canvas
  32. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  33. self.draw_app.tools_table_exc.setCurrentItem(item)
  34. except KeyError:
  35. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  36. self.draw_app.select_tool("select")
  37. return
  38. try:
  39. QtGui.QGuiApplication.restoreOverrideCursor()
  40. except:
  41. pass
  42. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill.png'))
  43. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  44. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  45. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  46. self.draw_app.draw_utility_geometry(geo=geo)
  47. self.draw_app.app.inform.emit(_("Click on target location ..."))
  48. # Switch notebook to Selected page
  49. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  50. def click(self, point):
  51. self.make()
  52. return "Done."
  53. def utility_geometry(self, data=None):
  54. self.points = data
  55. return DrawToolUtilityShape(self.util_shape(data))
  56. def util_shape(self, point):
  57. if point[0] is None and point[1] is None:
  58. point_x = self.draw_app.x
  59. point_y = self.draw_app.y
  60. else:
  61. point_x = point[0]
  62. point_y = point[1]
  63. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  64. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  65. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  66. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  67. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  68. def make(self):
  69. try:
  70. QtGui.QGuiApplication.restoreOverrideCursor()
  71. except:
  72. pass
  73. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  74. # to the value, as a list of itself
  75. if self.selected_dia in self.draw_app.points_edit:
  76. self.draw_app.points_edit[self.selected_dia].append(self.points)
  77. else:
  78. self.draw_app.points_edit[self.selected_dia] = [self.points]
  79. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  80. self.geometry = DrawToolShape(self.util_shape(self.points))
  81. self.complete = True
  82. self.draw_app.app.inform.emit(_("[success] Done. Drill added."))
  83. class FCDrillArray(FCShapeTool):
  84. """
  85. Resulting type: MultiLineString
  86. """
  87. def __init__(self, draw_app):
  88. DrawTool.__init__(self, draw_app)
  89. self.name = 'drill_array'
  90. self.draw_app.array_frame.show()
  91. self.selected_dia = None
  92. self.drill_axis = 'X'
  93. self.drill_array = 'linear'
  94. self.drill_array_size = None
  95. self.drill_pitch = None
  96. self.drill_linear_angle = None
  97. self.drill_angle = None
  98. self.drill_direction = None
  99. self.drill_radius = None
  100. self.origin = None
  101. self.destination = None
  102. self.flag_for_circ_array = None
  103. self.last_dx = 0
  104. self.last_dy = 0
  105. self.pt = []
  106. try:
  107. self.draw_app.app.inform.emit(self.start_msg)
  108. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  109. # as a visual marker, select again in tooltable the actual tool that we are using
  110. # remember that it was deselected when clicking on canvas
  111. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  112. self.draw_app.tools_table_exc.setCurrentItem(item)
  113. except KeyError:
  114. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  115. return
  116. try:
  117. QtGui.QGuiApplication.restoreOverrideCursor()
  118. except:
  119. pass
  120. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill_array.png'))
  121. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  122. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  123. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  124. self.draw_app.draw_utility_geometry(geo=geo)
  125. self.draw_app.app.inform.emit(_("Click on target location ..."))
  126. # Switch notebook to Selected page
  127. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  128. def click(self, point):
  129. if self.drill_array == 'Linear':
  130. self.make()
  131. return
  132. else:
  133. if self.flag_for_circ_array is None:
  134. self.draw_app.in_action = True
  135. self.pt.append(point)
  136. self.flag_for_circ_array = True
  137. self.set_origin(point)
  138. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  139. else:
  140. self.destination = point
  141. self.make()
  142. self.flag_for_circ_array = None
  143. return
  144. def set_origin(self, origin):
  145. self.origin = origin
  146. def utility_geometry(self, data=None, static=None):
  147. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  148. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  149. self.drill_array = self.draw_app.array_type_combo.get_value()
  150. try:
  151. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  152. try:
  153. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  154. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  155. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  156. except TypeError:
  157. self.draw_app.app.inform.emit(
  158. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  159. return
  160. except Exception as e:
  161. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  162. return
  163. if self.drill_array == 'Linear':
  164. if data[0] is None and data[1] is None:
  165. dx = self.draw_app.x
  166. dy = self.draw_app.y
  167. else:
  168. dx = data[0]
  169. dy = data[1]
  170. geo_list = []
  171. geo = None
  172. self.points = [dx, dy]
  173. for item in range(self.drill_array_size):
  174. if self.drill_axis == 'X':
  175. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  176. if self.drill_axis == 'Y':
  177. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  178. if self.drill_axis == 'A':
  179. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  180. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  181. geo = self.util_shape(
  182. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  183. )
  184. if static is None or static is False:
  185. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  186. else:
  187. geo_list.append(geo)
  188. # self.origin = data
  189. self.last_dx = dx
  190. self.last_dy = dy
  191. return DrawToolUtilityShape(geo_list)
  192. else:
  193. if data[0] is None and data[1] is None:
  194. cdx = self.draw_app.x
  195. cdy = self.draw_app.y
  196. else:
  197. cdx = data[0]
  198. cdy = data[1]
  199. if len(self.pt) > 0:
  200. temp_points = [x for x in self.pt]
  201. temp_points.append([cdx, cdy])
  202. return DrawToolUtilityShape(LineString(temp_points))
  203. def util_shape(self, point):
  204. if point[0] is None and point[1] is None:
  205. point_x = self.draw_app.x
  206. point_y = self.draw_app.y
  207. else:
  208. point_x = point[0]
  209. point_y = point[1]
  210. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  211. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  212. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  213. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  214. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  215. def make(self):
  216. self.geometry = []
  217. geo = None
  218. try:
  219. QtGui.QGuiApplication.restoreOverrideCursor()
  220. except:
  221. pass
  222. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  223. # to the value, as a list of itself
  224. if self.selected_dia not in self.draw_app.points_edit:
  225. self.draw_app.points_edit[self.selected_dia] = []
  226. for i in range(self.drill_array_size):
  227. self.draw_app.points_edit[self.selected_dia].append(self.points)
  228. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  229. if self.drill_array == 'Linear':
  230. for item in range(self.drill_array_size):
  231. if self.drill_axis == 'X':
  232. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  233. if self.drill_axis == 'Y':
  234. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  235. if self.drill_axis == 'A':
  236. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  237. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  238. geo = self.util_shape(
  239. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  240. )
  241. self.geometry.append(DrawToolShape(geo))
  242. else:
  243. if (self.drill_angle * self.drill_array_size) > 360:
  244. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many drills for the selected spacing angle."))
  245. return
  246. radius = distance(self.destination, self.origin)
  247. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  248. for i in range(self.drill_array_size):
  249. angle_radians = math.radians(self.drill_angle * i)
  250. if self.drill_direction == 'CW':
  251. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  252. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  253. else:
  254. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  255. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  256. geo = self.util_shape((x, y))
  257. self.geometry.append(DrawToolShape(geo))
  258. self.complete = True
  259. self.draw_app.app.inform.emit(_("[success] Done. Drill Array added."))
  260. self.draw_app.in_action = True
  261. self.draw_app.array_frame.hide()
  262. return
  263. class FCDrillResize(FCShapeTool):
  264. def __init__(self, draw_app):
  265. DrawTool.__init__(self, draw_app)
  266. self.name = 'drill_resize'
  267. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  268. self.resize_dia = None
  269. self.draw_app.resize_frame.show()
  270. self.points = None
  271. self.selected_dia_list = []
  272. self.current_storage = None
  273. self.geometry = []
  274. self.destination_storage = None
  275. self.draw_app.resize_btn.clicked.connect(self.make)
  276. # Switch notebook to Selected page
  277. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  278. def make(self):
  279. self.draw_app.is_modified = True
  280. try:
  281. new_dia = self.draw_app.resdrill_entry.get_value()
  282. except:
  283. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Resize drill(s) failed. Please enter a diameter for resize."))
  284. return
  285. if new_dia not in self.draw_app.olddia_newdia:
  286. self.destination_storage = FlatCAMGeoEditor.make_storage()
  287. self.draw_app.storage_dict[new_dia] = self.destination_storage
  288. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  289. # each time a tool diameter is edited or added
  290. self.draw_app.olddia_newdia[new_dia] = new_dia
  291. else:
  292. self.destination_storage = self.draw_app.storage_dict[new_dia]
  293. for index in self.draw_app.tools_table_exc.selectedIndexes():
  294. row = index.row()
  295. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  296. # therefore below we convert to float
  297. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  298. self.selected_dia_list.append(float(dia_on_row))
  299. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  300. # we add a new entry in the tool2tooldia dict
  301. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  302. sel_shapes_to_be_deleted = []
  303. if self.selected_dia_list:
  304. for sel_dia in self.selected_dia_list:
  305. self.current_storage = self.draw_app.storage_dict[sel_dia]
  306. for select_shape in self.draw_app.get_selected():
  307. if select_shape in self.current_storage.get_objects():
  308. factor = new_dia / sel_dia
  309. self.geometry.append(
  310. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  311. )
  312. self.current_storage.remove(select_shape)
  313. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  314. # self.points_edit it's only useful first time when we load the data into the storage
  315. # but is still used as reference when building tool_table in self.build_ui()
  316. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  317. # deleting self.points_edit elements (doesn't matter who but just the number)
  318. # solved the display issue.
  319. del self.draw_app.points_edit[sel_dia][0]
  320. sel_shapes_to_be_deleted.append(select_shape)
  321. self.draw_app.on_exc_shape_complete(self.destination_storage)
  322. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  323. # self.points_edit it's only useful first time when we load the data into the storage
  324. # but is still used as reference when building tool_table in self.build_ui()
  325. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  326. # deleting self.points_edit elements (doesn't matter who but just the number)
  327. # solved the display issue.
  328. if new_dia not in self.draw_app.points_edit:
  329. self.draw_app.points_edit[new_dia] = [(0, 0)]
  330. else:
  331. self.draw_app.points_edit[new_dia].append((0,0))
  332. self.geometry = []
  333. # if following the resize of the drills there will be no more drills for the selected tool then
  334. # delete that tool
  335. if not self.draw_app.points_edit[sel_dia]:
  336. self.draw_app.on_tool_delete(sel_dia)
  337. for shp in sel_shapes_to_be_deleted:
  338. self.draw_app.selected.remove(shp)
  339. sel_shapes_to_be_deleted = []
  340. self.draw_app.build_ui()
  341. self.draw_app.replot()
  342. self.draw_app.app.inform.emit(_("[success] Done. Drill Resize completed."))
  343. else:
  344. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No drills selected for resize ..."))
  345. self.draw_app.resize_frame.hide()
  346. self.complete = True
  347. # MS: always return to the Select Tool
  348. self.draw_app.select_tool("select")
  349. class FCDrillMove(FCShapeTool):
  350. def __init__(self, draw_app):
  351. DrawTool.__init__(self, draw_app)
  352. self.name = 'drill_move'
  353. # self.shape_buffer = self.draw_app.shape_buffer
  354. self.origin = None
  355. self.destination = None
  356. self.selected_dia_list = []
  357. if self.draw_app.launched_from_shortcuts is True:
  358. self.draw_app.launched_from_shortcuts = False
  359. self.draw_app.app.inform.emit(_("Click on target location ..."))
  360. else:
  361. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  362. self.current_storage = None
  363. self.geometry = []
  364. for index in self.draw_app.tools_table_exc.selectedIndexes():
  365. row = index.row()
  366. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  367. # therefore below we convert to float
  368. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  369. self.selected_dia_list.append(float(dia_on_row))
  370. # Switch notebook to Selected page
  371. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  372. def set_origin(self, origin):
  373. self.origin = origin
  374. def click(self, point):
  375. if len(self.draw_app.get_selected()) == 0:
  376. return "Nothing to move."
  377. if self.origin is None:
  378. self.set_origin(point)
  379. self.draw_app.app.inform.emit(_("Click on target location ..."))
  380. return
  381. else:
  382. self.destination = point
  383. self.make()
  384. # MS: always return to the Select Tool
  385. self.draw_app.select_tool("select")
  386. return
  387. def make(self):
  388. # Create new geometry
  389. dx = self.destination[0] - self.origin[0]
  390. dy = self.destination[1] - self.origin[1]
  391. sel_shapes_to_be_deleted = []
  392. for sel_dia in self.selected_dia_list:
  393. self.current_storage = self.draw_app.storage_dict[sel_dia]
  394. for select_shape in self.draw_app.get_selected():
  395. if select_shape in self.current_storage.get_objects():
  396. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  397. self.current_storage.remove(select_shape)
  398. sel_shapes_to_be_deleted.append(select_shape)
  399. self.draw_app.on_exc_shape_complete(self.current_storage)
  400. self.geometry = []
  401. for shp in sel_shapes_to_be_deleted:
  402. self.draw_app.selected.remove(shp)
  403. sel_shapes_to_be_deleted = []
  404. self.draw_app.build_ui()
  405. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) Move completed."))
  406. def utility_geometry(self, data=None):
  407. """
  408. Temporary geometry on screen while using this tool.
  409. :param data:
  410. :return:
  411. """
  412. geo_list = []
  413. if self.origin is None:
  414. return None
  415. if len(self.draw_app.get_selected()) == 0:
  416. return None
  417. dx = data[0] - self.origin[0]
  418. dy = data[1] - self.origin[1]
  419. for geom in self.draw_app.get_selected():
  420. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  421. return DrawToolUtilityShape(geo_list)
  422. class FCDrillCopy(FCDrillMove):
  423. def __init__(self, draw_app):
  424. FCDrillMove.__init__(self, draw_app)
  425. self.name = 'drill_copy'
  426. def make(self):
  427. # Create new geometry
  428. dx = self.destination[0] - self.origin[0]
  429. dy = self.destination[1] - self.origin[1]
  430. sel_shapes_to_be_deleted = []
  431. for sel_dia in self.selected_dia_list:
  432. self.current_storage = self.draw_app.storage_dict[sel_dia]
  433. for select_shape in self.draw_app.get_selected():
  434. if select_shape in self.current_storage.get_objects():
  435. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  436. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  437. self.draw_app.points_edit[sel_dia].append((0, 0))
  438. sel_shapes_to_be_deleted.append(select_shape)
  439. self.draw_app.on_exc_shape_complete(self.current_storage)
  440. self.geometry = []
  441. for shp in sel_shapes_to_be_deleted:
  442. self.draw_app.selected.remove(shp)
  443. sel_shapes_to_be_deleted = []
  444. self.draw_app.build_ui()
  445. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) copied."))
  446. class FCDrillSelect(DrawTool):
  447. def __init__(self, exc_editor_app):
  448. DrawTool.__init__(self, exc_editor_app)
  449. self.name = 'drill_select'
  450. try:
  451. QtGui.QGuiApplication.restoreOverrideCursor()
  452. except:
  453. pass
  454. self.exc_editor_app = exc_editor_app
  455. self.storage = self.exc_editor_app.storage_dict
  456. # self.selected = self.exc_editor_app.selected
  457. # here we store all shapes that were selected so we can search for the nearest to our click location
  458. self.sel_storage = FlatCAMExcEditor.make_storage()
  459. self.exc_editor_app.resize_frame.hide()
  460. self.exc_editor_app.array_frame.hide()
  461. def click(self, point):
  462. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  463. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  464. if key_modifier == Qt.ControlModifier:
  465. pass
  466. else:
  467. self.exc_editor_app.selected = []
  468. else:
  469. if key_modifier == Qt.ShiftModifier:
  470. pass
  471. else:
  472. self.exc_editor_app.selected = []
  473. def click_release(self, pos):
  474. self.exc_editor_app.tools_table_exc.clearSelection()
  475. try:
  476. for storage in self.exc_editor_app.storage_dict:
  477. for shape in self.exc_editor_app.storage_dict[storage].get_objects():
  478. self.sel_storage.insert(shape)
  479. _, closest_shape = self.sel_storage.nearest(pos)
  480. # constrain selection to happen only within a certain bounding box
  481. x_coord, y_coord = closest_shape.geo[0].xy
  482. delta = (x_coord[1] - x_coord[0])
  483. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  484. xmin = x_coord[0] - (0.7 * delta)
  485. xmax = x_coord[0] + (1.7 * delta)
  486. ymin = y_coord[0] - (0.7 * delta)
  487. ymax = y_coord[0] + (1.7 * delta)
  488. except StopIteration:
  489. return ""
  490. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  491. self.exc_editor_app.selected = []
  492. else:
  493. modifiers = QtWidgets.QApplication.keyboardModifiers()
  494. mod_key = 'Control'
  495. if modifiers == QtCore.Qt.ShiftModifier:
  496. mod_key = 'Shift'
  497. elif modifiers == QtCore.Qt.ControlModifier:
  498. mod_key = 'Control'
  499. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  500. if closest_shape in self.exc_editor_app.selected:
  501. self.exc_editor_app.selected.remove(closest_shape)
  502. else:
  503. self.exc_editor_app.selected.append(closest_shape)
  504. else:
  505. self.draw_app.selected = []
  506. self.draw_app.selected.append(closest_shape)
  507. # select the diameter of the selected shape in the tool table
  508. try:
  509. self.draw_app.tools_table_exc.cellPressed.disconnect()
  510. except:
  511. pass
  512. sel_tools = set()
  513. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  514. for shape_s in self.exc_editor_app.selected:
  515. for storage in self.exc_editor_app.storage_dict:
  516. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  517. sel_tools.add(storage)
  518. for storage in sel_tools:
  519. self.exc_editor_app.tools_table_exc.selectRow(int(storage))
  520. self.draw_app.last_tool_selected = int(storage)
  521. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  522. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  523. # delete whatever is in selection storage, there is no longer need for those shapes
  524. self.sel_storage = FlatCAMExcEditor.make_storage()
  525. return ""
  526. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  527. # for storage in self.exc_editor_app.storage_dict:
  528. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  529. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  530. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  531. # over_shape_list.append(obj_shape)
  532. #
  533. # try:
  534. # # if there is no shape under our click then deselect all shapes
  535. # if not over_shape_list:
  536. # self.exc_editor_app.selected = []
  537. # FlatCAMExcEditor.draw_shape_idx = -1
  538. # self.exc_editor_app.tools_table_exc.clearSelection()
  539. # else:
  540. # # if there are shapes under our click then advance through the list of them, one at the time in a
  541. # # circular way
  542. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  543. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  544. #
  545. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  546. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  547. # if obj_to_add in self.exc_editor_app.selected:
  548. # self.exc_editor_app.selected.remove(obj_to_add)
  549. # else:
  550. # self.exc_editor_app.selected.append(obj_to_add)
  551. # else:
  552. # self.exc_editor_app.selected = []
  553. # self.exc_editor_app.selected.append(obj_to_add)
  554. # else:
  555. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  556. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  557. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  558. # if obj_to_add in self.exc_editor_app.selected:
  559. # self.exc_editor_app.selected.remove(obj_to_add)
  560. # else:
  561. # self.exc_editor_app.selected.append(obj_to_add)
  562. # else:
  563. # self.exc_editor_app.selected = []
  564. # self.exc_editor_app.selected.append(obj_to_add)
  565. #
  566. # for storage in self.exc_editor_app.storage_dict:
  567. # for shape in self.exc_editor_app.selected:
  568. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  569. # for key in self.exc_editor_app.tool2tooldia:
  570. # if self.exc_editor_app.tool2tooldia[key] == storage:
  571. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  572. # item.setSelected(True)
  573. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  574. #
  575. # except Exception as e:
  576. # log.error("[ERROR] Something went bad. %s" % str(e))
  577. # raise
  578. class FlatCAMExcEditor(QtCore.QObject):
  579. draw_shape_idx = -1
  580. def __init__(self, app):
  581. assert isinstance(app, FlatCAMApp.App), \
  582. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  583. super(FlatCAMExcEditor, self).__init__()
  584. self.app = app
  585. self.canvas = self.app.plotcanvas
  586. ## Current application units in Upper Case
  587. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  588. self.exc_edit_widget = QtWidgets.QWidget()
  589. ## Box for custom widgets
  590. # This gets populated in offspring implementations.
  591. layout = QtWidgets.QVBoxLayout()
  592. self.exc_edit_widget.setLayout(layout)
  593. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  594. # this way I can hide/show the frame
  595. self.drills_frame = QtWidgets.QFrame()
  596. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  597. layout.addWidget(self.drills_frame)
  598. self.tools_box = QtWidgets.QVBoxLayout()
  599. self.tools_box.setContentsMargins(0, 0, 0, 0)
  600. self.drills_frame.setLayout(self.tools_box)
  601. ## Page Title box (spacing between children)
  602. self.title_box = QtWidgets.QHBoxLayout()
  603. self.tools_box.addLayout(self.title_box)
  604. ## Page Title icon
  605. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  606. self.icon = QtWidgets.QLabel()
  607. self.icon.setPixmap(pixmap)
  608. self.title_box.addWidget(self.icon, stretch=0)
  609. ## Title label
  610. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  611. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  612. self.title_box.addWidget(self.title_label, stretch=1)
  613. ## Object name
  614. self.name_box = QtWidgets.QHBoxLayout()
  615. self.tools_box.addLayout(self.name_box)
  616. name_label = QtWidgets.QLabel(_("Name:"))
  617. self.name_box.addWidget(name_label)
  618. self.name_entry = FCEntry()
  619. self.name_box.addWidget(self.name_entry)
  620. #### Tools Drills ####
  621. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  622. self.tools_table_label.setToolTip(
  623. _( "Tools in this Excellon object\n"
  624. "when are used for drilling.")
  625. )
  626. self.tools_box.addWidget(self.tools_table_label)
  627. self.tools_table_exc = FCTable()
  628. # delegate = SpinBoxDelegate(units=self.units)
  629. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  630. self.tools_box.addWidget(self.tools_table_exc)
  631. self.tools_table_exc.setColumnCount(4)
  632. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  633. self.tools_table_exc.setSortingEnabled(False)
  634. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  635. self.empty_label = QtWidgets.QLabel('')
  636. self.tools_box.addWidget(self.empty_label)
  637. #### Add a new Tool ####
  638. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  639. self.addtool_label.setToolTip(
  640. _("Add/Delete a tool to the tool list\n"
  641. "for this Excellon object.")
  642. )
  643. self.tools_box.addWidget(self.addtool_label)
  644. grid1 = QtWidgets.QGridLayout()
  645. self.tools_box.addLayout(grid1)
  646. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  647. addtool_entry_lbl.setToolTip(
  648. _("Diameter for the new tool")
  649. )
  650. grid1.addWidget(addtool_entry_lbl, 0, 0)
  651. hlay = QtWidgets.QHBoxLayout()
  652. self.addtool_entry = FCEntry()
  653. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  654. hlay.addWidget(self.addtool_entry)
  655. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  656. self.addtool_btn.setToolTip(
  657. _( "Add a new tool to the tool list\n"
  658. "with the diameter specified above.")
  659. )
  660. self.addtool_btn.setFixedWidth(80)
  661. hlay.addWidget(self.addtool_btn)
  662. grid1.addLayout(hlay, 0, 1)
  663. grid2 = QtWidgets.QGridLayout()
  664. self.tools_box.addLayout(grid2)
  665. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  666. self.deltool_btn.setToolTip(
  667. _( "Delete a tool in the tool list\n"
  668. "by selecting a row in the tool table.")
  669. )
  670. grid2.addWidget(self.deltool_btn, 0, 1)
  671. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  672. # this way I can hide/show the frame
  673. self.resize_frame = QtWidgets.QFrame()
  674. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  675. self.tools_box.addWidget(self.resize_frame)
  676. self.resize_box = QtWidgets.QVBoxLayout()
  677. self.resize_box.setContentsMargins(0, 0, 0, 0)
  678. self.resize_frame.setLayout(self.resize_box)
  679. #### Resize a drill ####
  680. self.emptyresize_label = QtWidgets.QLabel('')
  681. self.resize_box.addWidget(self.emptyresize_label)
  682. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  683. self.drillresize_label.setToolTip(
  684. _("Resize a drill or a selection of drills.")
  685. )
  686. self.resize_box.addWidget(self.drillresize_label)
  687. grid3 = QtWidgets.QGridLayout()
  688. self.resize_box.addLayout(grid3)
  689. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  690. res_entry_lbl.setToolTip(
  691. _( "Diameter to resize to.")
  692. )
  693. grid3.addWidget(res_entry_lbl, 0, 0)
  694. hlay2 = QtWidgets.QHBoxLayout()
  695. self.resdrill_entry = LengthEntry()
  696. hlay2.addWidget(self.resdrill_entry)
  697. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  698. self.resize_btn.setToolTip(
  699. _("Resize drill(s)")
  700. )
  701. self.resize_btn.setFixedWidth(80)
  702. hlay2.addWidget(self.resize_btn)
  703. grid3.addLayout(hlay2, 0, 1)
  704. self.resize_frame.hide()
  705. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  706. # all the add drill array widgets
  707. # this way I can hide/show the frame
  708. self.array_frame = QtWidgets.QFrame()
  709. self.array_frame.setContentsMargins(0, 0, 0, 0)
  710. self.tools_box.addWidget(self.array_frame)
  711. self.array_box = QtWidgets.QVBoxLayout()
  712. self.array_box.setContentsMargins(0, 0, 0, 0)
  713. self.array_frame.setLayout(self.array_box)
  714. #### Add DRILL Array ####
  715. self.emptyarray_label = QtWidgets.QLabel('')
  716. self.array_box.addWidget(self.emptyarray_label)
  717. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  718. self.drillarray_label.setToolTip(
  719. _("Add an array of drills (linear or circular array)")
  720. )
  721. self.array_box.addWidget(self.drillarray_label)
  722. self.array_type_combo = FCComboBox()
  723. self.array_type_combo.setToolTip(
  724. _( "Select the type of drills array to create.\n"
  725. "It can be Linear X(Y) or Circular")
  726. )
  727. self.array_type_combo.addItem(_("Linear"))
  728. self.array_type_combo.addItem(_("Circular"))
  729. self.array_box.addWidget(self.array_type_combo)
  730. self.array_form = QtWidgets.QFormLayout()
  731. self.array_box.addLayout(self.array_form)
  732. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  733. self.drill_array_size_label.setToolTip(
  734. _("Specify how many drills to be in the array.")
  735. )
  736. self.drill_array_size_label.setFixedWidth(100)
  737. self.drill_array_size_entry = LengthEntry()
  738. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  739. self.array_linear_frame = QtWidgets.QFrame()
  740. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  741. self.array_box.addWidget(self.array_linear_frame)
  742. self.linear_box = QtWidgets.QVBoxLayout()
  743. self.linear_box.setContentsMargins(0, 0, 0, 0)
  744. self.array_linear_frame.setLayout(self.linear_box)
  745. self.linear_form = QtWidgets.QFormLayout()
  746. self.linear_box.addLayout(self.linear_form)
  747. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  748. self.drill_axis_label.setToolTip(
  749. _("Direction on which the linear array is oriented:\n"
  750. "- 'X' - horizontal axis \n"
  751. "- 'Y' - vertical axis or \n"
  752. "- 'Angle' - a custom angle for the array inclination")
  753. )
  754. self.drill_axis_label.setFixedWidth(100)
  755. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  756. {'label': 'Y', 'value': 'Y'},
  757. {'label': _('Angle'), 'value': 'A'}])
  758. self.drill_axis_radio.set_value('X')
  759. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  760. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  761. self.drill_pitch_label.setToolTip(
  762. _("Pitch = Distance between elements of the array.")
  763. )
  764. self.drill_pitch_label.setFixedWidth(100)
  765. self.drill_pitch_entry = LengthEntry()
  766. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  767. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  768. self.linear_angle_label.setToolTip(
  769. _( "Angle at which the linear array is placed.\n"
  770. "The precision is of max 2 decimals.\n"
  771. "Min value is: -359.99 degrees.\n"
  772. "Max value is: 360.00 degrees.")
  773. )
  774. self.linear_angle_label.setFixedWidth(100)
  775. self.linear_angle_spinner = FCDoubleSpinner()
  776. self.linear_angle_spinner.set_precision(2)
  777. self.linear_angle_spinner.setRange(-359.99, 360.00)
  778. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  779. self.array_circular_frame = QtWidgets.QFrame()
  780. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  781. self.array_box.addWidget(self.array_circular_frame)
  782. self.circular_box = QtWidgets.QVBoxLayout()
  783. self.circular_box.setContentsMargins(0, 0, 0, 0)
  784. self.array_circular_frame.setLayout(self.circular_box)
  785. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  786. self.drill_direction_label.setToolTip(
  787. _( "Direction for circular array."
  788. "Can be CW = clockwise or CCW = counter clockwise.")
  789. )
  790. self.drill_direction_label.setFixedWidth(100)
  791. self.circular_form = QtWidgets.QFormLayout()
  792. self.circular_box.addLayout(self.circular_form)
  793. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  794. {'label': 'CCW.', 'value': 'CCW'}])
  795. self.drill_direction_radio.set_value('CW')
  796. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  797. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  798. self.drill_angle_label.setToolTip(
  799. _("Angle at which each element in circular array is placed.")
  800. )
  801. self.drill_angle_label.setFixedWidth(100)
  802. self.drill_angle_entry = LengthEntry()
  803. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  804. self.array_circular_frame.hide()
  805. self.linear_angle_spinner.hide()
  806. self.linear_angle_label.hide()
  807. self.array_frame.hide()
  808. self.tools_box.addStretch()
  809. ## Toolbar events and properties
  810. self.tools_exc = {
  811. "select": {"button": self.app.ui.select_drill_btn,
  812. "constructor": FCDrillSelect},
  813. "drill_add": {"button": self.app.ui.add_drill_btn,
  814. "constructor": FCDrillAdd},
  815. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  816. "constructor": FCDrillArray},
  817. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  818. "constructor": FCDrillResize},
  819. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  820. "constructor": FCDrillCopy},
  821. "drill_move": {"button": self.app.ui.move_drill_btn,
  822. "constructor": FCDrillMove},
  823. }
  824. ### Data
  825. self.active_tool = None
  826. self.storage_dict = {}
  827. self.current_storage = []
  828. # build the data from the Excellon point into a dictionary
  829. # {tool_dia: [geometry_in_points]}
  830. self.points_edit = {}
  831. self.sorted_diameters =[]
  832. self.new_drills = []
  833. self.new_tools = {}
  834. self.new_slots = {}
  835. self.new_tool_offset = {}
  836. # dictionary to store the tool_row and diameters in Tool_table
  837. # it will be updated everytime self.build_ui() is called
  838. self.olddia_newdia = {}
  839. self.tool2tooldia = {}
  840. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  841. # is cleared but as a side effect also the selected tool is cleared
  842. self.last_tool_selected = None
  843. self.utility = []
  844. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  845. self.launched_from_shortcuts = False
  846. # this var will store the state of the toolbar before starting the editor
  847. self.toolbar_old_state = False
  848. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  849. self.name_entry.returnPressed.connect(self.on_name_activate)
  850. self.addtool_btn.clicked.connect(self.on_tool_add)
  851. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  852. self.deltool_btn.clicked.connect(self.on_tool_delete)
  853. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  854. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  855. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  856. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  857. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  858. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  859. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  860. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  861. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  862. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  863. # Init GUI
  864. self.drill_array_size_entry.set_value(5)
  865. self.drill_pitch_entry.set_value(2.54)
  866. self.drill_angle_entry.set_value(12)
  867. self.drill_direction_radio.set_value('CW')
  868. self.drill_axis_radio.set_value('X')
  869. self.exc_obj = None
  870. # VisPy Visuals
  871. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  872. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  873. self.app.pool_recreated.connect(self.pool_recreated)
  874. # Remove from scene
  875. self.shapes.enabled = False
  876. self.tool_shape.enabled = False
  877. ## List of selected shapes.
  878. self.selected = []
  879. self.move_timer = QtCore.QTimer()
  880. self.move_timer.setSingleShot(True)
  881. self.key = None # Currently pressed key
  882. self.modifiers = None
  883. self.x = None # Current mouse cursor pos
  884. self.y = None
  885. # Current snapped mouse pos
  886. self.snap_x = None
  887. self.snap_y = None
  888. self.pos = None
  889. def make_callback(thetool):
  890. def f():
  891. self.on_tool_select(thetool)
  892. return f
  893. for tool in self.tools_exc:
  894. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  895. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  896. self.options = {
  897. "global_gridx": 0.1,
  898. "global_gridy": 0.1,
  899. "snap_max": 0.05,
  900. "grid_snap": True,
  901. "corner_snap": False,
  902. "grid_gap_link": True
  903. }
  904. self.app.options_read_form()
  905. for option in self.options:
  906. if option in self.app.options:
  907. self.options[option] = self.app.options[option]
  908. self.rtree_exc_index = rtindex.Index()
  909. # flag to show if the object was modified
  910. self.is_modified = False
  911. self.edited_obj_name = ""
  912. # variable to store the total amount of drills per job
  913. self.tot_drill_cnt = 0
  914. self.tool_row = 0
  915. # variable to store the total amount of slots per job
  916. self.tot_slot_cnt = 0
  917. self.tool_row_slots = 0
  918. self.tool_row = 0
  919. # store the status of the editor so the Delete at object level will not work until the edit is finished
  920. self.editor_active = False
  921. def entry2option(option, entry):
  922. self.options[option] = float(entry.text())
  923. # store the status of the editor so the Delete at object level will not work until the edit is finished
  924. self.editor_active = False
  925. def pool_recreated(self, pool):
  926. self.shapes.pool = pool
  927. self.tool_shape.pool = pool
  928. @staticmethod
  929. def make_storage():
  930. ## Shape storage.
  931. storage = FlatCAMRTreeStorage()
  932. storage.get_points = DrawToolShape.get_pts
  933. return storage
  934. def set_ui(self):
  935. # updated units
  936. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  937. self.olddia_newdia.clear()
  938. self.tool2tooldia.clear()
  939. # build the self.points_edit dict {dimaters: [point_list]}
  940. for drill in self.exc_obj.drills:
  941. if drill['tool'] in self.exc_obj.tools:
  942. if self.units == 'IN':
  943. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  944. else:
  945. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  946. try:
  947. self.points_edit[tool_dia].append(drill['point'])
  948. except KeyError:
  949. self.points_edit[tool_dia] = [drill['point']]
  950. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  951. for key in self.points_edit:
  952. self.olddia_newdia[key] = key
  953. sort_temp = []
  954. for diam in self.olddia_newdia:
  955. sort_temp.append(float(diam))
  956. self.sorted_diameters = sorted(sort_temp)
  957. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  958. if self.exc_obj.diameterless is False:
  959. for i in range(len(self.sorted_diameters)):
  960. tt_dia = self.sorted_diameters[i]
  961. self.tool2tooldia[i + 1] = tt_dia
  962. else:
  963. # the Excellon object has diameters that are bogus information, added by the application because the
  964. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  965. # but use the real order found in the exc_obj.tools
  966. for k, v in self.exc_obj.tools.items():
  967. if self.units == 'IN':
  968. tool_dia = float('%.3f' % v['C'])
  969. else:
  970. tool_dia = float('%.2f' % v['C'])
  971. self.tool2tooldia[int(k)] = tool_dia
  972. def build_ui(self, first_run=None):
  973. try:
  974. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  975. self.tools_table_exc.itemChanged.disconnect()
  976. except:
  977. pass
  978. try:
  979. self.tools_table_exc.cellPressed.disconnect()
  980. except:
  981. pass
  982. # updated units
  983. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  984. # make a new name for the new Excellon object (the one with edited content)
  985. self.edited_obj_name = self.exc_obj.options['name']
  986. self.name_entry.set_value(self.edited_obj_name)
  987. if self.units == "IN":
  988. self.addtool_entry.set_value(0.039)
  989. else:
  990. self.addtool_entry.set_value(1.00)
  991. sort_temp = []
  992. for diam in self.olddia_newdia:
  993. sort_temp.append(float(diam))
  994. self.sorted_diameters = sorted(sort_temp)
  995. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  996. n = len(self.sorted_diameters)
  997. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  998. self.tools_table_exc.setRowCount(n + 2)
  999. self.tot_drill_cnt = 0
  1000. self.tot_slot_cnt = 0
  1001. self.tool_row = 0
  1002. # this variable will serve as the real tool_number
  1003. tool_id = 0
  1004. for tool_no in self.sorted_diameters:
  1005. tool_id += 1
  1006. drill_cnt = 0 # variable to store the nr of drills per tool
  1007. slot_cnt = 0 # variable to store the nr of slots per tool
  1008. # Find no of drills for the current tool
  1009. for tool_dia in self.points_edit:
  1010. if float(tool_dia) == tool_no:
  1011. drill_cnt = len(self.points_edit[tool_dia])
  1012. self.tot_drill_cnt += drill_cnt
  1013. try:
  1014. # Find no of slots for the current tool
  1015. for slot in self.slots:
  1016. if slot['tool'] == tool_no:
  1017. slot_cnt += 1
  1018. self.tot_slot_cnt += slot_cnt
  1019. except AttributeError:
  1020. # log.debug("No slots in the Excellon file")
  1021. # slot editing not implemented
  1022. pass
  1023. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1024. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1025. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  1026. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1027. # There are no drill bits in MM with more than 3 decimals diameter
  1028. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1029. if self.units == 'MM':
  1030. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1031. else:
  1032. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  1033. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1034. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1035. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1036. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1037. if slot_cnt > 0:
  1038. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1039. else:
  1040. slot_count = QtWidgets.QTableWidgetItem('')
  1041. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1042. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1043. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1044. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1045. if first_run is True:
  1046. # set now the last tool selected
  1047. self.last_tool_selected = int(tool_id)
  1048. self.tool_row += 1
  1049. # make the diameter column editable
  1050. for row in range(self.tool_row):
  1051. self.tools_table_exc.item(row, 1).setFlags(
  1052. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1053. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1054. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1055. # add a last row with the Total number of drills
  1056. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1057. # it will have to have the foreground color (font color) white
  1058. empty = QtWidgets.QTableWidgetItem('9998')
  1059. empty.setForeground(QtGui.QColor(255, 255, 255))
  1060. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1061. empty_b = QtWidgets.QTableWidgetItem('')
  1062. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1063. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1064. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1065. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1066. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1067. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1068. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1069. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1070. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1071. font = QtGui.QFont()
  1072. font.setBold(True)
  1073. font.setWeight(75)
  1074. for k in [1, 2]:
  1075. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1076. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1077. self.tool_row += 1
  1078. # add a last row with the Total number of slots
  1079. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1080. # it will have to have the foreground color (font color) white
  1081. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1082. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1083. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1084. empty_3 = QtWidgets.QTableWidgetItem('')
  1085. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1086. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1087. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1088. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1089. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1090. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1091. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1092. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1093. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1094. for kl in [1, 2, 3]:
  1095. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1096. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1097. # all the tools are selected by default
  1098. self.tools_table_exc.selectColumn(0)
  1099. #
  1100. self.tools_table_exc.resizeColumnsToContents()
  1101. self.tools_table_exc.resizeRowsToContents()
  1102. vertical_header = self.tools_table_exc.verticalHeader()
  1103. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1104. vertical_header.hide()
  1105. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1106. horizontal_header = self.tools_table_exc.horizontalHeader()
  1107. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1108. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1109. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1110. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1111. # horizontal_header.setStretchLastSection(True)
  1112. # self.tools_table_exc.setSortingEnabled(True)
  1113. # sort by tool diameter
  1114. self.tools_table_exc.sortItems(1)
  1115. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1116. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1117. # use them
  1118. self.tool2tooldia.clear()
  1119. for row in range(self.tools_table_exc.rowCount() - 2):
  1120. tool = int(self.tools_table_exc.item(row, 0).text())
  1121. diameter = float(self.tools_table_exc.item(row, 1).text())
  1122. self.tool2tooldia[tool] = diameter
  1123. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1124. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1125. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1126. self.tools_table_exc.clearSelection()
  1127. # Remove anything else in the GUI Selected Tab
  1128. self.app.ui.selected_scroll_area.takeWidget()
  1129. # Put ourself in the GUI Selected Tab
  1130. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1131. # Switch notebook to Selected page
  1132. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1133. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1134. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1135. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1136. def on_tool_add(self, tooldia=None):
  1137. self.is_modified = True
  1138. if tooldia:
  1139. tool_dia = tooldia
  1140. else:
  1141. try:
  1142. tool_dia = float(self.addtool_entry.get_value())
  1143. except ValueError:
  1144. # try to convert comma to decimal point. if it's still not working error message and return
  1145. try:
  1146. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1147. except ValueError:
  1148. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1149. "use a number.")
  1150. )
  1151. return
  1152. if tool_dia not in self.olddia_newdia:
  1153. storage_elem = FlatCAMGeoEditor.make_storage()
  1154. self.storage_dict[tool_dia] = storage_elem
  1155. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1156. # each time a tool diameter is edited or added
  1157. self.olddia_newdia[tool_dia] = tool_dia
  1158. else:
  1159. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1160. "Save and reedit Excellon if you need to add this tool. ")
  1161. )
  1162. return
  1163. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1164. # we add a new entry in the tool2tooldia dict
  1165. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1166. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia), units=str(self.units)))
  1167. self.build_ui()
  1168. # make a quick sort through the tool2tooldia dict so we find which row to select
  1169. row_to_be_selected = None
  1170. for key in sorted(self.tool2tooldia):
  1171. if self.tool2tooldia[key] == tool_dia:
  1172. row_to_be_selected = int(key) - 1
  1173. self.last_tool_selected = int(key)
  1174. break
  1175. self.tools_table_exc.selectRow(row_to_be_selected)
  1176. def on_tool_delete(self, dia=None):
  1177. self.is_modified = True
  1178. deleted_tool_dia_list = []
  1179. deleted_tool_offset_list = []
  1180. try:
  1181. if dia is None or dia is False:
  1182. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1183. for index in self.tools_table_exc.selectionModel().selectedRows():
  1184. row = index.row()
  1185. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1186. else:
  1187. if isinstance(dia, list):
  1188. for dd in dia:
  1189. deleted_tool_dia_list.append(float('%.4f' % dd))
  1190. else:
  1191. deleted_tool_dia_list.append(float('%.4f' % dia))
  1192. except:
  1193. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1194. return
  1195. for deleted_tool_dia in deleted_tool_dia_list:
  1196. # delete de tool offset
  1197. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1198. # delete the storage used for that tool
  1199. storage_elem = FlatCAMGeoEditor.make_storage()
  1200. self.storage_dict[deleted_tool_dia] = storage_elem
  1201. self.storage_dict.pop(deleted_tool_dia, None)
  1202. # I've added this flag_del variable because dictionary don't like
  1203. # having keys deleted while iterating through them
  1204. flag_del = []
  1205. # self.points_edit.pop(deleted_tool_dia, None)
  1206. for deleted_tool in self.tool2tooldia:
  1207. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1208. flag_del.append(deleted_tool)
  1209. if flag_del:
  1210. for tool_to_be_deleted in flag_del:
  1211. # delete the tool
  1212. self.tool2tooldia.pop(tool_to_be_deleted, None)
  1213. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  1214. # number of drills from before was deleter
  1215. self.points_edit[deleted_tool_dia] = []
  1216. flag_del = []
  1217. self.olddia_newdia.pop(deleted_tool_dia, None)
  1218. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(del_dia=str(deleted_tool_dia), units=str(self.units)))
  1219. self.replot()
  1220. # self.app.inform.emit("Could not delete selected tool")
  1221. self.build_ui()
  1222. def on_tool_edit(self, item_changed):
  1223. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1224. self.tools_table_exc.itemChanged.disconnect()
  1225. self.tools_table_exc.cellPressed.disconnect()
  1226. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1227. self.is_modified = True
  1228. geometry = []
  1229. current_table_dia_edited = None
  1230. if self.tools_table_exc.currentItem() is not None:
  1231. try:
  1232. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  1233. except ValueError as e:
  1234. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1235. self.tools_table_exc.setCurrentItem(None)
  1236. return
  1237. row_of_item_changed = self.tools_table_exc.currentRow()
  1238. # rows start with 0, tools start with 1 so we adjust the value by 1
  1239. key_in_tool2tooldia = row_of_item_changed + 1
  1240. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1241. # tool diameter is not used so we create a new tool with the desired diameter
  1242. if current_table_dia_edited not in self.olddia_newdia.values():
  1243. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1244. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1245. # update the dict that holds tool_no as key and tool_dia as value
  1246. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1247. # update the tool offset
  1248. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  1249. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  1250. self.replot()
  1251. else:
  1252. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  1253. factor = current_table_dia_edited / dia_changed
  1254. geometry = []
  1255. for shape in self.storage_dict[dia_changed].get_objects():
  1256. geometry.append(DrawToolShape(
  1257. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center')
  1258. for subgeo in shape.geo])))
  1259. # add bogus drill points (for total count of drills)
  1260. for k, v in self.olddia_newdia.items():
  1261. if v == current_table_dia_edited:
  1262. self.points_edit[k].append((0, 0))
  1263. break
  1264. # search for the oldia that correspond to the newdia and add the drills in it's storage
  1265. # everything will be sort out later, when the edited excellon is updated
  1266. for k, v in self.olddia_newdia.items():
  1267. if v == current_table_dia_edited:
  1268. self.add_exc_shape(geometry, self.storage_dict[k])
  1269. break
  1270. # delete the old tool from which we moved the drills
  1271. self.on_tool_delete(dia=dia_changed)
  1272. # delete the tool offset
  1273. self.exc_obj.tool_offset.pop(dia_changed, None)
  1274. # we reactivate the signals after the after the tool editing
  1275. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1276. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1277. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1278. def on_name_activate(self):
  1279. self.edited_obj_name = self.name_entry.get_value()
  1280. def activate(self):
  1281. # adjust the status of the menu entries related to the editor
  1282. self.app.ui.menueditedit.setDisabled(True)
  1283. self.app.ui.menueditok.setDisabled(False)
  1284. # adjust the visibility of some of the canvas context menu
  1285. self.app.ui.popmenu_edit.setVisible(False)
  1286. self.app.ui.popmenu_save.setVisible(True)
  1287. self.connect_canvas_event_handlers()
  1288. # initialize working objects
  1289. self.storage_dict = {}
  1290. self.current_storage = []
  1291. self.points_edit = {}
  1292. self.sorted_diameters = []
  1293. self.new_drills = []
  1294. self.new_tools = {}
  1295. self.new_slots = {}
  1296. self.new_tool_offset = {}
  1297. self.olddia_newdia = {}
  1298. self.shapes.enabled = True
  1299. self.tool_shape.enabled = True
  1300. # self.app.app_cursor.enabled = True
  1301. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1302. self.app.ui.corner_snap_btn.setEnabled(True)
  1303. self.app.ui.snap_magnet.setVisible(True)
  1304. self.app.ui.corner_snap_btn.setVisible(True)
  1305. self.app.ui.exc_editor_menu.setDisabled(False)
  1306. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  1307. self.app.ui.update_obj_btn.setEnabled(True)
  1308. self.app.ui.e_editor_cmenu.setEnabled(True)
  1309. self.app.ui.exc_edit_toolbar.setDisabled(False)
  1310. self.app.ui.exc_edit_toolbar.setVisible(True)
  1311. # self.app.ui.snap_toolbar.setDisabled(False)
  1312. # start with GRID toolbar activated
  1313. if self.app.ui.grid_snap_btn.isChecked() is False:
  1314. self.app.ui.grid_snap_btn.trigger()
  1315. # Tell the App that the editor is active
  1316. self.editor_active = True
  1317. # show the UI
  1318. self.drills_frame.show()
  1319. def deactivate(self):
  1320. # adjust the status of the menu entries related to the editor
  1321. self.app.ui.menueditedit.setDisabled(False)
  1322. self.app.ui.menueditok.setDisabled(True)
  1323. # adjust the visibility of some of the canvas context menu
  1324. self.app.ui.popmenu_edit.setVisible(True)
  1325. self.app.ui.popmenu_save.setVisible(False)
  1326. self.disconnect_canvas_event_handlers()
  1327. self.clear()
  1328. self.app.ui.exc_edit_toolbar.setDisabled(True)
  1329. settings = QSettings("Open Source", "FlatCAM")
  1330. if settings.contains("layout"):
  1331. layout = settings.value('layout', type=str)
  1332. if layout == 'standard':
  1333. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1334. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1335. self.app.ui.corner_snap_btn.setEnabled(False)
  1336. self.app.ui.snap_magnet.setVisible(False)
  1337. self.app.ui.corner_snap_btn.setVisible(False)
  1338. elif layout == 'compact':
  1339. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1340. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1341. self.app.ui.corner_snap_btn.setEnabled(False)
  1342. self.app.ui.snap_magnet.setVisible(True)
  1343. self.app.ui.corner_snap_btn.setVisible(True)
  1344. else:
  1345. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1346. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1347. self.app.ui.corner_snap_btn.setEnabled(False)
  1348. self.app.ui.snap_magnet.setVisible(False)
  1349. self.app.ui.corner_snap_btn.setVisible(False)
  1350. # set the Editor Toolbar visibility to what was before entering in the Editor
  1351. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1352. else self.app.ui.exc_edit_toolbar.setVisible(True)
  1353. # Disable visuals
  1354. self.shapes.enabled = False
  1355. self.tool_shape.enabled = False
  1356. # self.app.app_cursor.enabled = False
  1357. # Tell the app that the editor is no longer active
  1358. self.editor_active = False
  1359. self.app.ui.exc_editor_menu.setDisabled(True)
  1360. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  1361. self.app.ui.update_obj_btn.setEnabled(False)
  1362. self.app.ui.g_editor_cmenu.setEnabled(False)
  1363. self.app.ui.e_editor_cmenu.setEnabled(False)
  1364. # Show original geometry
  1365. if self.exc_obj:
  1366. self.exc_obj.visible = True
  1367. # hide the UI
  1368. self.drills_frame.hide()
  1369. def connect_canvas_event_handlers(self):
  1370. ## Canvas events
  1371. # first connect to new, then disconnect the old handlers
  1372. # don't ask why but if there is nothing connected I've seen issues
  1373. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1374. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1375. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  1376. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1377. # but those from FlatCAMGeoEditor
  1378. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1379. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1380. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1381. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1382. self.app.collection.view.clicked.disconnect()
  1383. def disconnect_canvas_event_handlers(self):
  1384. # we restore the key and mouse control to FlatCAMApp method
  1385. # first connect to new, then disconnect the old handlers
  1386. # don't ask why but if there is nothing connected I've seen issues
  1387. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1388. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1389. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1390. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1391. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1392. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1393. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1394. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  1395. def clear(self):
  1396. self.active_tool = None
  1397. # self.shape_buffer = []
  1398. self.selected = []
  1399. self.points_edit = {}
  1400. self.new_tools = {}
  1401. self.new_drills = []
  1402. # self.storage_dict = {}
  1403. self.shapes.clear(update=True)
  1404. self.tool_shape.clear(update=True)
  1405. # self.storage = FlatCAMExcEditor.make_storage()
  1406. self.replot()
  1407. def edit_fcexcellon(self, exc_obj):
  1408. """
  1409. Imports the geometry from the given FlatCAM Excellon object
  1410. into the editor.
  1411. :param fcgeometry: FlatCAMExcellon
  1412. :return: None
  1413. """
  1414. assert isinstance(exc_obj, Excellon), \
  1415. "Expected an Excellon Object, got %s" % type(exc_obj)
  1416. self.deactivate()
  1417. self.activate()
  1418. # Hide original geometry
  1419. self.exc_obj = exc_obj
  1420. exc_obj.visible = False
  1421. # Set selection tolerance
  1422. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1423. self.select_tool("select")
  1424. self.set_ui()
  1425. # now that we hava data, create the GUI interface and add it to the Tool Tab
  1426. self.build_ui(first_run=True)
  1427. # we activate this after the initial build as we don't need to see the tool been populated
  1428. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1429. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  1430. # and then add it to the storage elements (each storage elements is a member of a list
  1431. for tool_dia in self.points_edit:
  1432. storage_elem = FlatCAMGeoEditor.make_storage()
  1433. for point in self.points_edit[tool_dia]:
  1434. # make a '+' sign, the line length is the tool diameter
  1435. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  1436. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  1437. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  1438. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  1439. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  1440. if shape is not None:
  1441. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  1442. self.storage_dict[tool_dia] = storage_elem
  1443. self.replot()
  1444. # add a first tool in the Tool Table but only if the Excellon Object is empty
  1445. if not self.tool2tooldia:
  1446. self.on_tool_add(tooldia=1.00)
  1447. def update_fcexcellon(self, exc_obj):
  1448. """
  1449. Create a new Excellon object that contain the edited content of the source Excellon object
  1450. :param exc_obj: FlatCAMExcellon
  1451. :return: None
  1452. """
  1453. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  1454. # the values of this dict are coordinates of the holes (drills)
  1455. edited_points = {}
  1456. for storage_tooldia in self.storage_dict:
  1457. for x in self.storage_dict[storage_tooldia].get_objects():
  1458. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  1459. # each MultiLineString is made out of Linestrings
  1460. # select first Linestring object in the current MultiLineString
  1461. first_linestring = x.geo[0]
  1462. # get it's coordinates
  1463. first_linestring_coords = first_linestring.coords
  1464. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  1465. y_coord = first_linestring_coords[0][1]
  1466. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  1467. # edited_points dictionary
  1468. point = (x_coord, y_coord)
  1469. if not storage_tooldia in edited_points:
  1470. edited_points[storage_tooldia] = [point]
  1471. else:
  1472. edited_points[storage_tooldia].append(point)
  1473. # recreate the drills and tools to be added to the new Excellon edited object
  1474. # first, we look in the tool table if one of the tool diameters was changed then
  1475. # append that a tuple formed by (old_dia, edited_dia) to a list
  1476. changed_key = []
  1477. for initial_dia in self.olddia_newdia:
  1478. edited_dia = self.olddia_newdia[initial_dia]
  1479. if edited_dia != initial_dia:
  1480. for old_dia in edited_points:
  1481. if old_dia == initial_dia:
  1482. changed_key.append((old_dia, edited_dia))
  1483. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  1484. # (and we have to add it)
  1485. # because in case we have drill points it will have to be already added in edited_points
  1486. # if initial_dia not in edited_points.keys():
  1487. # edited_points[initial_dia] = []
  1488. for el in changed_key:
  1489. edited_points[el[1]] = edited_points.pop(el[0])
  1490. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  1491. # ordered_edited_points is a ordered list of tuples;
  1492. # element[0] of the tuple is the diameter and
  1493. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  1494. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  1495. current_tool = 0
  1496. for tool_dia in ordered_edited_points:
  1497. current_tool += 1
  1498. # create the self.tools for the new Excellon object (the one with edited content)
  1499. name = str(current_tool)
  1500. spec = {"C": float(tool_dia[0])}
  1501. self.new_tools[name] = spec
  1502. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  1503. self.new_tools[name]['solid_geometry'] = []
  1504. # create the self.drills for the new Excellon object (the one with edited content)
  1505. for point in tool_dia[1]:
  1506. self.new_drills.append(
  1507. {
  1508. 'point': Point(point),
  1509. 'tool': str(current_tool)
  1510. }
  1511. )
  1512. # repopulate the 'solid_geometry' for each tool
  1513. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  1514. self.new_tools[name]['solid_geometry'].append(poly)
  1515. if self.is_modified is True:
  1516. if "_edit" in self.edited_obj_name:
  1517. try:
  1518. id = int(self.edited_obj_name[-1]) + 1
  1519. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  1520. except ValueError:
  1521. self.edited_obj_name += "_1"
  1522. else:
  1523. self.edited_obj_name += "_edit"
  1524. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  1525. 'params': [self.edited_obj_name]})
  1526. if self.exc_obj.slots:
  1527. self.new_slots = self.exc_obj.slots
  1528. self.new_tool_offset = self.exc_obj.tool_offset
  1529. # reset the tool table
  1530. self.tools_table_exc.clear()
  1531. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1532. self.last_tool_selected = None
  1533. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  1534. self.app.collection.set_active(self.exc_obj.options['name'])
  1535. self.app.collection.delete_active()
  1536. # restore GUI to the Selected TAB
  1537. # Remove anything else in the GUI
  1538. self.app.ui.tool_scroll_area.takeWidget()
  1539. # Switch notebook to Selected page
  1540. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1541. def update_options(self, obj):
  1542. try:
  1543. if not obj.options:
  1544. obj.options = {}
  1545. obj.options['xmin'] = 0
  1546. obj.options['ymin'] = 0
  1547. obj.options['xmax'] = 0
  1548. obj.options['ymax'] = 0
  1549. return True
  1550. else:
  1551. return False
  1552. except AttributeError:
  1553. obj.options = {}
  1554. return True
  1555. def new_edited_excellon(self, outname):
  1556. """
  1557. Creates a new Excellon object for the edited Excellon. Thread-safe.
  1558. :param outname: Name of the resulting object. None causes the
  1559. name to be that of the file.
  1560. :type outname: str
  1561. :return: None
  1562. """
  1563. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  1564. self.exc_obj.options['name'])
  1565. # How the object should be initialized
  1566. def obj_init(excellon_obj, app_obj):
  1567. # self.progress.emit(20)
  1568. excellon_obj.drills = self.new_drills
  1569. excellon_obj.tools = self.new_tools
  1570. excellon_obj.slots = self.new_slots
  1571. excellon_obj.tool_offset = self.new_tool_offset
  1572. excellon_obj.options['name'] = outname
  1573. try:
  1574. excellon_obj.create_geometry()
  1575. except KeyError:
  1576. self.app.inform.emit(
  1577. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  1578. )
  1579. except:
  1580. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1581. msg += traceback.format_exc()
  1582. app_obj.inform.emit(msg)
  1583. raise
  1584. # raise
  1585. with self.app.proc_container.new(_("Creating Excellon.")):
  1586. try:
  1587. self.app.new_object("excellon", outname, obj_init)
  1588. except Exception as e:
  1589. log.error("Error on object creation: %s" % str(e))
  1590. self.app.progress.emit(100)
  1591. return
  1592. self.app.inform.emit(_("[success] Excellon editing finished."))
  1593. # self.progress.emit(100)
  1594. def on_tool_select(self, tool):
  1595. """
  1596. Behavior of the toolbar. Tool initialization.
  1597. :rtype : None
  1598. """
  1599. current_tool = tool
  1600. self.app.log.debug("on_tool_select('%s')" % tool)
  1601. if self.last_tool_selected is None and current_tool is not 'select':
  1602. # self.draw_app.select_tool('select')
  1603. self.complete = True
  1604. current_tool = 'select'
  1605. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  1606. # This is to make the group behave as radio group
  1607. if current_tool in self.tools_exc:
  1608. if self.tools_exc[current_tool]["button"].isChecked():
  1609. self.app.log.debug("%s is checked." % current_tool)
  1610. for t in self.tools_exc:
  1611. if t != current_tool:
  1612. self.tools_exc[t]["button"].setChecked(False)
  1613. # this is where the Editor toolbar classes (button's) are instantiated
  1614. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  1615. # self.app.inform.emit(self.active_tool.start_msg)
  1616. else:
  1617. self.app.log.debug("%s is NOT checked." % current_tool)
  1618. for t in self.tools_exc:
  1619. self.tools_exc[t]["button"].setChecked(False)
  1620. self.select_tool('select')
  1621. self.active_tool = FCDrillSelect(self)
  1622. def on_row_selected(self, row, col):
  1623. if col == 0:
  1624. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1625. if self.app.defaults["global_mselect_key"] == 'Control':
  1626. modifier_to_use = Qt.ControlModifier
  1627. else:
  1628. modifier_to_use = Qt.ShiftModifier
  1629. if key_modifier == modifier_to_use:
  1630. pass
  1631. else:
  1632. self.selected = []
  1633. try:
  1634. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  1635. self.last_tool_selected = copy(self.tools_table_exc.currentRow()) + 1
  1636. for obj in self.storage_dict[selected_dia].get_objects():
  1637. self.selected.append(obj)
  1638. except Exception as e:
  1639. self.app.log.debug(str(e))
  1640. self.replot()
  1641. def toolbar_tool_toggle(self, key):
  1642. self.options[key] = self.sender().isChecked()
  1643. if self.options[key] == True:
  1644. return 1
  1645. else:
  1646. return 0
  1647. def on_canvas_click(self, event):
  1648. """
  1649. event.x and .y have canvas coordinates
  1650. event.xdaya and .ydata have plot coordinates
  1651. :param event: Event object dispatched by Matplotlib
  1652. :return: None
  1653. """
  1654. if event.button is 1:
  1655. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1656. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  1657. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1658. ### Snap coordinates
  1659. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  1660. self.pos = (x, y)
  1661. # print(self.active_tool)
  1662. # Selection with left mouse button
  1663. if self.active_tool is not None and event.button is 1:
  1664. # Dispatch event to active_tool
  1665. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1666. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  1667. # If it is a shape generating tool
  1668. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  1669. if self.current_storage is not None:
  1670. self.on_exc_shape_complete(self.current_storage)
  1671. self.build_ui()
  1672. # MS: always return to the Select Tool if modifier key is not pressed
  1673. # else return to the current tool
  1674. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1675. if self.app.defaults["global_mselect_key"] == 'Control':
  1676. modifier_to_use = Qt.ControlModifier
  1677. else:
  1678. modifier_to_use = Qt.ShiftModifier
  1679. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1680. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1681. if key_modifier == modifier_to_use:
  1682. self.select_tool(self.active_tool.name)
  1683. else:
  1684. self.select_tool("select")
  1685. return
  1686. if isinstance(self.active_tool, FCDrillSelect):
  1687. # self.app.log.debug("Replotting after click.")
  1688. self.replot()
  1689. else:
  1690. self.app.log.debug("No active tool to respond to click!")
  1691. def on_exc_shape_complete(self, storage):
  1692. self.app.log.debug("on_shape_complete()")
  1693. # Add shape
  1694. if type(storage) is list:
  1695. for item_storage in storage:
  1696. self.add_exc_shape(self.active_tool.geometry, item_storage)
  1697. else:
  1698. self.add_exc_shape(self.active_tool.geometry, storage)
  1699. # Remove any utility shapes
  1700. self.delete_utility_geometry()
  1701. self.tool_shape.clear(update=True)
  1702. # Replot and reset tool.
  1703. self.replot()
  1704. # self.active_tool = type(self.active_tool)(self)
  1705. def add_exc_shape(self, shape, storage):
  1706. """
  1707. Adds a shape to the shape storage.
  1708. :param shape: Shape to be added.
  1709. :type shape: DrawToolShape
  1710. :return: None
  1711. """
  1712. # List of DrawToolShape?
  1713. if isinstance(shape, list):
  1714. for subshape in shape:
  1715. self.add_exc_shape(subshape, storage)
  1716. return
  1717. assert isinstance(shape, DrawToolShape), \
  1718. "Expected a DrawToolShape, got %s" % str(type(shape))
  1719. assert shape.geo is not None, \
  1720. "Shape object has empty geometry (None)"
  1721. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1722. not isinstance(shape.geo, list), \
  1723. "Shape objects has empty geometry ([])"
  1724. if isinstance(shape, DrawToolUtilityShape):
  1725. self.utility.append(shape)
  1726. else:
  1727. storage.insert(shape) # TODO: Check performance
  1728. def add_shape(self, shape):
  1729. """
  1730. Adds a shape to the shape storage.
  1731. :param shape: Shape to be added.
  1732. :type shape: DrawToolShape
  1733. :return: None
  1734. """
  1735. # List of DrawToolShape?
  1736. if isinstance(shape, list):
  1737. for subshape in shape:
  1738. self.add_shape(subshape)
  1739. return
  1740. assert isinstance(shape, DrawToolShape), \
  1741. "Expected a DrawToolShape, got %s" % type(shape)
  1742. assert shape.geo is not None, \
  1743. "Shape object has empty geometry (None)"
  1744. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1745. not isinstance(shape.geo, list), \
  1746. "Shape objects has empty geometry ([])"
  1747. if isinstance(shape, DrawToolUtilityShape):
  1748. self.utility.append(shape)
  1749. else:
  1750. self.storage.insert(shape) # TODO: Check performance
  1751. def on_exc_click_release(self, event):
  1752. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  1753. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  1754. if self.app.grid_status():
  1755. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  1756. else:
  1757. pos = (pos_canvas[0], pos_canvas[1])
  1758. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  1759. # canvas menu
  1760. try:
  1761. if event.button == 2: # right click
  1762. if self.app.panning_action is True:
  1763. self.app.panning_action = False
  1764. else:
  1765. self.app.cursor = QtGui.QCursor()
  1766. self.app.ui.popMenu.popup(self.app.cursor.pos())
  1767. except Exception as e:
  1768. log.warning("Error: %s" % str(e))
  1769. raise
  1770. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  1771. # selection and then select a type of selection ("enclosing" or "touching")
  1772. try:
  1773. if event.button == 1: # left click
  1774. if self.app.selection_type is not None:
  1775. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  1776. self.app.selection_type = None
  1777. elif isinstance(self.active_tool, FCDrillSelect):
  1778. # Dispatch event to active_tool
  1779. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1780. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  1781. # self.app.inform.emit(msg)
  1782. self.active_tool.click_release((self.pos[0], self.pos[1]))
  1783. self.replot()
  1784. except Exception as e:
  1785. log.warning("Error: %s" % str(e))
  1786. raise
  1787. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  1788. """
  1789. :param start_pos: mouse position when the selection LMB click was done
  1790. :param end_pos: mouse position when the left mouse button is released
  1791. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1792. :type Bool
  1793. :return:
  1794. """
  1795. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1796. self.app.delete_selection_shape()
  1797. for storage in self.storage_dict:
  1798. for obj in self.storage_dict[storage].get_objects():
  1799. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  1800. (sel_type is False and poly_selection.intersects(obj.geo)):
  1801. if self.key == self.app.defaults["global_mselect_key"]:
  1802. if obj in self.selected:
  1803. self.selected.remove(obj)
  1804. else:
  1805. # add the object to the selected shapes
  1806. self.selected.append(obj)
  1807. else:
  1808. self.selected.append(obj)
  1809. try:
  1810. self.tools_table_exc.cellPressed.disconnect()
  1811. except:
  1812. pass
  1813. # select the diameter of the selected shape in the tool table
  1814. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1815. for storage in self.storage_dict:
  1816. for shape_s in self.selected:
  1817. if shape_s in self.storage_dict[storage].get_objects():
  1818. for key in self.tool2tooldia:
  1819. if self.tool2tooldia[key] == storage:
  1820. item = self.tools_table_exc.item((key - 1), 1)
  1821. self.tools_table_exc.setCurrentItem(item)
  1822. self.last_tool_selected = key
  1823. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1824. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1825. self.replot()
  1826. def on_canvas_move(self, event):
  1827. """
  1828. Called on 'mouse_move' event
  1829. event.pos have canvas screen coordinates
  1830. :param event: Event object dispatched by VisPy SceneCavas
  1831. :return: None
  1832. """
  1833. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1834. event.xdata, event.ydata = pos[0], pos[1]
  1835. self.x = event.xdata
  1836. self.y = event.ydata
  1837. # Prevent updates on pan
  1838. # if len(event.buttons) > 0:
  1839. # return
  1840. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  1841. if event.button == 2:
  1842. self.app.panning_action = True
  1843. return
  1844. else:
  1845. self.app.panning_action = False
  1846. try:
  1847. x = float(event.xdata)
  1848. y = float(event.ydata)
  1849. except TypeError:
  1850. return
  1851. if self.active_tool is None:
  1852. return
  1853. ### Snap coordinates
  1854. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  1855. self.snap_x = x
  1856. self.snap_y = y
  1857. # update the position label in the infobar since the APP mouse event handlers are disconnected
  1858. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1859. "<b>Y</b>: %.4f" % (x, y))
  1860. if self.pos is None:
  1861. self.pos = (0, 0)
  1862. dx = x - self.pos[0]
  1863. dy = y - self.pos[1]
  1864. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  1865. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1866. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1867. ### Utility geometry (animated)
  1868. geo = self.active_tool.utility_geometry(data=(x, y))
  1869. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  1870. # Remove any previous utility shape
  1871. self.tool_shape.clear(update=True)
  1872. self.draw_utility_geometry(geo=geo)
  1873. ### Selection area on canvas section ###
  1874. dx = pos[0] - self.pos[0]
  1875. if event.is_dragging == 1 and event.button == 1:
  1876. self.app.delete_selection_shape()
  1877. if dx < 0:
  1878. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  1879. color=self.app.defaults["global_alt_sel_line"],
  1880. face_color=self.app.defaults['global_alt_sel_fill'])
  1881. self.app.selection_type = False
  1882. else:
  1883. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  1884. self.app.selection_type = True
  1885. else:
  1886. self.app.selection_type = None
  1887. # Update cursor
  1888. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  1889. def on_canvas_key_release(self, event):
  1890. self.key = None
  1891. def draw_utility_geometry(self, geo):
  1892. # Add the new utility shape
  1893. try:
  1894. # this case is for the Font Parse
  1895. for el in list(geo.geo):
  1896. if type(el) == MultiPolygon:
  1897. for poly in el:
  1898. self.tool_shape.add(
  1899. shape=poly,
  1900. color=(self.app.defaults["global_draw_color"] + '80'),
  1901. update=False,
  1902. layer=0,
  1903. tolerance=None
  1904. )
  1905. elif type(el) == MultiLineString:
  1906. for linestring in el:
  1907. self.tool_shape.add(
  1908. shape=linestring,
  1909. color=(self.app.defaults["global_draw_color"] + '80'),
  1910. update=False,
  1911. layer=0,
  1912. tolerance=None
  1913. )
  1914. else:
  1915. self.tool_shape.add(
  1916. shape=el,
  1917. color=(self.app.defaults["global_draw_color"] + '80'),
  1918. update=False,
  1919. layer=0,
  1920. tolerance=None
  1921. )
  1922. except TypeError:
  1923. self.tool_shape.add(
  1924. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  1925. update=False, layer=0, tolerance=None)
  1926. self.tool_shape.redraw()
  1927. def replot(self):
  1928. self.plot_all()
  1929. def plot_all(self):
  1930. """
  1931. Plots all shapes in the editor.
  1932. :return: None
  1933. :rtype: None
  1934. """
  1935. # self.app.log.debug("plot_all()")
  1936. self.shapes.clear(update=True)
  1937. for storage in self.storage_dict:
  1938. for shape_plus in self.storage_dict[storage].get_objects():
  1939. if shape_plus.geo is None:
  1940. continue
  1941. if shape_plus in self.selected:
  1942. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  1943. linewidth=2)
  1944. continue
  1945. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  1946. # for shape in self.storage.get_objects():
  1947. # if shape.geo is None: # TODO: This shouldn't have happened
  1948. # continue
  1949. #
  1950. # if shape in self.selected:
  1951. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  1952. # continue
  1953. #
  1954. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  1955. for shape in self.utility:
  1956. self.plot_shape(geometry=shape.geo, linewidth=1)
  1957. continue
  1958. self.shapes.redraw()
  1959. def plot_shape(self, geometry=None, color='black', linewidth=1):
  1960. """
  1961. Plots a geometric object or list of objects without rendering. Plotted objects
  1962. are returned as a list. This allows for efficient/animated rendering.
  1963. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  1964. :param color: Shape color
  1965. :param linewidth: Width of lines in # of pixels.
  1966. :return: List of plotted elements.
  1967. """
  1968. plot_elements = []
  1969. if geometry is None:
  1970. geometry = self.active_tool.geometry
  1971. try:
  1972. for geo in geometry:
  1973. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  1974. ## Non-iterable
  1975. except TypeError:
  1976. ## DrawToolShape
  1977. if isinstance(geometry, DrawToolShape):
  1978. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  1979. ## Polygon: Descend into exterior and each interior.
  1980. if type(geometry) == Polygon:
  1981. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  1982. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  1983. if type(geometry) == LineString or type(geometry) == LinearRing:
  1984. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  1985. if type(geometry) == Point:
  1986. pass
  1987. return plot_elements
  1988. def on_shape_complete(self):
  1989. self.app.log.debug("on_shape_complete()")
  1990. # Add shape
  1991. self.add_shape(self.active_tool.geometry)
  1992. # Remove any utility shapes
  1993. self.delete_utility_geometry()
  1994. self.tool_shape.clear(update=True)
  1995. # Replot and reset tool.
  1996. self.replot()
  1997. # self.active_tool = type(self.active_tool)(self)
  1998. def get_selected(self):
  1999. """
  2000. Returns list of shapes that are selected in the editor.
  2001. :return: List of shapes.
  2002. """
  2003. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2004. return self.selected
  2005. def delete_selected(self):
  2006. temp_ref = [s for s in self.selected]
  2007. for shape_sel in temp_ref:
  2008. self.delete_shape(shape_sel)
  2009. self.selected = []
  2010. self.build_ui()
  2011. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  2012. def delete_shape(self, shape):
  2013. self.is_modified = True
  2014. if shape in self.utility:
  2015. self.utility.remove(shape)
  2016. return
  2017. for storage in self.storage_dict:
  2018. # try:
  2019. # self.storage_dict[storage].remove(shape)
  2020. # except:
  2021. # pass
  2022. if shape in self.storage_dict[storage].get_objects():
  2023. self.storage_dict[storage].remove(shape)
  2024. # a hack to make the tool_table display less drills per diameter
  2025. # self.points_edit it's only useful first time when we load the data into the storage
  2026. # but is still used as referecen when building tool_table in self.build_ui()
  2027. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2028. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  2029. del self.points_edit[storage][0]
  2030. if shape in self.selected:
  2031. self.selected.remove(shape) # TODO: Check performance
  2032. def delete_utility_geometry(self):
  2033. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2034. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2035. for_deletion = [shape for shape in self.utility]
  2036. for shape in for_deletion:
  2037. self.delete_shape(shape)
  2038. self.tool_shape.clear(update=True)
  2039. self.tool_shape.redraw()
  2040. def on_delete_btn(self):
  2041. self.delete_selected()
  2042. self.replot()
  2043. def select_tool(self, toolname):
  2044. """
  2045. Selects a drawing tool. Impacts the object and GUI.
  2046. :param toolname: Name of the tool.
  2047. :return: None
  2048. """
  2049. self.tools_exc[toolname]["button"].setChecked(True)
  2050. self.on_tool_select(toolname)
  2051. def set_selected(self, shape):
  2052. # Remove and add to the end.
  2053. if shape in self.selected:
  2054. self.selected.remove(shape)
  2055. self.selected.append(shape)
  2056. def set_unselected(self, shape):
  2057. if shape in self.selected:
  2058. self.selected.remove(shape)
  2059. def on_array_type_combo(self):
  2060. if self.array_type_combo.currentIndex() == 0:
  2061. self.array_circular_frame.hide()
  2062. self.array_linear_frame.show()
  2063. else:
  2064. self.delete_utility_geometry()
  2065. self.array_circular_frame.show()
  2066. self.array_linear_frame.hide()
  2067. self.app.inform.emit(_("Click on the circular array Center position"))
  2068. def on_linear_angle_radio(self):
  2069. val = self.drill_axis_radio.get_value()
  2070. if val == 'A':
  2071. self.linear_angle_spinner.show()
  2072. self.linear_angle_label.show()
  2073. else:
  2074. self.linear_angle_spinner.hide()
  2075. self.linear_angle_label.hide()
  2076. def exc_add_drill(self):
  2077. self.select_tool('add')
  2078. return
  2079. def exc_add_drill_array(self):
  2080. self.select_tool('add_array')
  2081. return
  2082. def exc_resize_drills(self):
  2083. self.select_tool('resize')
  2084. return
  2085. def exc_copy_drills(self):
  2086. self.select_tool('copy')
  2087. return
  2088. def exc_move_drills(self):
  2089. self.select_tool('move')
  2090. return