FlatCAMExcEditor.py 104 KB

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