FlatCAMExcEditor.py 109 KB

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