FlatCAMExcEditor.py 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  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. import builtins
  15. fcTranslate.apply_language('strings')
  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(_("Click to place ..."))
  28. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  29. # as a visual marker, select again in tooltable the actual tool that we are using
  30. # remember that it was deselected when clicking on canvas
  31. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  32. self.draw_app.tools_table_exc.setCurrentItem(item)
  33. except KeyError:
  34. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  35. self.draw_app.select_tool("drill_select")
  36. return
  37. try:
  38. QtGui.QGuiApplication.restoreOverrideCursor()
  39. except Exception as e:
  40. pass
  41. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill.png'))
  42. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  43. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  44. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  45. self.draw_app.draw_utility_geometry(geo=geo)
  46. self.draw_app.app.inform.emit(_("Click to place ..."))
  47. # Switch notebook to Selected page
  48. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  49. def click(self, point):
  50. self.make()
  51. return "Done."
  52. def utility_geometry(self, data=None):
  53. self.points = data
  54. return DrawToolUtilityShape(self.util_shape(data))
  55. def util_shape(self, point):
  56. if point[0] is None and point[1] is None:
  57. point_x = self.draw_app.x
  58. point_y = self.draw_app.y
  59. else:
  60. point_x = point[0]
  61. point_y = point[1]
  62. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  63. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  64. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  65. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  66. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  67. def make(self):
  68. try:
  69. QtGui.QGuiApplication.restoreOverrideCursor()
  70. except Exception as e:
  71. pass
  72. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  73. # to the value, as a list of itself
  74. if self.selected_dia in self.draw_app.points_edit:
  75. self.draw_app.points_edit[self.selected_dia].append(self.points)
  76. else:
  77. self.draw_app.points_edit[self.selected_dia] = [self.points]
  78. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  79. self.geometry = DrawToolShape(self.util_shape(self.points))
  80. self.draw_app.in_action = False
  81. self.complete = True
  82. self.draw_app.app.inform.emit(_("[success] Done. Drill added."))
  83. class FCDrillArray(FCShapeTool):
  84. """
  85. Resulting type: MultiLineString
  86. """
  87. def __init__(self, draw_app):
  88. DrawTool.__init__(self, draw_app)
  89. self.name = 'drill_array'
  90. self.draw_app.array_frame.show()
  91. self.selected_dia = None
  92. self.drill_axis = 'X'
  93. self.drill_array = 'linear'
  94. self.drill_array_size = None
  95. self.drill_pitch = None
  96. self.drill_linear_angle = None
  97. self.drill_angle = None
  98. self.drill_direction = None
  99. self.drill_radius = None
  100. self.origin = None
  101. self.destination = None
  102. self.flag_for_circ_array = None
  103. self.last_dx = 0
  104. self.last_dy = 0
  105. self.pt = []
  106. try:
  107. self.draw_app.app.inform.emit(_("Click to place ..."))
  108. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  109. # as a visual marker, select again in tooltable the actual tool that we are using
  110. # remember that it was deselected when clicking on canvas
  111. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  112. self.draw_app.tools_table_exc.setCurrentItem(item)
  113. except KeyError:
  114. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  115. return
  116. try:
  117. QtGui.QGuiApplication.restoreOverrideCursor()
  118. except Exception as e:
  119. pass
  120. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill_array.png'))
  121. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  122. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  123. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  124. self.draw_app.draw_utility_geometry(geo=geo)
  125. self.draw_app.app.inform.emit(_("Click on target location ..."))
  126. # Switch notebook to Selected page
  127. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  128. def click(self, point):
  129. if self.drill_array == 'Linear':
  130. self.make()
  131. return
  132. else:
  133. if self.flag_for_circ_array is None:
  134. self.draw_app.in_action = True
  135. self.pt.append(point)
  136. self.flag_for_circ_array = True
  137. self.set_origin(point)
  138. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  139. else:
  140. self.destination = point
  141. self.make()
  142. self.flag_for_circ_array = None
  143. return
  144. def set_origin(self, origin):
  145. self.origin = origin
  146. def utility_geometry(self, data=None, static=None):
  147. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  148. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  149. self.drill_array = self.draw_app.array_type_combo.get_value()
  150. try:
  151. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  152. try:
  153. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  154. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  155. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  156. except TypeError:
  157. self.draw_app.app.inform.emit(
  158. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  159. return
  160. except Exception as e:
  161. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value. %s") % str(e))
  162. return
  163. if self.drill_array == 'Linear':
  164. if data[0] is None and data[1] is None:
  165. dx = self.draw_app.x
  166. dy = self.draw_app.y
  167. else:
  168. dx = data[0]
  169. dy = data[1]
  170. geo_list = []
  171. geo = None
  172. self.points = [dx, dy]
  173. for item in range(self.drill_array_size):
  174. if self.drill_axis == 'X':
  175. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  176. if self.drill_axis == 'Y':
  177. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  178. if self.drill_axis == 'A':
  179. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  180. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  181. geo = self.util_shape(
  182. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  183. )
  184. if static is None or static is False:
  185. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  186. else:
  187. geo_list.append(geo)
  188. # self.origin = data
  189. self.last_dx = dx
  190. self.last_dy = dy
  191. return DrawToolUtilityShape(geo_list)
  192. else:
  193. if data[0] is None and data[1] is None:
  194. cdx = self.draw_app.x
  195. cdy = self.draw_app.y
  196. else:
  197. cdx = data[0]
  198. cdy = data[1]
  199. if len(self.pt) > 0:
  200. temp_points = [x for x in self.pt]
  201. temp_points.append([cdx, cdy])
  202. return DrawToolUtilityShape(LineString(temp_points))
  203. def util_shape(self, point):
  204. if point[0] is None and point[1] is None:
  205. point_x = self.draw_app.x
  206. point_y = self.draw_app.y
  207. else:
  208. point_x = point[0]
  209. point_y = point[1]
  210. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  211. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  212. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  213. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  214. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  215. def make(self):
  216. self.geometry = []
  217. geo = None
  218. try:
  219. QtGui.QGuiApplication.restoreOverrideCursor()
  220. except Exception as e:
  221. pass
  222. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  223. # to the value, as a list of itself
  224. if self.selected_dia not in self.draw_app.points_edit:
  225. self.draw_app.points_edit[self.selected_dia] = []
  226. for i in range(self.drill_array_size):
  227. self.draw_app.points_edit[self.selected_dia].append(self.points)
  228. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  229. if self.drill_array == 'Linear':
  230. for item in range(self.drill_array_size):
  231. if self.drill_axis == 'X':
  232. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  233. if self.drill_axis == 'Y':
  234. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  235. if self.drill_axis == 'A':
  236. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  237. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  238. geo = self.util_shape(
  239. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  240. )
  241. self.geometry.append(DrawToolShape(geo))
  242. else:
  243. if (self.drill_angle * self.drill_array_size) > 360:
  244. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many drills for the selected spacing angle."))
  245. return
  246. radius = distance(self.destination, self.origin)
  247. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  248. for i in range(self.drill_array_size):
  249. angle_radians = math.radians(self.drill_angle * i)
  250. if self.drill_direction == 'CW':
  251. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  252. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  253. else:
  254. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  255. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  256. geo = self.util_shape((x, y))
  257. self.geometry.append(DrawToolShape(geo))
  258. self.complete = True
  259. self.draw_app.app.inform.emit(_("[success] Done. Drill Array added."))
  260. self.draw_app.in_action = False
  261. self.draw_app.array_frame.hide()
  262. return
  263. class FCSlot(FCShapeTool):
  264. """
  265. Resulting type: Polygon
  266. """
  267. def __init__(self, draw_app):
  268. DrawTool.__init__(self, draw_app)
  269. self.name = 'drill_slot'
  270. self.draw_app = draw_app
  271. self.draw_app.slot_frame.show()
  272. self.selected_dia = None
  273. try:
  274. self.draw_app.app.inform.emit(_("Click to place ..."))
  275. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  276. # as a visual marker, select again in tooltable the actual tool that we are using
  277. # remember that it was deselected when clicking on canvas
  278. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  279. self.draw_app.tools_table_exc.setCurrentItem(item)
  280. except KeyError:
  281. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a slot first select a tool"))
  282. self.draw_app.select_tool("drill_select")
  283. return
  284. try:
  285. QtGui.QGuiApplication.restoreOverrideCursor()
  286. except Exception as e:
  287. pass
  288. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_slot.png'))
  289. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  290. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  291. self.half_height = 0.0
  292. self.half_width = 0.0
  293. self.radius = float(self.selected_dia / 2.0)
  294. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  295. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  296. self.draw_app.draw_utility_geometry(geo=geo)
  297. self.draw_app.app.inform.emit(_("Click to place ..."))
  298. # Switch notebook to Selected page
  299. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  300. def click(self, point):
  301. self.make()
  302. return "Done."
  303. def utility_geometry(self, data=None):
  304. self.points = data
  305. geo_data = self.util_shape(data)
  306. if geo_data:
  307. return DrawToolUtilityShape(geo_data)
  308. else:
  309. return None
  310. def util_shape(self, point):
  311. if point is None:
  312. return
  313. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  314. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  315. self.radius = float(self.selected_dia / 2.0)
  316. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  317. try:
  318. slot_length = float(self.draw_app.slot_length_entry.get_value())
  319. except ValueError:
  320. # try to convert comma to decimal point. if it's still not working error message and return
  321. try:
  322. slot_length = float(self.draw_app.slot_length_entry.get_value().replace(',', '.'))
  323. self.draw_app.slot_length_entry.set_value(slot_length)
  324. except ValueError:
  325. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  326. "Add it and retry."))
  327. return
  328. try:
  329. slot_angle = float(self.draw_app.slot_angle_spinner.get_value())
  330. except ValueError:
  331. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  332. "Add it and retry."))
  333. return
  334. if self.draw_app.slot_axis_radio.get_value() == 'X':
  335. self.half_width = slot_length / 2.0
  336. self.half_height = self.radius
  337. else:
  338. self.half_width = self.radius
  339. self.half_height = slot_length / 2.0
  340. if point[0] is None and point[1] is None:
  341. point_x = self.draw_app.x
  342. point_y = self.draw_app.y
  343. else:
  344. point_x = point[0]
  345. point_y = point[1]
  346. geo = []
  347. if self.half_height > self.half_width:
  348. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  349. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  350. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  351. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  352. down_center = [point_x, point_y - self.half_height + self.half_width]
  353. d_start_angle = math.pi
  354. d_stop_angle = 0.0
  355. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  356. up_center = [point_x, point_y + self.half_height - self.half_width]
  357. u_start_angle = 0.0
  358. u_stop_angle = math.pi
  359. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  360. geo.append(p1)
  361. for pt in down_arc:
  362. geo.append(pt)
  363. geo.append(p2)
  364. geo.append(p3)
  365. for pt in up_arc:
  366. geo.append(pt)
  367. geo.append(p4)
  368. if self.draw_app.slot_axis_radio.get_value() == 'A':
  369. return affinity.rotate(geom=Polygon(geo), angle=-slot_angle)
  370. else:
  371. return Polygon(geo)
  372. else:
  373. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  374. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  375. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  376. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  377. left_center = [point_x - self.half_width + self.half_height, point_y]
  378. d_start_angle = math.pi / 2
  379. d_stop_angle = 1.5 * math.pi
  380. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  381. right_center = [point_x + self.half_width - self.half_height, point_y]
  382. u_start_angle = 1.5 * math.pi
  383. u_stop_angle = math.pi / 2
  384. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  385. geo.append(p1)
  386. geo.append(p2)
  387. for pt in right_arc:
  388. geo.append(pt)
  389. geo.append(p3)
  390. geo.append(p4)
  391. for pt in left_arc:
  392. geo.append(pt)
  393. return Polygon(geo)
  394. def make(self):
  395. try:
  396. QtGui.QGuiApplication.restoreOverrideCursor()
  397. except Exception as e:
  398. pass
  399. try:
  400. self.geometry = DrawToolShape(self.util_shape(self.points))
  401. except Exception as e:
  402. log.debug("FCSlot.make() --> %s" % str(e))
  403. # add the point to drills/slots if the diameter is a key in the dict, if not, create it add the drill location
  404. # to the value, as a list of itself
  405. if self.selected_dia in self.draw_app.slot_points_edit:
  406. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  407. else:
  408. self.draw_app.slot_points_edit[self.selected_dia] = [self.points]
  409. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  410. self.draw_app.in_action = False
  411. self.complete = True
  412. self.draw_app.app.inform.emit(_("[success] Done. Adding Slot completed."))
  413. self.draw_app.slot_frame.hide()
  414. class FCSlotArray(FCShapeTool):
  415. """
  416. Resulting type: MultiPolygon
  417. """
  418. def __init__(self, draw_app):
  419. DrawTool.__init__(self, draw_app)
  420. self.name = 'drill_slotarray'
  421. self.draw_app = draw_app
  422. try:
  423. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  424. except KeyError:
  425. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Slot Array first select a tool in Tools Table"))
  426. self.complete = True
  427. self.draw_app.in_action = False
  428. self.draw_app.slot_array_frame.hide()
  429. return
  430. if self.radius == 0:
  431. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Aperture size is zero. It needs to be greater than zero."))
  432. self.dont_execute = True
  433. return
  434. else:
  435. self.dont_execute = False
  436. try:
  437. QtGui.QGuiApplication.restoreOverrideCursor()
  438. except Exception as e:
  439. pass
  440. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_array.png'))
  441. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  442. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  443. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  444. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  445. try:
  446. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  447. except KeyError:
  448. pass
  449. try:
  450. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  451. except KeyError:
  452. pass
  453. self.draw_app.slot_array_frame.show()
  454. self.selected_size = None
  455. self.pad_axis = 'X'
  456. self.pad_array = 'linear'
  457. self.pad_array_size = None
  458. self.pad_pitch = None
  459. self.pad_linear_angle = None
  460. self.pad_angle = None
  461. self.pad_direction = None
  462. self.pad_radius = None
  463. self.origin = None
  464. self.destination = None
  465. self.flag_for_circ_array = None
  466. self.last_dx = 0
  467. self.last_dy = 0
  468. self.pt = []
  469. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  470. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  471. self.draw_app.draw_utility_geometry(geo=geo)
  472. self.draw_app.app.inform.emit(_("Click on target location ..."))
  473. # Switch notebook to Selected page
  474. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  475. def click(self, point):
  476. if self.pad_array == 'Linear':
  477. self.make()
  478. return
  479. else:
  480. if self.flag_for_circ_array is None:
  481. self.draw_app.in_action = True
  482. self.pt.append(point)
  483. self.flag_for_circ_array = True
  484. self.set_origin(point)
  485. self.draw_app.app.inform.emit(_("Click on the Pad Circular Array Start position"))
  486. else:
  487. self.destination = point
  488. self.make()
  489. self.flag_for_circ_array = None
  490. return
  491. def set_origin(self, origin):
  492. self.origin = origin
  493. def utility_geometry(self, data=None, static=None):
  494. if self.dont_execute is True:
  495. self.draw_app.select_tool('select')
  496. return
  497. self.pad_axis = self.draw_app.pad_axis_radio.get_value()
  498. self.pad_direction = self.draw_app.pad_direction_radio.get_value()
  499. self.pad_array = self.draw_app.array_type_combo.get_value()
  500. try:
  501. self.pad_array_size = int(self.draw_app.pad_array_size_entry.get_value())
  502. try:
  503. self.pad_pitch = float(self.draw_app.pad_pitch_entry.get_value())
  504. self.pad_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  505. self.pad_angle = float(self.draw_app.pad_angle_entry.get_value())
  506. except TypeError:
  507. self.draw_app.app.inform.emit(
  508. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  509. return
  510. except Exception as e:
  511. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  512. return
  513. if self.pad_array == 'Linear':
  514. if data[0] is None and data[1] is None:
  515. dx = self.draw_app.x
  516. dy = self.draw_app.y
  517. else:
  518. dx = data[0]
  519. dy = data[1]
  520. geo_el_list = []
  521. geo_el = []
  522. self.points = [dx, dy]
  523. for item in range(self.pad_array_size):
  524. if self.pad_axis == 'X':
  525. geo_el = self.util_shape(((dx + (self.pad_pitch * item)), dy))
  526. if self.pad_axis == 'Y':
  527. geo_el = self.util_shape((dx, (dy + (self.pad_pitch * item))))
  528. if self.pad_axis == 'A':
  529. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  530. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  531. geo_el = self.util_shape(
  532. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  533. )
  534. if static is None or static is False:
  535. new_geo_el = dict()
  536. if 'solid' in geo_el:
  537. new_geo_el['solid'] = affinity.translate(
  538. geo_el['solid'], xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)
  539. )
  540. if 'follow' in geo_el:
  541. new_geo_el['follow'] = affinity.translate(
  542. geo_el['follow'], xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)
  543. )
  544. geo_el_list.append(new_geo_el)
  545. else:
  546. geo_el_list.append(geo_el)
  547. # self.origin = data
  548. self.last_dx = dx
  549. self.last_dy = dy
  550. return DrawToolUtilityShape(geo_el_list)
  551. else:
  552. if data[0] is None and data[1] is None:
  553. cdx = self.draw_app.x
  554. cdy = self.draw_app.y
  555. else:
  556. cdx = data[0]
  557. cdy = data[1]
  558. if len(self.pt) > 0:
  559. temp_points = [x for x in self.pt]
  560. temp_points.append([cdx, cdy])
  561. return DrawToolUtilityShape(LineString(temp_points))
  562. def util_shape(self, point):
  563. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  564. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  565. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  566. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  567. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  568. try:
  569. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  570. except KeyError:
  571. pass
  572. try:
  573. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  574. except KeyError:
  575. pass
  576. if point[0] is None and point[1] is None:
  577. point_x = self.draw_app.x
  578. point_y = self.draw_app.y
  579. else:
  580. point_x = point[0]
  581. point_y = point[1]
  582. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  583. if ap_type == 'C':
  584. new_geo_el = dict()
  585. center = Point([point_x, point_y])
  586. new_geo_el['solid'] = center.buffer(self.radius)
  587. new_geo_el['follow'] = center
  588. return new_geo_el
  589. elif ap_type == 'R':
  590. new_geo_el = dict()
  591. p1 = (point_x - self.half_width, point_y - self.half_height)
  592. p2 = (point_x + self.half_width, point_y - self.half_height)
  593. p3 = (point_x + self.half_width, point_y + self.half_height)
  594. p4 = (point_x - self.half_width, point_y + self.half_height)
  595. new_geo_el['solid'] = Polygon([p1, p2, p3, p4, p1])
  596. new_geo_el['follow'] = Point([point_x, point_y])
  597. return new_geo_el
  598. elif ap_type == 'O':
  599. geo = []
  600. new_geo_el = dict()
  601. if self.half_height > self.half_width:
  602. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  603. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  604. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  605. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  606. down_center = [point_x, point_y - self.half_height + self.half_width]
  607. d_start_angle = math.pi
  608. d_stop_angle = 0.0
  609. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  610. up_center = [point_x, point_y + self.half_height - self.half_width]
  611. u_start_angle = 0.0
  612. u_stop_angle = math.pi
  613. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  614. geo.append(p1)
  615. for pt in down_arc:
  616. geo.append(pt)
  617. geo.append(p2)
  618. geo.append(p3)
  619. for pt in up_arc:
  620. geo.append(pt)
  621. geo.append(p4)
  622. new_geo_el['solid'] = Polygon(geo)
  623. center = Point([point_x, point_y])
  624. new_geo_el['follow'] = center
  625. return new_geo_el
  626. else:
  627. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  628. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  629. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  630. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  631. left_center = [point_x - self.half_width + self.half_height, point_y]
  632. d_start_angle = math.pi / 2
  633. d_stop_angle = 1.5 * math.pi
  634. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  635. right_center = [point_x + self.half_width - self.half_height, point_y]
  636. u_start_angle = 1.5 * math.pi
  637. u_stop_angle = math.pi / 2
  638. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  639. geo.append(p1)
  640. geo.append(p2)
  641. for pt in right_arc:
  642. geo.append(pt)
  643. geo.append(p3)
  644. geo.append(p4)
  645. for pt in left_arc:
  646. geo.append(pt)
  647. new_geo_el['solid'] = Polygon(geo)
  648. center = Point([point_x, point_y])
  649. new_geo_el['follow'] = center
  650. return new_geo_el
  651. else:
  652. self.draw_app.app.inform.emit(_(
  653. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  654. return None
  655. def make(self):
  656. self.geometry = []
  657. geo = None
  658. self.draw_app.current_storage = self.storage_obj
  659. if self.pad_array == 'Linear':
  660. for item in range(self.pad_array_size):
  661. if self.pad_axis == 'X':
  662. geo = self.util_shape(((self.points[0] + (self.pad_pitch * item)), self.points[1]))
  663. if self.pad_axis == 'Y':
  664. geo = self.util_shape((self.points[0], (self.points[1] + (self.pad_pitch * item))))
  665. if self.pad_axis == 'A':
  666. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  667. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  668. geo = self.util_shape(
  669. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  670. )
  671. self.geometry.append(DrawToolShape(geo))
  672. else:
  673. if (self.pad_angle * self.pad_array_size) > 360:
  674. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many Pads for the selected spacing angle."))
  675. return
  676. radius = distance(self.destination, self.origin)
  677. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  678. for i in range(self.pad_array_size):
  679. angle_radians = math.radians(self.pad_angle * i)
  680. if self.pad_direction == 'CW':
  681. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  682. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  683. else:
  684. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  685. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  686. geo = self.util_shape((x, y))
  687. if self.pad_direction == 'CW':
  688. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  689. else:
  690. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  691. self.geometry.append(DrawToolShape(geo))
  692. self.complete = True
  693. self.draw_app.app.inform.emit(_("[success] Done. Pad Array added."))
  694. self.draw_app.in_action = False
  695. self.draw_app.slot_array_frame.hide()
  696. return
  697. def clean_up(self):
  698. self.draw_app.selected = []
  699. self.draw_app.apertures_table.clearSelection()
  700. self.draw_app.plot_all()
  701. class FCDrillResize(FCShapeTool):
  702. def __init__(self, draw_app):
  703. DrawTool.__init__(self, draw_app)
  704. self.name = 'drill_resize'
  705. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  706. self.resize_dia = None
  707. self.draw_app.resize_frame.show()
  708. self.points = None
  709. self.selected_dia_list = []
  710. self.current_storage = None
  711. self.geometry = []
  712. self.destination_storage = None
  713. self.draw_app.resize_btn.clicked.connect(self.make)
  714. # Switch notebook to Selected page
  715. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  716. def make(self):
  717. self.draw_app.is_modified = True
  718. try:
  719. new_dia = self.draw_app.resdrill_entry.get_value()
  720. except:
  721. self.draw_app.app.inform.emit(
  722. _("[ERROR_NOTCL] Resize drill(s) failed. Please enter a diameter for resize.")
  723. )
  724. return
  725. if new_dia not in self.draw_app.olddia_newdia:
  726. self.destination_storage = FlatCAMGeoEditor.make_storage()
  727. self.draw_app.storage_dict[new_dia] = self.destination_storage
  728. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  729. # each time a tool diameter is edited or added
  730. self.draw_app.olddia_newdia[new_dia] = new_dia
  731. else:
  732. self.destination_storage = self.draw_app.storage_dict[new_dia]
  733. for index in self.draw_app.tools_table_exc.selectedIndexes():
  734. row = index.row()
  735. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  736. # therefore below we convert to float
  737. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  738. self.selected_dia_list.append(float(dia_on_row))
  739. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  740. # we add a new entry in the tool2tooldia dict
  741. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  742. sel_shapes_to_be_deleted = []
  743. if self.selected_dia_list:
  744. for sel_dia in self.selected_dia_list:
  745. self.current_storage = self.draw_app.storage_dict[sel_dia]
  746. for select_shape in self.draw_app.get_selected():
  747. if select_shape in self.current_storage.get_objects():
  748. factor = new_dia / sel_dia
  749. self.geometry.append(
  750. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  751. )
  752. self.current_storage.remove(select_shape)
  753. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  754. # self.points_edit it's only useful first time when we load the data into the storage
  755. # but is still used as reference when building tool_table in self.build_ui()
  756. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  757. # deleting self.points_edit elements (doesn't matter who but just the number)
  758. # solved the display issue.
  759. del self.draw_app.points_edit[sel_dia][0]
  760. sel_shapes_to_be_deleted.append(select_shape)
  761. self.draw_app.on_exc_shape_complete(self.destination_storage)
  762. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  763. # self.points_edit it's only useful first time when we load the data into the storage
  764. # but is still used as reference when building tool_table in self.build_ui()
  765. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  766. # deleting self.points_edit elements (doesn't matter who but just the number)
  767. # solved the display issue.
  768. if new_dia not in self.draw_app.points_edit:
  769. self.draw_app.points_edit[new_dia] = [(0, 0)]
  770. else:
  771. self.draw_app.points_edit[new_dia].append((0, 0))
  772. self.geometry = []
  773. # if following the resize of the drills there will be no more drills for the selected tool then
  774. # delete that tool
  775. if not self.draw_app.points_edit[sel_dia]:
  776. self.draw_app.on_tool_delete(sel_dia)
  777. for shp in sel_shapes_to_be_deleted:
  778. self.draw_app.selected.remove(shp)
  779. self.draw_app.build_ui()
  780. self.draw_app.replot()
  781. self.draw_app.app.inform.emit(_("[success] Done. Drill Resize completed."))
  782. else:
  783. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No drills selected for resize ..."))
  784. self.draw_app.resize_frame.hide()
  785. self.complete = True
  786. # MS: always return to the Select Tool
  787. self.draw_app.select_tool("drill_select")
  788. class FCDrillMove(FCShapeTool):
  789. def __init__(self, draw_app):
  790. DrawTool.__init__(self, draw_app)
  791. self.name = 'drill_move'
  792. # self.shape_buffer = self.draw_app.shape_buffer
  793. self.origin = None
  794. self.destination = None
  795. self.sel_limit = self.draw_app.app.defaults["excellon_editor_sel_limit"]
  796. self.selection_shape = self.selection_bbox()
  797. self.selected_dia_list = []
  798. if self.draw_app.launched_from_shortcuts is True:
  799. self.draw_app.launched_from_shortcuts = False
  800. self.draw_app.app.inform.emit(_("Click on target location ..."))
  801. else:
  802. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  803. self.current_storage = None
  804. self.geometry = []
  805. for index in self.draw_app.tools_table_exc.selectedIndexes():
  806. row = index.row()
  807. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  808. # therefore below we convert to float
  809. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  810. self.selected_dia_list.append(float(dia_on_row))
  811. # Switch notebook to Selected page
  812. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  813. def set_origin(self, origin):
  814. self.origin = origin
  815. def click(self, point):
  816. if len(self.draw_app.get_selected()) == 0:
  817. return "Nothing to move."
  818. if self.origin is None:
  819. self.set_origin(point)
  820. self.draw_app.app.inform.emit(_("Click on target location ..."))
  821. return
  822. else:
  823. self.destination = point
  824. self.make()
  825. # MS: always return to the Select Tool
  826. self.draw_app.select_tool("drill_select")
  827. return
  828. def make(self):
  829. # Create new geometry
  830. dx = self.destination[0] - self.origin[0]
  831. dy = self.destination[1] - self.origin[1]
  832. sel_shapes_to_be_deleted = []
  833. for sel_dia in self.selected_dia_list:
  834. self.current_storage = self.draw_app.storage_dict[sel_dia]
  835. for select_shape in self.draw_app.get_selected():
  836. if select_shape in self.current_storage.get_objects():
  837. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  838. self.current_storage.remove(select_shape)
  839. sel_shapes_to_be_deleted.append(select_shape)
  840. self.draw_app.on_exc_shape_complete(self.current_storage)
  841. self.geometry = []
  842. for shp in sel_shapes_to_be_deleted:
  843. self.draw_app.selected.remove(shp)
  844. sel_shapes_to_be_deleted = []
  845. self.draw_app.build_ui()
  846. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) Move completed."))
  847. def selection_bbox(self):
  848. geo_list = []
  849. for select_shape in self.draw_app.get_selected():
  850. geometric_data = select_shape.geo
  851. try:
  852. for g in geometric_data:
  853. geo_list.append(g)
  854. except TypeError:
  855. geo_list.append(geometric_data)
  856. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  857. pt1 = (xmin, ymin)
  858. pt2 = (xmax, ymin)
  859. pt3 = (xmax, ymax)
  860. pt4 = (xmin, ymax)
  861. return Polygon([pt1, pt2, pt3, pt4])
  862. def utility_geometry(self, data=None):
  863. """
  864. Temporary geometry on screen while using this tool.
  865. :param data:
  866. :return:
  867. """
  868. geo_list = []
  869. if self.origin is None:
  870. return None
  871. if len(self.draw_app.get_selected()) == 0:
  872. return None
  873. dx = data[0] - self.origin[0]
  874. dy = data[1] - self.origin[1]
  875. if len(self.draw_app.get_selected()) <= self.sel_limit:
  876. try:
  877. for geom in self.draw_app.get_selected():
  878. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  879. except AttributeError:
  880. self.draw_app.select_tool('drill_select')
  881. self.draw_app.selected = []
  882. return
  883. return DrawToolUtilityShape(geo_list)
  884. else:
  885. try:
  886. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  887. except ValueError:
  888. ss_el = None
  889. return DrawToolUtilityShape(ss_el)
  890. class FCDrillCopy(FCDrillMove):
  891. def __init__(self, draw_app):
  892. FCDrillMove.__init__(self, draw_app)
  893. self.name = 'drill_copy'
  894. def make(self):
  895. # Create new geometry
  896. dx = self.destination[0] - self.origin[0]
  897. dy = self.destination[1] - self.origin[1]
  898. sel_shapes_to_be_deleted = []
  899. for sel_dia in self.selected_dia_list:
  900. self.current_storage = self.draw_app.storage_dict[sel_dia]
  901. for select_shape in self.draw_app.get_selected():
  902. if select_shape in self.current_storage.get_objects():
  903. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  904. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  905. self.draw_app.points_edit[sel_dia].append((0, 0))
  906. sel_shapes_to_be_deleted.append(select_shape)
  907. self.draw_app.on_exc_shape_complete(self.current_storage)
  908. self.geometry = []
  909. for shp in sel_shapes_to_be_deleted:
  910. self.draw_app.selected.remove(shp)
  911. sel_shapes_to_be_deleted = []
  912. self.draw_app.build_ui()
  913. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) copied."))
  914. class FCDrillSelect(DrawTool):
  915. def __init__(self, exc_editor_app):
  916. DrawTool.__init__(self, exc_editor_app)
  917. self.name = 'drill_select'
  918. try:
  919. QtGui.QGuiApplication.restoreOverrideCursor()
  920. except Exception as e:
  921. pass
  922. self.exc_editor_app = exc_editor_app
  923. self.storage = self.exc_editor_app.storage_dict
  924. # self.selected = self.exc_editor_app.selected
  925. # here we store all shapes that were selected so we can search for the nearest to our click location
  926. self.sel_storage = FlatCAMExcEditor.make_storage()
  927. self.exc_editor_app.resize_frame.hide()
  928. self.exc_editor_app.array_frame.hide()
  929. self.exc_editor_app.slot_frame.hide()
  930. # self.exc_editor_app.slot_array_frame.hide()
  931. def click(self, point):
  932. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  933. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  934. if key_modifier == Qt.ControlModifier:
  935. pass
  936. else:
  937. self.exc_editor_app.selected = []
  938. else:
  939. if key_modifier == Qt.ShiftModifier:
  940. pass
  941. else:
  942. self.exc_editor_app.selected = []
  943. def click_release(self, pos):
  944. self.exc_editor_app.tools_table_exc.clearSelection()
  945. xmin, ymin, xmax, ymax = 0, 0, 0, 0
  946. try:
  947. for storage in self.exc_editor_app.storage_dict:
  948. for sh in self.exc_editor_app.storage_dict[storage].get_objects():
  949. self.sel_storage.insert(sh)
  950. _, closest_shape = self.sel_storage.nearest(pos)
  951. # constrain selection to happen only within a certain bounding box; it works only for MultiLineStrings
  952. if isinstance(closest_shape.geo, MultiLineString):
  953. x_coord, y_coord = closest_shape.geo[0].xy
  954. delta = (x_coord[1] - x_coord[0])
  955. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  956. xmin = x_coord[0] - (0.7 * delta)
  957. xmax = x_coord[0] + (1.7 * delta)
  958. ymin = y_coord[0] - (0.7 * delta)
  959. ymax = y_coord[0] + (1.7 * delta)
  960. elif isinstance(closest_shape.geo, Polygon):
  961. xmin, ymin, xmax, ymax = closest_shape.geo.bounds
  962. dx = xmax - xmin
  963. dy = ymax - ymin
  964. delta = dx if dx > dy else dy
  965. xmin -= 0.7 * delta
  966. xmax += 0.7 * delta
  967. ymin -= 0.7 * delta
  968. ymax += 0.7 * delta
  969. except StopIteration:
  970. return ""
  971. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  972. self.exc_editor_app.selected = []
  973. else:
  974. modifiers = QtWidgets.QApplication.keyboardModifiers()
  975. mod_key = 'Control'
  976. if modifiers == QtCore.Qt.ShiftModifier:
  977. mod_key = 'Shift'
  978. elif modifiers == QtCore.Qt.ControlModifier:
  979. mod_key = 'Control'
  980. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  981. if closest_shape in self.exc_editor_app.selected:
  982. self.exc_editor_app.selected.remove(closest_shape)
  983. else:
  984. self.exc_editor_app.selected.append(closest_shape)
  985. else:
  986. self.draw_app.selected = []
  987. self.draw_app.selected.append(closest_shape)
  988. # select the diameter of the selected shape in the tool table
  989. try:
  990. self.draw_app.tools_table_exc.cellPressed.disconnect()
  991. except (TypeError, AttributeError):
  992. pass
  993. sel_tools = set()
  994. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  995. for shape_s in self.exc_editor_app.selected:
  996. for storage in self.exc_editor_app.storage_dict:
  997. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  998. sel_tools.add(storage)
  999. for storage in sel_tools:
  1000. for k, v in self.draw_app.tool2tooldia.items():
  1001. if v == storage:
  1002. self.exc_editor_app.tools_table_exc.selectRow(int(k) - 1)
  1003. self.draw_app.last_tool_selected = int(k)
  1004. break
  1005. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1006. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  1007. # delete whatever is in selection storage, there is no longer need for those shapes
  1008. self.sel_storage = FlatCAMExcEditor.make_storage()
  1009. return ""
  1010. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1011. # for storage in self.exc_editor_app.storage_dict:
  1012. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1013. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1014. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1015. # over_shape_list.append(obj_shape)
  1016. #
  1017. # try:
  1018. # # if there is no shape under our click then deselect all shapes
  1019. # if not over_shape_list:
  1020. # self.exc_editor_app.selected = []
  1021. # FlatCAMExcEditor.draw_shape_idx = -1
  1022. # self.exc_editor_app.tools_table_exc.clearSelection()
  1023. # else:
  1024. # # if there are shapes under our click then advance through the list of them, one at the time in a
  1025. # # circular way
  1026. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  1027. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  1028. #
  1029. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  1030. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  1031. # if obj_to_add in self.exc_editor_app.selected:
  1032. # self.exc_editor_app.selected.remove(obj_to_add)
  1033. # else:
  1034. # self.exc_editor_app.selected.append(obj_to_add)
  1035. # else:
  1036. # self.exc_editor_app.selected = []
  1037. # self.exc_editor_app.selected.append(obj_to_add)
  1038. # else:
  1039. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1040. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  1041. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  1042. # if obj_to_add in self.exc_editor_app.selected:
  1043. # self.exc_editor_app.selected.remove(obj_to_add)
  1044. # else:
  1045. # self.exc_editor_app.selected.append(obj_to_add)
  1046. # else:
  1047. # self.exc_editor_app.selected = []
  1048. # self.exc_editor_app.selected.append(obj_to_add)
  1049. #
  1050. # for storage in self.exc_editor_app.storage_dict:
  1051. # for shape in self.exc_editor_app.selected:
  1052. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1053. # for key in self.exc_editor_app.tool2tooldia:
  1054. # if self.exc_editor_app.tool2tooldia[key] == storage:
  1055. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1056. # item.setSelected(True)
  1057. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1058. #
  1059. # except Exception as e:
  1060. # log.error("[ERROR] Something went bad. %s" % str(e))
  1061. # raise
  1062. class FlatCAMExcEditor(QtCore.QObject):
  1063. draw_shape_idx = -1
  1064. def __init__(self, app):
  1065. assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1066. super(FlatCAMExcEditor, self).__init__()
  1067. self.app = app
  1068. self.canvas = self.app.plotcanvas
  1069. # ## Current application units in Upper Case
  1070. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1071. self.exc_edit_widget = QtWidgets.QWidget()
  1072. # ## Box for custom widgets
  1073. # This gets populated in offspring implementations.
  1074. layout = QtWidgets.QVBoxLayout()
  1075. self.exc_edit_widget.setLayout(layout)
  1076. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1077. # this way I can hide/show the frame
  1078. self.drills_frame = QtWidgets.QFrame()
  1079. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  1080. layout.addWidget(self.drills_frame)
  1081. self.tools_box = QtWidgets.QVBoxLayout()
  1082. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1083. self.drills_frame.setLayout(self.tools_box)
  1084. # ## Page Title box (spacing between children)
  1085. self.title_box = QtWidgets.QHBoxLayout()
  1086. self.tools_box.addLayout(self.title_box)
  1087. # ## Page Title icon
  1088. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1089. self.icon = QtWidgets.QLabel()
  1090. self.icon.setPixmap(pixmap)
  1091. self.title_box.addWidget(self.icon, stretch=0)
  1092. # ## Title label
  1093. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  1094. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1095. self.title_box.addWidget(self.title_label, stretch=1)
  1096. # ## Object name
  1097. self.name_box = QtWidgets.QHBoxLayout()
  1098. self.tools_box.addLayout(self.name_box)
  1099. name_label = QtWidgets.QLabel(_("Name:"))
  1100. self.name_box.addWidget(name_label)
  1101. self.name_entry = FCEntry()
  1102. self.name_box.addWidget(self.name_entry)
  1103. # ### Tools Drills ## ##
  1104. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  1105. self.tools_table_label.setToolTip(
  1106. _("Tools in this Excellon object\n"
  1107. "when are used for drilling.")
  1108. )
  1109. self.tools_box.addWidget(self.tools_table_label)
  1110. self.tools_table_exc = FCTable()
  1111. # delegate = SpinBoxDelegate(units=self.units)
  1112. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  1113. self.tools_box.addWidget(self.tools_table_exc)
  1114. self.tools_table_exc.setColumnCount(4)
  1115. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1116. self.tools_table_exc.setSortingEnabled(False)
  1117. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1118. self.empty_label = QtWidgets.QLabel('')
  1119. self.tools_box.addWidget(self.empty_label)
  1120. # ### Add a new Tool ## ##
  1121. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  1122. self.addtool_label.setToolTip(
  1123. _("Add/Delete a tool to the tool list\n"
  1124. "for this Excellon object.")
  1125. )
  1126. self.tools_box.addWidget(self.addtool_label)
  1127. grid1 = QtWidgets.QGridLayout()
  1128. self.tools_box.addLayout(grid1)
  1129. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  1130. addtool_entry_lbl.setToolTip(
  1131. _("Diameter for the new tool")
  1132. )
  1133. hlay = QtWidgets.QHBoxLayout()
  1134. self.addtool_entry = FCEntry()
  1135. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1136. hlay.addWidget(self.addtool_entry)
  1137. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  1138. self.addtool_btn.setToolTip(
  1139. _("Add a new tool to the tool list\n"
  1140. "with the diameter specified above.")
  1141. )
  1142. self.addtool_btn.setFixedWidth(80)
  1143. hlay.addWidget(self.addtool_btn)
  1144. grid1.addWidget(addtool_entry_lbl, 0, 0)
  1145. grid1.addLayout(hlay, 0, 1)
  1146. grid2 = QtWidgets.QGridLayout()
  1147. self.tools_box.addLayout(grid2)
  1148. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  1149. self.deltool_btn.setToolTip(
  1150. _("Delete a tool in the tool list\n"
  1151. "by selecting a row in the tool table.")
  1152. )
  1153. grid2.addWidget(self.deltool_btn, 0, 1)
  1154. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1155. # this way I can hide/show the frame
  1156. self.resize_frame = QtWidgets.QFrame()
  1157. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  1158. self.tools_box.addWidget(self.resize_frame)
  1159. self.resize_box = QtWidgets.QVBoxLayout()
  1160. self.resize_box.setContentsMargins(0, 0, 0, 0)
  1161. self.resize_frame.setLayout(self.resize_box)
  1162. # ### Resize a drill ## ##
  1163. self.emptyresize_label = QtWidgets.QLabel('')
  1164. self.resize_box.addWidget(self.emptyresize_label)
  1165. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  1166. self.drillresize_label.setToolTip(
  1167. _("Resize a drill or a selection of drills.")
  1168. )
  1169. self.resize_box.addWidget(self.drillresize_label)
  1170. grid3 = QtWidgets.QGridLayout()
  1171. self.resize_box.addLayout(grid3)
  1172. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  1173. res_entry_lbl.setToolTip(
  1174. _("Diameter to resize to.")
  1175. )
  1176. grid3.addWidget(res_entry_lbl, 0, 0)
  1177. hlay2 = QtWidgets.QHBoxLayout()
  1178. self.resdrill_entry = LengthEntry()
  1179. hlay2.addWidget(self.resdrill_entry)
  1180. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  1181. self.resize_btn.setToolTip(
  1182. _("Resize drill(s)")
  1183. )
  1184. self.resize_btn.setFixedWidth(80)
  1185. hlay2.addWidget(self.resize_btn)
  1186. grid3.addLayout(hlay2, 0, 1)
  1187. self.resize_frame.hide()
  1188. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1189. # all the add drill array widgets
  1190. # this way I can hide/show the frame
  1191. self.array_frame = QtWidgets.QFrame()
  1192. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1193. self.tools_box.addWidget(self.array_frame)
  1194. self.array_box = QtWidgets.QVBoxLayout()
  1195. self.array_box.setContentsMargins(0, 0, 0, 0)
  1196. self.array_frame.setLayout(self.array_box)
  1197. # ### Add DRILL Array ## ##
  1198. self.emptyarray_label = QtWidgets.QLabel('')
  1199. self.array_box.addWidget(self.emptyarray_label)
  1200. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  1201. self.drillarray_label.setToolTip(
  1202. _("Add an array of drills (linear or circular array)")
  1203. )
  1204. self.array_box.addWidget(self.drillarray_label)
  1205. self.array_type_combo = FCComboBox()
  1206. self.array_type_combo.setToolTip(
  1207. _("Select the type of drills array to create.\n"
  1208. "It can be Linear X(Y) or Circular")
  1209. )
  1210. self.array_type_combo.addItem(_("Linear"))
  1211. self.array_type_combo.addItem(_("Circular"))
  1212. self.array_box.addWidget(self.array_type_combo)
  1213. self.array_form = QtWidgets.QFormLayout()
  1214. self.array_box.addLayout(self.array_form)
  1215. # Set the number of drill holes in the drill array
  1216. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  1217. self.drill_array_size_label.setToolTip(_("Specify how many drills to be in the array."))
  1218. self.drill_array_size_label.setMinimumWidth(100)
  1219. self.drill_array_size_entry = LengthEntry()
  1220. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  1221. self.array_linear_frame = QtWidgets.QFrame()
  1222. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1223. self.array_box.addWidget(self.array_linear_frame)
  1224. self.linear_box = QtWidgets.QVBoxLayout()
  1225. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1226. self.array_linear_frame.setLayout(self.linear_box)
  1227. self.linear_form = QtWidgets.QFormLayout()
  1228. self.linear_box.addLayout(self.linear_form)
  1229. # Linear Drill Array direction
  1230. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  1231. self.drill_axis_label.setToolTip(
  1232. _("Direction on which the linear array is oriented:\n"
  1233. "- 'X' - horizontal axis \n"
  1234. "- 'Y' - vertical axis or \n"
  1235. "- 'Angle' - a custom angle for the array inclination")
  1236. )
  1237. self.drill_axis_label.setFixedWidth(100)
  1238. self.drill_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1239. {'label': _('Y'), 'value': 'Y'},
  1240. {'label': _('Angle'), 'value': 'A'}])
  1241. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  1242. # Linear Drill Array pitch distance
  1243. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1244. self.drill_pitch_label.setToolTip(
  1245. _("Pitch = Distance between elements of the array.")
  1246. )
  1247. self.drill_pitch_label.setFixedWidth(100)
  1248. self.drill_pitch_entry = LengthEntry()
  1249. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  1250. # Linear Drill Array angle
  1251. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1252. self.linear_angle_label.setToolTip(
  1253. _("Angle at which the linear array is placed.\n"
  1254. "The precision is of max 2 decimals.\n"
  1255. "Min value is: -359.99 degrees.\n"
  1256. "Max value is: 360.00 degrees.")
  1257. )
  1258. self.linear_angle_label.setFixedWidth(100)
  1259. self.linear_angle_spinner = FCDoubleSpinner()
  1260. self.linear_angle_spinner.set_precision(2)
  1261. self.linear_angle_spinner.setSingleStep(1.0)
  1262. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1263. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1264. self.array_circular_frame = QtWidgets.QFrame()
  1265. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1266. self.array_box.addWidget(self.array_circular_frame)
  1267. self.circular_box = QtWidgets.QVBoxLayout()
  1268. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1269. self.array_circular_frame.setLayout(self.circular_box)
  1270. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  1271. self.drill_direction_label.setToolTip(_("Direction for circular array."
  1272. "Can be CW = clockwise or CCW = counter clockwise."))
  1273. self.drill_direction_label.setFixedWidth(100)
  1274. self.circular_form = QtWidgets.QFormLayout()
  1275. self.circular_box.addLayout(self.circular_form)
  1276. self.drill_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1277. {'label': _('CCW'), 'value': 'CCW'}])
  1278. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  1279. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  1280. self.drill_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1281. self.drill_angle_label.setMinimumWidth(100)
  1282. self.drill_angle_entry = LengthEntry()
  1283. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  1284. self.array_circular_frame.hide()
  1285. self.linear_angle_spinner.hide()
  1286. self.linear_angle_label.hide()
  1287. self.array_frame.hide()
  1288. # ######################################################
  1289. # ##### ADDING SLOTS ###################################
  1290. # ######################################################
  1291. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1292. # all the add slot widgets
  1293. # this way I can hide/show the frame
  1294. self.slot_frame = QtWidgets.QFrame()
  1295. self.slot_frame.setContentsMargins(0, 0, 0, 0)
  1296. self.tools_box.addWidget(self.slot_frame)
  1297. self.slot_box = QtWidgets.QVBoxLayout()
  1298. self.slot_box.setContentsMargins(0, 0, 0, 0)
  1299. self.slot_frame.setLayout(self.slot_box)
  1300. self.emptyarray_label = QtWidgets.QLabel('')
  1301. self.slot_box.addWidget(self.emptyarray_label)
  1302. self.slot_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Slot"))
  1303. self.slot_label.setToolTip(
  1304. _("Add slot (hole with oval shape)")
  1305. )
  1306. self.slot_box.addWidget(self.slot_label)
  1307. self.slot_form = QtWidgets.QFormLayout()
  1308. self.slot_box.addLayout(self.slot_form)
  1309. # Slot length
  1310. self.slot_length_label = QtWidgets.QLabel(_('Length:'))
  1311. self.slot_length_label.setToolTip(
  1312. _("Length = The length of the slot.")
  1313. )
  1314. self.slot_length_label.setMinimumWidth(100)
  1315. self.slot_length_entry = LengthEntry()
  1316. self.slot_form.addRow(self.slot_length_label, self.slot_length_entry)
  1317. # Slot direction
  1318. self.slot_axis_label = QtWidgets.QLabel(_('Direction:'))
  1319. self.slot_axis_label.setToolTip(
  1320. _("Direction on which the slot is oriented:\n"
  1321. "- 'X' - horizontal axis \n"
  1322. "- 'Y' - vertical axis or \n"
  1323. "- 'Angle' - a custom angle for the slot inclination")
  1324. )
  1325. self.slot_axis_label.setMinimumWidth(100)
  1326. self.slot_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1327. {'label': _('Y'), 'value': 'Y'},
  1328. {'label': _('Angle'), 'value': 'A'}])
  1329. self.slot_form.addRow(self.slot_axis_label, self.slot_axis_radio)
  1330. # Slot custom angle
  1331. self.slot_angle_label = QtWidgets.QLabel(_('Angle:'))
  1332. self.slot_angle_label.setToolTip(
  1333. _("Angle at which the slot is placed.\n"
  1334. "The precision is of max 2 decimals.\n"
  1335. "Min value is: -359.99 degrees.\n"
  1336. "Max value is: 360.00 degrees.")
  1337. )
  1338. self.slot_angle_label.setMinimumWidth(100)
  1339. self.slot_angle_spinner = FCDoubleSpinner()
  1340. self.slot_angle_spinner.set_precision(2)
  1341. self.slot_angle_spinner.setWrapping(True)
  1342. self.slot_angle_spinner.setRange(-359.99, 360.00)
  1343. self.slot_angle_spinner.setSingleStep(1.0)
  1344. self.slot_form.addRow(self.slot_angle_label, self.slot_angle_spinner)
  1345. self.slot_frame.hide()
  1346. self.tools_box.addStretch()
  1347. # ## Toolbar events and properties
  1348. self.tools_exc = {
  1349. "drill_select": {"button": self.app.ui.select_drill_btn,
  1350. "constructor": FCDrillSelect},
  1351. "drill_add": {"button": self.app.ui.add_drill_btn,
  1352. "constructor": FCDrillAdd},
  1353. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  1354. "constructor": FCDrillArray},
  1355. "drill_slot": {"button": self.app.ui.add_slot_btn,
  1356. "constructor": FCSlot},
  1357. "drill_slotarray": {"button": self.app.ui.add_slot_array_btn,
  1358. "constructor": FCSlotArray},
  1359. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  1360. "constructor": FCDrillResize},
  1361. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  1362. "constructor": FCDrillCopy},
  1363. "drill_move": {"button": self.app.ui.move_drill_btn,
  1364. "constructor": FCDrillMove},
  1365. }
  1366. # ## Data
  1367. self.active_tool = None
  1368. self.in_action = False
  1369. self.storage_dict = {}
  1370. self.current_storage = []
  1371. # build the data from the Excellon point into a dictionary
  1372. # {tool_dia: [geometry_in_points]}
  1373. self.points_edit = {}
  1374. self.slot_points_edit = {}
  1375. self.sorted_diameters = []
  1376. self.new_drills = []
  1377. self.new_tools = {}
  1378. self.new_slots = []
  1379. self.new_tool_offset = {}
  1380. # dictionary to store the tool_row and diameters in Tool_table
  1381. # it will be updated everytime self.build_ui() is called
  1382. self.olddia_newdia = {}
  1383. self.tool2tooldia = {}
  1384. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1385. # is cleared but as a side effect also the selected tool is cleared
  1386. self.last_tool_selected = None
  1387. self.utility = []
  1388. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1389. self.launched_from_shortcuts = False
  1390. # this var will store the state of the toolbar before starting the editor
  1391. self.toolbar_old_state = False
  1392. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  1393. self.name_entry.returnPressed.connect(self.on_name_activate)
  1394. self.addtool_btn.clicked.connect(self.on_tool_add)
  1395. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  1396. self.deltool_btn.clicked.connect(self.on_tool_delete)
  1397. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1398. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1399. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1400. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1401. self.slot_axis_radio.activated_custom.connect(self.on_slot_angle_radio)
  1402. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  1403. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  1404. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  1405. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  1406. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  1407. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  1408. self.exc_obj = None
  1409. # VisPy Visuals
  1410. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1411. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1412. self.app.pool_recreated.connect(self.pool_recreated)
  1413. # Remove from scene
  1414. self.shapes.enabled = False
  1415. self.tool_shape.enabled = False
  1416. # ## List of selected shapes.
  1417. self.selected = []
  1418. self.move_timer = QtCore.QTimer()
  1419. self.move_timer.setSingleShot(True)
  1420. self.key = None # Currently pressed key
  1421. self.modifiers = None
  1422. self.x = None # Current mouse cursor pos
  1423. self.y = None
  1424. # Current snapped mouse pos
  1425. self.snap_x = None
  1426. self.snap_y = None
  1427. self.pos = None
  1428. self.complete = False
  1429. def make_callback(thetool):
  1430. def f():
  1431. self.on_tool_select(thetool)
  1432. return f
  1433. for tool in self.tools_exc:
  1434. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1435. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1436. self.options = {
  1437. "global_gridx": 0.1,
  1438. "global_gridy": 0.1,
  1439. "snap_max": 0.05,
  1440. "grid_snap": True,
  1441. "corner_snap": False,
  1442. "grid_gap_link": True
  1443. }
  1444. self.app.options_read_form()
  1445. for option in self.options:
  1446. if option in self.app.options:
  1447. self.options[option] = self.app.options[option]
  1448. self.rtree_exc_index = rtindex.Index()
  1449. # flag to show if the object was modified
  1450. self.is_modified = False
  1451. self.edited_obj_name = ""
  1452. # variable to store the total amount of drills per job
  1453. self.tot_drill_cnt = 0
  1454. self.tool_row = 0
  1455. # variable to store the total amount of slots per job
  1456. self.tot_slot_cnt = 0
  1457. self.tool_row_slots = 0
  1458. self.tool_row = 0
  1459. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1460. self.editor_active = False
  1461. def entry2option(option, entry):
  1462. self.options[option] = float(entry.text())
  1463. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1464. self.editor_active = False
  1465. def pool_recreated(self, pool):
  1466. self.shapes.pool = pool
  1467. self.tool_shape.pool = pool
  1468. @staticmethod
  1469. def make_storage():
  1470. # ## Shape storage.
  1471. storage = FlatCAMRTreeStorage()
  1472. storage.get_points = DrawToolShape.get_pts
  1473. return storage
  1474. def set_ui(self):
  1475. # updated units
  1476. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1477. self.olddia_newdia.clear()
  1478. self.tool2tooldia.clear()
  1479. # build the self.points_edit dict {dimaters: [point_list]}
  1480. for drill in self.exc_obj.drills:
  1481. if drill['tool'] in self.exc_obj.tools:
  1482. if self.units == 'IN':
  1483. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1484. else:
  1485. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1486. try:
  1487. self.points_edit[tool_dia].append(drill['point'])
  1488. except KeyError:
  1489. self.points_edit[tool_dia] = [drill['point']]
  1490. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1491. for slot in self.exc_obj.slots:
  1492. if slot['tool'] in self.exc_obj.tools:
  1493. if self.units == 'IN':
  1494. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1495. else:
  1496. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1497. try:
  1498. self.slot_points_edit[tool_dia].append({
  1499. "start": slot["start"],
  1500. "stop": slot["stop"]
  1501. })
  1502. except KeyError:
  1503. self.slot_points_edit[tool_dia] = [{
  1504. "start": slot["start"],
  1505. "stop": slot["stop"]
  1506. }]
  1507. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1508. for key in self.points_edit:
  1509. self.olddia_newdia[key] = key
  1510. for key in self.slot_points_edit:
  1511. if key not in self.olddia_newdia:
  1512. self.olddia_newdia[key] = key
  1513. sort_temp = []
  1514. for diam in self.olddia_newdia:
  1515. sort_temp.append(float(diam))
  1516. self.sorted_diameters = sorted(sort_temp)
  1517. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1518. if self.exc_obj.diameterless is False:
  1519. for i in range(len(self.sorted_diameters)):
  1520. tt_dia = self.sorted_diameters[i]
  1521. self.tool2tooldia[i + 1] = tt_dia
  1522. else:
  1523. # the Excellon object has diameters that are bogus information, added by the application because the
  1524. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1525. # but use the real order found in the exc_obj.tools
  1526. for k, v in self.exc_obj.tools.items():
  1527. if self.units == 'IN':
  1528. tool_dia = float('%.4f' % v['C'])
  1529. else:
  1530. tool_dia = float('%.2f' % v['C'])
  1531. self.tool2tooldia[int(k)] = tool_dia
  1532. # Init GUI
  1533. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1534. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1535. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1536. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1537. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1538. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1539. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1540. self.slot_length_entry.set_value(1.0)
  1541. self.slot_axis_radio.set_value('X')
  1542. self.slot_angle_spinner.set_value(0.0)
  1543. def build_ui(self, first_run=None):
  1544. try:
  1545. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1546. self.tools_table_exc.itemChanged.disconnect()
  1547. except (TypeError, AttributeError):
  1548. pass
  1549. try:
  1550. self.tools_table_exc.cellPressed.disconnect()
  1551. except (TypeError, AttributeError):
  1552. pass
  1553. # updated units
  1554. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1555. # make a new name for the new Excellon object (the one with edited content)
  1556. self.edited_obj_name = self.exc_obj.options['name']
  1557. self.name_entry.set_value(self.edited_obj_name)
  1558. sort_temp = []
  1559. for diam in self.olddia_newdia:
  1560. sort_temp.append(float(diam))
  1561. self.sorted_diameters = sorted(sort_temp)
  1562. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1563. n = len(self.sorted_diameters)
  1564. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1565. self.tools_table_exc.setRowCount(n + 2)
  1566. self.tot_drill_cnt = 0
  1567. self.tot_slot_cnt = 0
  1568. self.tool_row = 0
  1569. # this variable will serve as the real tool_number
  1570. tool_id = 0
  1571. for tool_no in self.sorted_diameters:
  1572. tool_id += 1
  1573. drill_cnt = 0 # variable to store the nr of drills per tool
  1574. slot_cnt = 0 # variable to store the nr of slots per tool
  1575. # Find no of drills for the current tool
  1576. for tool_dia in self.points_edit:
  1577. if float(tool_dia) == tool_no:
  1578. drill_cnt = len(self.points_edit[tool_dia])
  1579. self.tot_drill_cnt += drill_cnt
  1580. try:
  1581. # Find no of slots for the current tool
  1582. for slot in self.slots:
  1583. if slot['tool'] == tool_no:
  1584. slot_cnt += 1
  1585. self.tot_slot_cnt += slot_cnt
  1586. except AttributeError:
  1587. # log.debug("No slots in the Excellon file")
  1588. # Find no of slots for the current tool
  1589. for tool_dia in self.slot_points_edit:
  1590. if float(tool_dia) == tool_no:
  1591. slot_cnt = len(self.slot_points_edit[tool_dia])
  1592. self.tot_slot_cnt += slot_cnt
  1593. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1594. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1595. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1596. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1597. # There are no drill bits in MM with more than 3 decimals diameter
  1598. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1599. if self.units == 'MM':
  1600. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1601. else:
  1602. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1603. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1604. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1605. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1606. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1607. if slot_cnt > 0:
  1608. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1609. else:
  1610. slot_count = QtWidgets.QTableWidgetItem('')
  1611. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1612. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1613. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1614. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1615. if first_run is True:
  1616. # set now the last tool selected
  1617. self.last_tool_selected = int(tool_id)
  1618. self.tool_row += 1
  1619. # make the diameter column editable
  1620. for row in range(self.tool_row):
  1621. self.tools_table_exc.item(row, 1).setFlags(
  1622. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1623. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1624. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1625. # add a last row with the Total number of drills
  1626. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1627. # it will have to have the foreground color (font color) white
  1628. empty = QtWidgets.QTableWidgetItem('9998')
  1629. empty.setForeground(QtGui.QColor(255, 255, 255))
  1630. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1631. empty_b = QtWidgets.QTableWidgetItem('')
  1632. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1633. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1634. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1635. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1636. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1637. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1638. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1639. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1640. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1641. font = QtGui.QFont()
  1642. font.setBold(True)
  1643. font.setWeight(75)
  1644. for k in [1, 2]:
  1645. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1646. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1647. self.tool_row += 1
  1648. # add a last row with the Total number of slots
  1649. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1650. # it will have to have the foreground color (font color) white
  1651. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1652. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1653. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1654. empty_3 = QtWidgets.QTableWidgetItem('')
  1655. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1656. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1657. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1658. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1659. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1660. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1661. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1662. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1663. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1664. for kl in [1, 2, 3]:
  1665. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1666. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1667. # all the tools are selected by default
  1668. self.tools_table_exc.selectColumn(0)
  1669. #
  1670. self.tools_table_exc.resizeColumnsToContents()
  1671. self.tools_table_exc.resizeRowsToContents()
  1672. vertical_header = self.tools_table_exc.verticalHeader()
  1673. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1674. vertical_header.hide()
  1675. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1676. horizontal_header = self.tools_table_exc.horizontalHeader()
  1677. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1678. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1679. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1680. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1681. # horizontal_header.setStretchLastSection(True)
  1682. # self.tools_table_exc.setSortingEnabled(True)
  1683. # sort by tool diameter
  1684. self.tools_table_exc.sortItems(1)
  1685. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1686. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1687. # use them
  1688. self.tool2tooldia.clear()
  1689. for row in range(self.tools_table_exc.rowCount() - 2):
  1690. tool = int(self.tools_table_exc.item(row, 0).text())
  1691. diameter = float(self.tools_table_exc.item(row, 1).text())
  1692. self.tool2tooldia[tool] = diameter
  1693. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1694. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1695. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1696. self.tools_table_exc.clearSelection()
  1697. # Remove anything else in the GUI Selected Tab
  1698. self.app.ui.selected_scroll_area.takeWidget()
  1699. # Put ourself in the GUI Selected Tab
  1700. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1701. # Switch notebook to Selected page
  1702. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1703. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1704. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1705. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1706. def on_tool_add(self, tooldia=None):
  1707. self.is_modified = True
  1708. if tooldia:
  1709. tool_dia = tooldia
  1710. else:
  1711. try:
  1712. tool_dia = float(self.addtool_entry.get_value())
  1713. except ValueError:
  1714. # try to convert comma to decimal point. if it's still not working error message and return
  1715. try:
  1716. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1717. except ValueError:
  1718. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1719. "use a number.")
  1720. )
  1721. return
  1722. if tool_dia not in self.olddia_newdia:
  1723. storage_elem = FlatCAMGeoEditor.make_storage()
  1724. self.storage_dict[tool_dia] = storage_elem
  1725. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1726. # each time a tool diameter is edited or added
  1727. self.olddia_newdia[tool_dia] = tool_dia
  1728. else:
  1729. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1730. "Save and reedit Excellon if you need to add this tool. ")
  1731. )
  1732. return
  1733. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1734. # we add a new entry in the tool2tooldia dict
  1735. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1736. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia),
  1737. units=str(self.units)))
  1738. self.build_ui()
  1739. # make a quick sort through the tool2tooldia dict so we find which row to select
  1740. row_to_be_selected = None
  1741. for key in sorted(self.tool2tooldia):
  1742. if self.tool2tooldia[key] == tool_dia:
  1743. row_to_be_selected = int(key) - 1
  1744. self.last_tool_selected = int(key)
  1745. break
  1746. self.tools_table_exc.selectRow(row_to_be_selected)
  1747. def on_tool_delete(self, dia=None):
  1748. self.is_modified = True
  1749. deleted_tool_dia_list = []
  1750. try:
  1751. if dia is None or dia is False:
  1752. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1753. for index in self.tools_table_exc.selectionModel().selectedRows():
  1754. row = index.row()
  1755. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1756. else:
  1757. if isinstance(dia, list):
  1758. for dd in dia:
  1759. deleted_tool_dia_list.append(float('%.4f' % dd))
  1760. else:
  1761. deleted_tool_dia_list.append(float('%.4f' % dia))
  1762. except Exception as e:
  1763. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1764. return
  1765. for deleted_tool_dia in deleted_tool_dia_list:
  1766. # delete de tool offset
  1767. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1768. # delete the storage used for that tool
  1769. storage_elem = FlatCAMGeoEditor.make_storage()
  1770. self.storage_dict[deleted_tool_dia] = storage_elem
  1771. self.storage_dict.pop(deleted_tool_dia, None)
  1772. # I've added this flag_del variable because dictionary don't like
  1773. # having keys deleted while iterating through them
  1774. flag_del = []
  1775. # self.points_edit.pop(deleted_tool_dia, None)
  1776. for deleted_tool in self.tool2tooldia:
  1777. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1778. flag_del.append(deleted_tool)
  1779. if flag_del:
  1780. for tool_to_be_deleted in flag_del:
  1781. # delete the tool
  1782. self.tool2tooldia.pop(tool_to_be_deleted, None)
  1783. # delete also the drills from points_edit dict just in case we add the tool again,
  1784. # we don't want to show the number of drills from before was deleter
  1785. self.points_edit[deleted_tool_dia] = []
  1786. self.olddia_newdia.pop(deleted_tool_dia, None)
  1787. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(
  1788. del_dia=str(deleted_tool_dia),
  1789. units=str(self.units)))
  1790. self.replot()
  1791. # self.app.inform.emit("Could not delete selected tool")
  1792. self.build_ui()
  1793. def on_tool_edit(self, item_changed):
  1794. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1795. self.tools_table_exc.itemChanged.disconnect()
  1796. self.tools_table_exc.cellPressed.disconnect()
  1797. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1798. self.is_modified = True
  1799. current_table_dia_edited = None
  1800. if self.tools_table_exc.currentItem() is not None:
  1801. try:
  1802. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  1803. except ValueError as e:
  1804. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1805. self.tools_table_exc.setCurrentItem(None)
  1806. return
  1807. row_of_item_changed = self.tools_table_exc.currentRow()
  1808. # rows start with 0, tools start with 1 so we adjust the value by 1
  1809. key_in_tool2tooldia = row_of_item_changed + 1
  1810. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1811. # tool diameter is not used so we create a new tool with the desired diameter
  1812. if current_table_dia_edited not in self.olddia_newdia.values():
  1813. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1814. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1815. # update the dict that holds tool_no as key and tool_dia as value
  1816. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1817. # update the tool offset
  1818. modified_offset = self.exc_obj.tool_offset.pop(dia_changed, None)
  1819. if modified_offset is not None:
  1820. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  1821. self.replot()
  1822. else:
  1823. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  1824. factor = current_table_dia_edited / dia_changed
  1825. geometry = []
  1826. for shape_exc in self.storage_dict[dia_changed].get_objects():
  1827. scaled_geo = MultiLineString(
  1828. [affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center') for subgeo in shape_exc.geo]
  1829. )
  1830. geometry.append(DrawToolShape(scaled_geo))
  1831. # add bogus drill points (for total count of drills)
  1832. for k, v in self.olddia_newdia.items():
  1833. if v == current_table_dia_edited:
  1834. self.points_edit[k].append((0, 0))
  1835. break
  1836. # search for the old dia that correspond to the new dia and add the drills in it's storage
  1837. # everything will be sort out later, when the edited Excellon is updated
  1838. for k, v in self.olddia_newdia.items():
  1839. if v == current_table_dia_edited:
  1840. self.add_exc_shape(geometry, self.storage_dict[k])
  1841. break
  1842. # delete the old tool from which we moved the drills
  1843. self.on_tool_delete(dia=dia_changed)
  1844. # delete the tool offset
  1845. self.exc_obj.tool_offset.pop(dia_changed, None)
  1846. # we reactivate the signals after the after the tool editing
  1847. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1848. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1849. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1850. def on_name_activate(self):
  1851. self.edited_obj_name = self.name_entry.get_value()
  1852. def activate(self):
  1853. # adjust the status of the menu entries related to the editor
  1854. self.app.ui.menueditedit.setDisabled(True)
  1855. self.app.ui.menueditok.setDisabled(False)
  1856. # adjust the visibility of some of the canvas context menu
  1857. self.app.ui.popmenu_edit.setVisible(False)
  1858. self.app.ui.popmenu_save.setVisible(True)
  1859. self.connect_canvas_event_handlers()
  1860. # initialize working objects
  1861. self.storage_dict = {}
  1862. self.current_storage = []
  1863. self.points_edit = {}
  1864. self.sorted_diameters = []
  1865. self.new_drills = []
  1866. self.new_tools = {}
  1867. self.new_slots = []
  1868. self.new_tool_offset = {}
  1869. self.olddia_newdia = {}
  1870. self.shapes.enabled = True
  1871. self.tool_shape.enabled = True
  1872. # self.app.app_cursor.enabled = True
  1873. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1874. self.app.ui.corner_snap_btn.setEnabled(True)
  1875. self.app.ui.snap_magnet.setVisible(True)
  1876. self.app.ui.corner_snap_btn.setVisible(True)
  1877. self.app.ui.exc_editor_menu.setDisabled(False)
  1878. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  1879. self.app.ui.update_obj_btn.setEnabled(True)
  1880. self.app.ui.e_editor_cmenu.setEnabled(True)
  1881. self.app.ui.exc_edit_toolbar.setDisabled(False)
  1882. self.app.ui.exc_edit_toolbar.setVisible(True)
  1883. # self.app.ui.snap_toolbar.setDisabled(False)
  1884. # start with GRID toolbar activated
  1885. if self.app.ui.grid_snap_btn.isChecked() is False:
  1886. self.app.ui.grid_snap_btn.trigger()
  1887. self.app.ui.popmenu_disable.setVisible(False)
  1888. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  1889. self.app.ui.popmenu_properties.setVisible(False)
  1890. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  1891. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1892. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1893. # Tell the App that the editor is active
  1894. self.editor_active = True
  1895. # show the UI
  1896. self.drills_frame.show()
  1897. def deactivate(self):
  1898. try:
  1899. QtGui.QGuiApplication.restoreOverrideCursor()
  1900. except Exception as e:
  1901. pass
  1902. # adjust the status of the menu entries related to the editor
  1903. self.app.ui.menueditedit.setDisabled(False)
  1904. self.app.ui.menueditok.setDisabled(True)
  1905. # adjust the visibility of some of the canvas context menu
  1906. self.app.ui.popmenu_edit.setVisible(True)
  1907. self.app.ui.popmenu_save.setVisible(False)
  1908. self.disconnect_canvas_event_handlers()
  1909. self.clear()
  1910. self.app.ui.exc_edit_toolbar.setDisabled(True)
  1911. settings = QSettings("Open Source", "FlatCAM")
  1912. if settings.contains("layout"):
  1913. layout = settings.value('layout', type=str)
  1914. if layout == 'standard':
  1915. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1916. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1917. self.app.ui.corner_snap_btn.setEnabled(False)
  1918. self.app.ui.snap_magnet.setVisible(False)
  1919. self.app.ui.corner_snap_btn.setVisible(False)
  1920. elif layout == 'compact':
  1921. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1922. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1923. self.app.ui.corner_snap_btn.setEnabled(False)
  1924. self.app.ui.snap_magnet.setVisible(True)
  1925. self.app.ui.corner_snap_btn.setVisible(True)
  1926. else:
  1927. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1928. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1929. self.app.ui.corner_snap_btn.setEnabled(False)
  1930. self.app.ui.snap_magnet.setVisible(False)
  1931. self.app.ui.corner_snap_btn.setVisible(False)
  1932. # set the Editor Toolbar visibility to what was before entering in the Editor
  1933. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1934. else self.app.ui.exc_edit_toolbar.setVisible(True)
  1935. # Disable visuals
  1936. self.shapes.enabled = False
  1937. self.tool_shape.enabled = False
  1938. # self.app.app_cursor.enabled = False
  1939. # Tell the app that the editor is no longer active
  1940. self.editor_active = False
  1941. self.app.ui.exc_editor_menu.setDisabled(True)
  1942. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  1943. self.app.ui.update_obj_btn.setEnabled(False)
  1944. self.app.ui.popmenu_disable.setVisible(True)
  1945. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  1946. self.app.ui.popmenu_properties.setVisible(True)
  1947. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1948. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  1949. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1950. # Show original geometry
  1951. if self.exc_obj:
  1952. self.exc_obj.visible = True
  1953. # hide the UI
  1954. self.drills_frame.hide()
  1955. def connect_canvas_event_handlers(self):
  1956. # ## Canvas events
  1957. # first connect to new, then disconnect the old handlers
  1958. # don't ask why but if there is nothing connected I've seen issues
  1959. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1960. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1961. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  1962. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1963. # but those from FlatCAMGeoEditor
  1964. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1965. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1966. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1967. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1968. self.app.collection.view.clicked.disconnect()
  1969. self.app.ui.popmenu_copy.triggered.disconnect()
  1970. self.app.ui.popmenu_delete.triggered.disconnect()
  1971. self.app.ui.popmenu_move.triggered.disconnect()
  1972. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  1973. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  1974. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  1975. # Excellon Editor
  1976. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  1977. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  1978. def disconnect_canvas_event_handlers(self):
  1979. # we restore the key and mouse control to FlatCAMApp method
  1980. # first connect to new, then disconnect the old handlers
  1981. # don't ask why but if there is nothing connected I've seen issues
  1982. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1983. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1984. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1985. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1986. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1987. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1988. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1989. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  1990. try:
  1991. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  1992. except (TypeError, AttributeError):
  1993. pass
  1994. try:
  1995. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  1996. except (TypeError, AttributeError):
  1997. pass
  1998. try:
  1999. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  2000. except (TypeError, AttributeError):
  2001. pass
  2002. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2003. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2004. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2005. # Excellon Editor
  2006. try:
  2007. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2008. except (TypeError, AttributeError):
  2009. pass
  2010. try:
  2011. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2012. except (TypeError, AttributeError):
  2013. pass
  2014. def clear(self):
  2015. self.active_tool = None
  2016. # self.shape_buffer = []
  2017. self.selected = []
  2018. self.points_edit = {}
  2019. self.new_tools = {}
  2020. self.new_drills = []
  2021. # self.storage_dict = {}
  2022. self.shapes.clear(update=True)
  2023. self.tool_shape.clear(update=True)
  2024. # self.storage = FlatCAMExcEditor.make_storage()
  2025. self.replot()
  2026. def edit_fcexcellon(self, exc_obj):
  2027. """
  2028. Imports the geometry from the given FlatCAM Excellon object
  2029. into the editor.
  2030. :param exc_obj: FlatCAMExcellon object
  2031. :return: None
  2032. """
  2033. assert isinstance(exc_obj, Excellon), \
  2034. "Expected an Excellon Object, got %s" % type(exc_obj)
  2035. self.deactivate()
  2036. self.activate()
  2037. # Hide original geometry
  2038. self.exc_obj = exc_obj
  2039. exc_obj.visible = False
  2040. self.points_edit = {}
  2041. self.slot_points_edit = {}
  2042. # Set selection tolerance
  2043. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2044. self.select_tool("drill_select")
  2045. self.set_ui()
  2046. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2047. self.build_ui(first_run=True)
  2048. # we activate this after the initial build as we don't need to see the tool been populated
  2049. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2050. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2051. # and then add it to the storage elements (each storage elements is a member of a list
  2052. for tool_dia in self.points_edit:
  2053. storage_elem = FlatCAMGeoEditor.make_storage()
  2054. for point in self.points_edit[tool_dia]:
  2055. # make a '+' sign, the line length is the tool diameter
  2056. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2057. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2058. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2059. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2060. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2061. if shape_geo is not None:
  2062. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2063. self.storage_dict[tool_dia] = storage_elem
  2064. # slots
  2065. for tool_dia in self.slot_points_edit:
  2066. buf_value = float(tool_dia) / 2
  2067. for elem_dict in self.slot_points_edit[tool_dia]:
  2068. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2069. shape_geo = line_geo.buffer(buf_value)
  2070. if tool_dia not in self.storage_dict:
  2071. storage_elem = FlatCAMGeoEditor.make_storage()
  2072. self.storage_dict[tool_dia] = storage_elem
  2073. if shape_geo is not None:
  2074. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2075. self.replot()
  2076. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2077. if not self.tool2tooldia:
  2078. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2079. def update_fcexcellon(self, exc_obj):
  2080. """
  2081. Create a new Excellon object that contain the edited content of the source Excellon object
  2082. :param exc_obj: FlatCAMExcellon
  2083. :return: None
  2084. """
  2085. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2086. # the values of this dict are coordinates of the holes (drills)
  2087. edited_points = {}
  2088. """
  2089. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2090. - the dict element of the list has the structure
  2091. ================ ====================================
  2092. Key Value
  2093. ================ ====================================
  2094. start (Shapely.Point) Start point of the slot
  2095. stop (Shapely.Point) Stop point of the slot
  2096. ================ ====================================
  2097. """
  2098. edited_slot_points = {}
  2099. for storage_tooldia in self.storage_dict:
  2100. for x in self.storage_dict[storage_tooldia].get_objects():
  2101. if isinstance(x.geo, MultiLineString):
  2102. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2103. # each MultiLineString is made out of Linestrings
  2104. # select first Linestring object in the current MultiLineString
  2105. first_linestring = x.geo[0]
  2106. # get it's coordinates
  2107. first_linestring_coords = first_linestring.coords
  2108. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2109. y_coord = first_linestring_coords[0][1]
  2110. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2111. # edited_points dictionary
  2112. point = (x_coord, y_coord)
  2113. if storage_tooldia not in edited_points:
  2114. edited_points[storage_tooldia] = [point]
  2115. else:
  2116. edited_points[storage_tooldia].append(point)
  2117. elif isinstance(x.geo, Polygon):
  2118. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2119. # edited_points dictionary
  2120. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2121. # diameter
  2122. radius = float(storage_tooldia) / 2
  2123. radius = radius - 0.0000001
  2124. poly = x.geo
  2125. poly = poly.buffer(-radius)
  2126. xmin, ymin, xmax, ymax = poly.bounds
  2127. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2128. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2129. if line_one < line_two:
  2130. point = {
  2131. "start": (xmin, ymax),
  2132. "stop": (xmax, ymin)
  2133. }
  2134. else:
  2135. point = {
  2136. "start": (xmin, ymin),
  2137. "stop": (xmax, ymax)
  2138. }
  2139. if storage_tooldia not in edited_slot_points:
  2140. edited_slot_points[storage_tooldia] = [point]
  2141. else:
  2142. edited_slot_points[storage_tooldia].append(point)
  2143. # recreate the drills and tools to be added to the new Excellon edited object
  2144. # first, we look in the tool table if one of the tool diameters was changed then
  2145. # append that a tuple formed by (old_dia, edited_dia) to a list
  2146. changed_key = set()
  2147. for initial_dia in self.olddia_newdia:
  2148. edited_dia = self.olddia_newdia[initial_dia]
  2149. if edited_dia != initial_dia:
  2150. # for drills
  2151. for old_dia in edited_points:
  2152. if old_dia == initial_dia:
  2153. changed_key.add((old_dia, edited_dia))
  2154. # for slots
  2155. for old_dia in edited_slot_points:
  2156. if old_dia == initial_dia:
  2157. changed_key.add((old_dia, edited_dia))
  2158. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2159. # (and we have to add it)
  2160. # because in case we have drill points it will have to be already added in edited_points
  2161. # if initial_dia not in edited_points.keys():
  2162. # edited_points[initial_dia] = []
  2163. for el in changed_key:
  2164. edited_points[el[1]] = edited_points.pop(el[0])
  2165. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2166. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2167. # ordered_edited_points is a ordered list of tuples;
  2168. # element[0] of the tuple is the diameter and
  2169. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2170. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2171. current_tool = 0
  2172. for tool_dia in ordered_edited_points:
  2173. current_tool += 1
  2174. # create the self.tools for the new Excellon object (the one with edited content)
  2175. name = str(current_tool)
  2176. spec = {"C": float(tool_dia[0])}
  2177. self.new_tools[name] = spec
  2178. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2179. self.new_tools[name]['solid_geometry'] = []
  2180. # create the self.drills for the new Excellon object (the one with edited content)
  2181. for point in tool_dia[1]:
  2182. self.new_drills.append(
  2183. {
  2184. 'point': Point(point),
  2185. 'tool': str(current_tool)
  2186. }
  2187. )
  2188. # repopulate the 'solid_geometry' for each tool
  2189. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2190. self.new_tools[name]['solid_geometry'].append(poly)
  2191. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2192. for tool_dia in ordered_edited_slot_points:
  2193. tool_exist_flag = False
  2194. for tool in self.new_tools:
  2195. if tool_dia[0] == self.new_tools[tool]["C"]:
  2196. current_tool = tool
  2197. tool_exist_flag = True
  2198. break
  2199. if tool_exist_flag is False:
  2200. current_tool += 1
  2201. # create the self.tools for the new Excellon object (the one with edited content)
  2202. name = str(current_tool)
  2203. spec = {"C": float(tool_dia[0])}
  2204. self.new_tools[name] = spec
  2205. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2206. self.new_tools[name]['solid_geometry'] = []
  2207. # create the self.slots for the new Excellon object (the one with edited content)
  2208. for coord_dict in tool_dia[1]:
  2209. self.new_slots.append(
  2210. {
  2211. 'start': Point(coord_dict['start']),
  2212. 'stop': Point(coord_dict['stop']),
  2213. 'tool': str(current_tool)
  2214. }
  2215. )
  2216. # repopulate the 'solid_geometry' for each tool
  2217. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2218. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2219. )
  2220. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2221. if self.is_modified is True:
  2222. if "_edit" in self.edited_obj_name:
  2223. try:
  2224. idd = int(self.edited_obj_name[-1]) + 1
  2225. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2226. except ValueError:
  2227. self.edited_obj_name += "_1"
  2228. else:
  2229. self.edited_obj_name += "_edit"
  2230. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2231. 'params': [self.edited_obj_name]})
  2232. self.new_tool_offset = self.exc_obj.tool_offset
  2233. # reset the tool table
  2234. self.tools_table_exc.clear()
  2235. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2236. self.last_tool_selected = None
  2237. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2238. self.app.collection.set_active(self.exc_obj.options['name'])
  2239. self.app.collection.delete_active()
  2240. # restore GUI to the Selected TAB
  2241. # Remove anything else in the GUI
  2242. self.app.ui.tool_scroll_area.takeWidget()
  2243. # Switch notebook to Selected page
  2244. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2245. def update_options(self, obj):
  2246. try:
  2247. if not obj.options:
  2248. obj.options = {}
  2249. obj.options['xmin'] = 0
  2250. obj.options['ymin'] = 0
  2251. obj.options['xmax'] = 0
  2252. obj.options['ymax'] = 0
  2253. return True
  2254. else:
  2255. return False
  2256. except AttributeError:
  2257. obj.options = {}
  2258. return True
  2259. def new_edited_excellon(self, outname):
  2260. """
  2261. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2262. :param outname: Name of the resulting object. None causes the
  2263. name to be that of the file.
  2264. :type outname: str
  2265. :return: None
  2266. """
  2267. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2268. self.exc_obj.options['name'])
  2269. # How the object should be initialized
  2270. def obj_init(excellon_obj, app_obj):
  2271. # self.progress.emit(20)
  2272. excellon_obj.drills = self.new_drills
  2273. excellon_obj.tools = self.new_tools
  2274. excellon_obj.slots = self.new_slots
  2275. excellon_obj.tool_offset = self.new_tool_offset
  2276. excellon_obj.options['name'] = outname
  2277. try:
  2278. excellon_obj.create_geometry()
  2279. except KeyError:
  2280. self.app.inform.emit(
  2281. _("[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  2282. )
  2283. except:
  2284. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2285. msg += traceback.format_exc()
  2286. app_obj.inform.emit(msg)
  2287. raise
  2288. # raise
  2289. with self.app.proc_container.new(_("Creating Excellon.")):
  2290. try:
  2291. self.app.new_object("excellon", outname, obj_init)
  2292. except Exception as e:
  2293. log.error("Error on object creation: %s" % str(e))
  2294. self.app.progress.emit(100)
  2295. return
  2296. self.app.inform.emit(_("[success] Excellon editing finished."))
  2297. # self.progress.emit(100)
  2298. def on_tool_select(self, tool):
  2299. """
  2300. Behavior of the toolbar. Tool initialization.
  2301. :rtype : None
  2302. """
  2303. current_tool = tool
  2304. self.app.log.debug("on_tool_select('%s')" % tool)
  2305. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2306. # self.draw_app.select_tool('drill_select')
  2307. self.complete = True
  2308. current_tool = 'drill_select'
  2309. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  2310. # This is to make the group behave as radio group
  2311. if current_tool in self.tools_exc:
  2312. if self.tools_exc[current_tool]["button"].isChecked():
  2313. self.app.log.debug("%s is checked." % current_tool)
  2314. for t in self.tools_exc:
  2315. if t != current_tool:
  2316. self.tools_exc[t]["button"].setChecked(False)
  2317. # this is where the Editor toolbar classes (button's) are instantiated
  2318. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2319. # self.app.inform.emit(self.active_tool.start_msg)
  2320. else:
  2321. self.app.log.debug("%s is NOT checked." % current_tool)
  2322. for t in self.tools_exc:
  2323. self.tools_exc[t]["button"].setChecked(False)
  2324. self.select_tool('drill_select')
  2325. self.active_tool = FCDrillSelect(self)
  2326. def on_row_selected(self, row, col):
  2327. if col == 0:
  2328. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2329. if self.app.defaults["global_mselect_key"] == 'Control':
  2330. modifier_to_use = Qt.ControlModifier
  2331. else:
  2332. modifier_to_use = Qt.ShiftModifier
  2333. if key_modifier == modifier_to_use:
  2334. pass
  2335. else:
  2336. self.selected = []
  2337. try:
  2338. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2339. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2340. for obj in self.storage_dict[selected_dia].get_objects():
  2341. self.selected.append(obj)
  2342. except Exception as e:
  2343. self.app.log.debug(str(e))
  2344. self.replot()
  2345. def toolbar_tool_toggle(self, key):
  2346. self.options[key] = self.sender().isChecked()
  2347. if self.options[key] is True:
  2348. return 1
  2349. else:
  2350. return 0
  2351. def on_canvas_click(self, event):
  2352. """
  2353. event.x and .y have canvas coordinates
  2354. event.xdata and .ydata have plot coordinates
  2355. :param event: Event object dispatched by VisPy
  2356. :return: None
  2357. """
  2358. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2359. if self.app.grid_status() == True:
  2360. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2361. self.app.app_cursor.enabled = True
  2362. # Update cursor
  2363. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2364. size=20)
  2365. else:
  2366. self.pos = (self.pos[0], self.pos[1])
  2367. self.app.app_cursor.enabled = False
  2368. if event.button is 1:
  2369. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2370. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2371. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2372. # Selection with left mouse button
  2373. if self.active_tool is not None and event.button is 1:
  2374. # Dispatch event to active_tool
  2375. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2376. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2377. # If it is a shape generating tool
  2378. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2379. if self.current_storage is not None:
  2380. self.on_exc_shape_complete(self.current_storage)
  2381. self.build_ui()
  2382. # MS: always return to the Select Tool if modifier key is not pressed
  2383. # else return to the current tool
  2384. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2385. if self.app.defaults["global_mselect_key"] == 'Control':
  2386. modifier_to_use = Qt.ControlModifier
  2387. else:
  2388. modifier_to_use = Qt.ShiftModifier
  2389. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2390. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2391. if key_modifier == modifier_to_use:
  2392. self.select_tool(self.active_tool.name)
  2393. else:
  2394. # return to Select tool but not for FCDrillAdd or FCSlot
  2395. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2396. self.select_tool(self.active_tool.name)
  2397. else:
  2398. self.select_tool("drill_select")
  2399. return
  2400. if isinstance(self.active_tool, FCDrillSelect):
  2401. # self.app.log.debug("Replotting after click.")
  2402. self.replot()
  2403. else:
  2404. self.app.log.debug("No active tool to respond to click!")
  2405. def on_exc_shape_complete(self, storage):
  2406. self.app.log.debug("on_shape_complete()")
  2407. # Add shape
  2408. if type(storage) is list:
  2409. for item_storage in storage:
  2410. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2411. else:
  2412. self.add_exc_shape(self.active_tool.geometry, storage)
  2413. # Remove any utility shapes
  2414. self.delete_utility_geometry()
  2415. self.tool_shape.clear(update=True)
  2416. # Replot and reset tool.
  2417. self.replot()
  2418. # self.active_tool = type(self.active_tool)(self)
  2419. def add_exc_shape(self, shape, storage):
  2420. """
  2421. Adds a shape to the shape storage.
  2422. :param shape: Shape to be added.
  2423. :type shape: DrawToolShape
  2424. :param storage: object where to store the shapes
  2425. :return: None
  2426. """
  2427. # List of DrawToolShape?
  2428. if isinstance(shape, list):
  2429. for subshape in shape:
  2430. self.add_exc_shape(subshape, storage)
  2431. return
  2432. assert isinstance(shape, DrawToolShape), \
  2433. "Expected a DrawToolShape, got %s" % str(type(shape))
  2434. assert shape.geo is not None, \
  2435. "Shape object has empty geometry (None)"
  2436. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2437. "Shape objects has empty geometry ([])"
  2438. if isinstance(shape, DrawToolUtilityShape):
  2439. self.utility.append(shape)
  2440. else:
  2441. storage.insert(shape) # TODO: Check performance
  2442. def add_shape(self, shape):
  2443. """
  2444. Adds a shape to the shape storage.
  2445. :param shape: Shape to be added.
  2446. :type shape: DrawToolShape
  2447. :return: None
  2448. """
  2449. # List of DrawToolShape?
  2450. if isinstance(shape, list):
  2451. for subshape in shape:
  2452. self.add_shape(subshape)
  2453. return
  2454. assert isinstance(shape, DrawToolShape), \
  2455. "Expected a DrawToolShape, got %s" % type(shape)
  2456. assert shape.geo is not None, \
  2457. "Shape object has empty geometry (None)"
  2458. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2459. "Shape objects has empty geometry ([])"
  2460. if isinstance(shape, DrawToolUtilityShape):
  2461. self.utility.append(shape)
  2462. else:
  2463. self.storage.insert(shape) # TODO: Check performance
  2464. def on_exc_click_release(self, event):
  2465. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2466. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2467. if self.app.grid_status() == True:
  2468. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2469. else:
  2470. pos = (pos_canvas[0], pos_canvas[1])
  2471. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2472. # canvas menu
  2473. try:
  2474. if event.button == 2: # right click
  2475. if self.app.ui.popMenu.mouse_is_panning is False:
  2476. try:
  2477. QtGui.QGuiApplication.restoreOverrideCursor()
  2478. except Exception as e:
  2479. pass
  2480. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2481. self.active_tool.complete = True
  2482. self.in_action = False
  2483. self.delete_utility_geometry()
  2484. self.app.inform.emit(_("[success] Done."))
  2485. self.select_tool('drill_select')
  2486. else:
  2487. if isinstance(self.active_tool, FCDrillAdd):
  2488. self.active_tool.complete = True
  2489. self.in_action = False
  2490. self.delete_utility_geometry()
  2491. self.app.inform.emit(_("[success] Done."))
  2492. self.select_tool('drill_select')
  2493. self.app.cursor = QtGui.QCursor()
  2494. self.app.populate_cmenu_grids()
  2495. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2496. except Exception as e:
  2497. log.warning("Error: %s" % str(e))
  2498. raise
  2499. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2500. # selection and then select a type of selection ("enclosing" or "touching")
  2501. try:
  2502. if event.button == 1: # left click
  2503. if self.app.selection_type is not None:
  2504. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2505. self.app.selection_type = None
  2506. elif isinstance(self.active_tool, FCDrillSelect):
  2507. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2508. # if there are selected objects then plot them
  2509. if self.selected:
  2510. self.replot()
  2511. except Exception as e:
  2512. log.warning("Error: %s" % str(e))
  2513. raise
  2514. def draw_selection_area_handler(self, start, end, sel_type):
  2515. """
  2516. :param start_pos: mouse position when the selection LMB click was done
  2517. :param end_pos: mouse position when the left mouse button is released
  2518. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2519. :return:
  2520. """
  2521. start_pos = (start[0], start[1])
  2522. end_pos = (end[0], end[1])
  2523. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2524. self.app.delete_selection_shape()
  2525. for storage in self.storage_dict:
  2526. for obj in self.storage_dict[storage].get_objects():
  2527. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2528. (sel_type is False and poly_selection.intersects(obj.geo)):
  2529. if self.key == self.app.defaults["global_mselect_key"]:
  2530. if obj in self.selected:
  2531. self.selected.remove(obj)
  2532. else:
  2533. # add the object to the selected shapes
  2534. self.selected.append(obj)
  2535. else:
  2536. self.selected.append(obj)
  2537. try:
  2538. self.tools_table_exc.cellPressed.disconnect()
  2539. except Exception as e:
  2540. pass
  2541. # select the diameter of the selected shape in the tool table
  2542. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2543. for storage in self.storage_dict:
  2544. for shape_s in self.selected:
  2545. if shape_s in self.storage_dict[storage].get_objects():
  2546. for key in self.tool2tooldia:
  2547. if self.tool2tooldia[key] == storage:
  2548. item = self.tools_table_exc.item((key - 1), 1)
  2549. self.tools_table_exc.setCurrentItem(item)
  2550. self.last_tool_selected = int(key)
  2551. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2552. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2553. self.replot()
  2554. def on_canvas_move(self, event):
  2555. """
  2556. Called on 'mouse_move' event
  2557. event.pos have canvas screen coordinates
  2558. :param event: Event object dispatched by VisPy SceneCavas
  2559. :return: None
  2560. """
  2561. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2562. event.xdata, event.ydata = pos[0], pos[1]
  2563. self.x = event.xdata
  2564. self.y = event.ydata
  2565. self.app.ui.popMenu.mouse_is_panning = False
  2566. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2567. if event.button == 2 and event.is_dragging == 1:
  2568. self.app.ui.popMenu.mouse_is_panning = True
  2569. return
  2570. try:
  2571. x = float(event.xdata)
  2572. y = float(event.ydata)
  2573. except TypeError:
  2574. return
  2575. if self.active_tool is None:
  2576. return
  2577. # ## Snap coordinates
  2578. if self.app.grid_status() == True:
  2579. x, y = self.app.geo_editor.snap(x, y)
  2580. self.app.app_cursor.enabled = True
  2581. # Update cursor
  2582. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2583. else:
  2584. self.app.app_cursor.enabled = False
  2585. self.snap_x = x
  2586. self.snap_y = y
  2587. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2588. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2589. "<b>Y</b>: %.4f" % (x, y))
  2590. if self.pos is None:
  2591. self.pos = (0, 0)
  2592. dx = x - self.pos[0]
  2593. dy = y - self.pos[1]
  2594. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2595. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2596. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2597. # ## Utility geometry (animated)
  2598. geo = self.active_tool.utility_geometry(data=(x, y))
  2599. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2600. # Remove any previous utility shape
  2601. self.tool_shape.clear(update=True)
  2602. self.draw_utility_geometry(geo=geo)
  2603. # ## Selection area on canvas section # ##
  2604. if event.is_dragging == 1 and event.button == 1:
  2605. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2606. # can create strange issues
  2607. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray) or \
  2608. isinstance(self.active_tool, FCSlot) or isinstance(self.active_tool, FCSlotArray):
  2609. pass
  2610. else:
  2611. dx = pos[0] - self.pos[0]
  2612. self.app.delete_selection_shape()
  2613. if dx < 0:
  2614. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2615. color=self.app.defaults["global_alt_sel_line"],
  2616. face_color=self.app.defaults['global_alt_sel_fill'])
  2617. self.app.selection_type = False
  2618. else:
  2619. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2620. self.app.selection_type = True
  2621. else:
  2622. self.app.selection_type = None
  2623. # Update cursor
  2624. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2625. def on_canvas_key_release(self, event):
  2626. self.key = None
  2627. def draw_utility_geometry(self, geo):
  2628. # Add the new utility shape
  2629. try:
  2630. # this case is for the Font Parse
  2631. for el in list(geo.geo):
  2632. if type(el) == MultiPolygon:
  2633. for poly in el:
  2634. self.tool_shape.add(
  2635. shape=poly,
  2636. color=(self.app.defaults["global_draw_color"] + '80'),
  2637. update=False,
  2638. layer=0,
  2639. tolerance=None
  2640. )
  2641. elif type(el) == MultiLineString:
  2642. for linestring in el:
  2643. self.tool_shape.add(
  2644. shape=linestring,
  2645. color=(self.app.defaults["global_draw_color"] + '80'),
  2646. update=False,
  2647. layer=0,
  2648. tolerance=None
  2649. )
  2650. else:
  2651. self.tool_shape.add(
  2652. shape=el,
  2653. color=(self.app.defaults["global_draw_color"] + '80'),
  2654. update=False,
  2655. layer=0,
  2656. tolerance=None
  2657. )
  2658. except TypeError:
  2659. self.tool_shape.add(
  2660. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2661. update=False, layer=0, tolerance=None)
  2662. self.tool_shape.redraw()
  2663. def replot(self):
  2664. self.plot_all()
  2665. def plot_all(self):
  2666. """
  2667. Plots all shapes in the editor.
  2668. :return: None
  2669. :rtype: None
  2670. """
  2671. # self.app.log.debug("plot_all()")
  2672. self.shapes.clear(update=True)
  2673. for storage in self.storage_dict:
  2674. for shape_plus in self.storage_dict[storage].get_objects():
  2675. if shape_plus.geo is None:
  2676. continue
  2677. if shape_plus in self.selected:
  2678. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  2679. linewidth=2)
  2680. continue
  2681. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  2682. # for shape in self.storage.get_objects():
  2683. # if shape.geo is None: # TODO: This shouldn't have happened
  2684. # continue
  2685. #
  2686. # if shape in self.selected:
  2687. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2688. # continue
  2689. #
  2690. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2691. for shape_form in self.utility:
  2692. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  2693. continue
  2694. self.shapes.redraw()
  2695. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2696. """
  2697. Plots a geometric object or list of objects without rendering. Plotted objects
  2698. are returned as a list. This allows for efficient/animated rendering.
  2699. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2700. :param color: Shape color
  2701. :param linewidth: Width of lines in # of pixels.
  2702. :return: List of plotted elements.
  2703. """
  2704. plot_elements = []
  2705. if geometry is None:
  2706. geometry = self.active_tool.geometry
  2707. try:
  2708. for geo in geometry:
  2709. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2710. # ## Non-iterable
  2711. except TypeError:
  2712. # ## DrawToolShape
  2713. if isinstance(geometry, DrawToolShape):
  2714. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2715. # ## Polygon: Descend into exterior and each interior.
  2716. if type(geometry) == Polygon:
  2717. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2718. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2719. if type(geometry) == LineString or type(geometry) == LinearRing:
  2720. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  2721. if type(geometry) == Point:
  2722. pass
  2723. return plot_elements
  2724. def on_shape_complete(self):
  2725. self.app.log.debug("on_shape_complete()")
  2726. # Add shape
  2727. self.add_shape(self.active_tool.geometry)
  2728. # Remove any utility shapes
  2729. self.delete_utility_geometry()
  2730. self.tool_shape.clear(update=True)
  2731. # Replot and reset tool.
  2732. self.replot()
  2733. # self.active_tool = type(self.active_tool)(self)
  2734. def get_selected(self):
  2735. """
  2736. Returns list of shapes that are selected in the editor.
  2737. :return: List of shapes.
  2738. """
  2739. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2740. return self.selected
  2741. def delete_selected(self):
  2742. temp_ref = [s for s in self.selected]
  2743. for shape_sel in temp_ref:
  2744. self.delete_shape(shape_sel)
  2745. self.selected = []
  2746. self.build_ui()
  2747. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  2748. def delete_shape(self, del_shape):
  2749. self.is_modified = True
  2750. if del_shape in self.utility:
  2751. self.utility.remove(del_shape)
  2752. return
  2753. for storage in self.storage_dict:
  2754. # try:
  2755. # self.storage_dict[storage].remove(shape)
  2756. # except:
  2757. # pass
  2758. if del_shape in self.storage_dict[storage].get_objects():
  2759. if isinstance(del_shape.geo, MultiLineString):
  2760. self.storage_dict[storage].remove(del_shape)
  2761. # a hack to make the tool_table display less drills per diameter
  2762. # self.points_edit it's only useful first time when we load the data into the storage
  2763. # but is still used as referecen when building tool_table in self.build_ui()
  2764. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2765. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  2766. del self.points_edit[storage][0]
  2767. else:
  2768. self.storage_dict[storage].remove(del_shape)
  2769. del self.slot_points_edit[storage][0]
  2770. if del_shape in self.selected:
  2771. self.selected.remove(del_shape) # TODO: Check performance
  2772. def delete_utility_geometry(self):
  2773. for_deletion = [util_shape for util_shape in self.utility]
  2774. for util_shape in for_deletion:
  2775. self.delete_shape(util_shape)
  2776. self.tool_shape.clear(update=True)
  2777. self.tool_shape.redraw()
  2778. def on_delete_btn(self):
  2779. self.delete_selected()
  2780. self.replot()
  2781. def select_tool(self, toolname):
  2782. """
  2783. Selects a drawing tool. Impacts the object and GUI.
  2784. :param toolname: Name of the tool.
  2785. :return: None
  2786. """
  2787. self.tools_exc[toolname]["button"].setChecked(True)
  2788. self.on_tool_select(toolname)
  2789. def set_selected(self, sel_shape):
  2790. # Remove and add to the end.
  2791. if sel_shape in self.selected:
  2792. self.selected.remove(sel_shape)
  2793. self.selected.append(sel_shape)
  2794. def set_unselected(self, unsel_shape):
  2795. if unsel_shape in self.selected:
  2796. self.selected.remove(unsel_shape)
  2797. def on_array_type_combo(self):
  2798. if self.array_type_combo.currentIndex() == 0:
  2799. self.array_circular_frame.hide()
  2800. self.array_linear_frame.show()
  2801. else:
  2802. self.delete_utility_geometry()
  2803. self.array_circular_frame.show()
  2804. self.array_linear_frame.hide()
  2805. self.app.inform.emit(_("Click on the circular array Center position"))
  2806. def on_linear_angle_radio(self):
  2807. val = self.drill_axis_radio.get_value()
  2808. if val == 'A':
  2809. self.linear_angle_spinner.show()
  2810. self.linear_angle_label.show()
  2811. else:
  2812. self.linear_angle_spinner.hide()
  2813. self.linear_angle_label.hide()
  2814. def on_slot_angle_radio(self):
  2815. val = self.slot_axis_radio.get_value()
  2816. if val == 'A':
  2817. self.slot_angle_spinner.show()
  2818. self.slot_angle_label.show()
  2819. else:
  2820. self.slot_angle_spinner.hide()
  2821. self.slot_angle_label.hide()
  2822. def exc_add_drill(self):
  2823. self.select_tool('drill_add')
  2824. return
  2825. def exc_add_drill_array(self):
  2826. self.select_tool('drill_array')
  2827. return
  2828. def exc_resize_drills(self):
  2829. self.select_tool('drill_resize')
  2830. return
  2831. def exc_copy_drills(self):
  2832. self.select_tool('drill_copy')
  2833. return
  2834. def exc_move_drills(self):
  2835. self.select_tool('drill_move')
  2836. return
  2837. def get_shapely_list_bounds(geometry_list):
  2838. xmin = Inf
  2839. ymin = Inf
  2840. xmax = -Inf
  2841. ymax = -Inf
  2842. for gs in geometry_list:
  2843. try:
  2844. gxmin, gymin, gxmax, gymax = gs.bounds
  2845. xmin = min([xmin, gxmin])
  2846. ymin = min([ymin, gymin])
  2847. xmax = max([xmax, gxmax])
  2848. ymax = max([ymax, gymax])
  2849. except Exception as e:
  2850. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  2851. return [xmin, ymin, xmax, ymax]
  2852. # EOF