FlatCAMExcEditor.py 171 KB

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