AppExcEditor.py 182 KB

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