AppExcEditor.py 182 KB

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