FlatCAMExcEditor.py 158 KB

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