FlatCAMExcEditor.py 134 KB

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