FlatCAMGrbEditor.py 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, QSettings
  3. from shapely.geometry import LineString, LinearRing, MultiLineString
  4. from shapely.ops import cascaded_union, unary_union
  5. import shapely.affinity as affinity
  6. from numpy import arctan2, Inf, array, sqrt, sign, dot
  7. from rtree import index as rtindex
  8. import threading, time
  9. from copy import copy, deepcopy
  10. from camlib import *
  11. from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, LengthEntry, RadioSet, \
  12. SpinBoxDelegate, EvalEntry, EvalEntry2, FCInputDialog, FCButton, OptionalInputSection, FCCheckBox
  13. from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
  14. from FlatCAMObj import FlatCAMGerber
  15. from FlatCAMTool import FlatCAMTool
  16. import gettext
  17. import FlatCAMTranslation as fcTranslate
  18. fcTranslate.apply_language('strings')
  19. import builtins
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. class FCPad(FCShapeTool):
  23. """
  24. Resulting type: Polygon
  25. """
  26. def __init__(self, draw_app):
  27. DrawTool.__init__(self, draw_app)
  28. self.name = 'pad'
  29. self.draw_app = draw_app
  30. try:
  31. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  32. except KeyError:
  33. self.draw_app.app.inform.emit(_(
  34. "[WARNING_NOTCL] To add an Pad first select a aperture in Aperture Table"))
  35. self.draw_app.in_action = False
  36. self.complete = True
  37. return
  38. if self.radius == 0:
  39. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Aperture size is zero. It needs to be greater than zero."))
  40. self.dont_execute = True
  41. return
  42. else:
  43. self.dont_execute = False
  44. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  45. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  46. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  47. try:
  48. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  49. except KeyError:
  50. pass
  51. try:
  52. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  53. except KeyError:
  54. pass
  55. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  56. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  57. self.draw_app.draw_utility_geometry(geo=geo)
  58. self.draw_app.app.inform.emit(_("Click to place ..."))
  59. # Switch notebook to Selected page
  60. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  61. self.start_msg = _("Click to place ...")
  62. def click(self, point):
  63. self.make()
  64. return "Done."
  65. def utility_geometry(self, data=None):
  66. if self.dont_execute is True:
  67. self.draw_app.select_tool('select')
  68. return
  69. self.points = data
  70. geo_data = self.util_shape(data)
  71. if geo_data:
  72. return DrawToolUtilityShape(geo_data)
  73. else:
  74. return None
  75. def util_shape(self, point):
  76. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  77. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  78. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  79. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  80. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  81. try:
  82. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  83. except KeyError:
  84. pass
  85. try:
  86. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  87. except KeyError:
  88. pass
  89. if point[0] is None and point[1] is None:
  90. point_x = self.draw_app.x
  91. point_y = self.draw_app.y
  92. else:
  93. point_x = point[0]
  94. point_y = point[1]
  95. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  96. if ap_type == 'C':
  97. center = Point([point_x, point_y])
  98. return center.buffer(self.radius)
  99. elif ap_type == 'R':
  100. p1 = (point_x - self.half_width, point_y - self.half_height)
  101. p2 = (point_x + self.half_width, point_y - self.half_height)
  102. p3 = (point_x + self.half_width, point_y + self.half_height)
  103. p4 = (point_x - self.half_width, point_y + self.half_height)
  104. return Polygon([p1, p2, p3, p4, p1])
  105. elif ap_type == 'O':
  106. geo = []
  107. if self.half_height > self.half_width:
  108. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  109. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  110. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  111. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  112. down_center = (point_x, point_y - self.half_height + self.half_width)
  113. d_start_angle = math.pi
  114. d_stop_angle = 0.0
  115. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  116. up_center = (point_x, point_y + self.half_height - self.half_width)
  117. u_start_angle = 0.0
  118. u_stop_angle = math.pi
  119. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  120. geo.append(p1)
  121. for pt in down_arc:
  122. geo.append(pt)
  123. geo.append(p2)
  124. geo.append(p3)
  125. for pt in up_arc:
  126. geo.append(pt)
  127. geo.append(p4)
  128. return Polygon(geo)
  129. else:
  130. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  131. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  132. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  133. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  134. left_center = (point_x - self.half_width + self.half_height, point_y)
  135. d_start_angle = math.pi / 2
  136. d_stop_angle = 1.5 * math.pi
  137. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  138. right_center = (point_x + self.half_width - self.half_height, point_y)
  139. u_start_angle = 1.5 * math.pi
  140. u_stop_angle = math.pi / 2
  141. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  142. geo.append(p1)
  143. geo.append(p2)
  144. for pt in right_arc:
  145. geo.append(pt)
  146. geo.append(p3)
  147. geo.append(p4)
  148. for pt in left_arc:
  149. geo.append(pt)
  150. return Polygon(geo)
  151. else:
  152. self.draw_app.app.inform.emit(_(
  153. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  154. return None
  155. def make(self):
  156. self.draw_app.current_storage = self.storage_obj
  157. try:
  158. self.geometry = DrawToolShape(self.util_shape(self.points))
  159. except Exception as e:
  160. log.debug("FCPad.make() --> %s" % str(e))
  161. self.draw_app.in_action = False
  162. self.complete = True
  163. self.draw_app.app.inform.emit(_("[success] Done. Adding Pad completed."))
  164. def clean_up(self):
  165. self.draw_app.selected = []
  166. self.draw_app.apertures_table.clearSelection()
  167. self.draw_app.plot_all()
  168. class FCPadArray(FCShapeTool):
  169. """
  170. Resulting type: MultiPolygon
  171. """
  172. def __init__(self, draw_app):
  173. DrawTool.__init__(self, draw_app)
  174. self.name = 'array'
  175. self.draw_app = draw_app
  176. try:
  177. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  178. except KeyError:
  179. self.draw_app.app.inform.emit(_(
  180. "[WARNING_NOTCL] To add an Pad Array first select a aperture in Aperture Table"))
  181. self.complete = True
  182. self.draw_app.in_action = False
  183. self.draw_app.array_frame.hide()
  184. return
  185. if self.radius == 0:
  186. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Aperture size is zero. It needs to be greater than zero."))
  187. self.dont_execute = True
  188. return
  189. else:
  190. self.dont_execute = False
  191. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  192. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  193. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  194. try:
  195. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  196. except KeyError:
  197. pass
  198. try:
  199. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  200. except KeyError:
  201. pass
  202. self.draw_app.array_frame.show()
  203. self.selected_size = None
  204. self.pad_axis = 'X'
  205. self.pad_array = 'linear'
  206. self.pad_array_size = None
  207. self.pad_pitch = None
  208. self.pad_linear_angle = None
  209. self.pad_angle = None
  210. self.pad_direction = None
  211. self.pad_radius = None
  212. self.origin = None
  213. self.destination = None
  214. self.flag_for_circ_array = None
  215. self.last_dx = 0
  216. self.last_dy = 0
  217. self.pt = []
  218. self.draw_app.app.inform.emit(self.start_msg)
  219. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  220. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  221. self.draw_app.draw_utility_geometry(geo=geo)
  222. self.draw_app.app.inform.emit(_("Click on target location ..."))
  223. # Switch notebook to Selected page
  224. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  225. def click(self, point):
  226. if self.pad_array == 'Linear':
  227. self.make()
  228. return
  229. else:
  230. if self.flag_for_circ_array is None:
  231. self.draw_app.in_action = True
  232. self.pt.append(point)
  233. self.flag_for_circ_array = True
  234. self.set_origin(point)
  235. self.draw_app.app.inform.emit(_("Click on the Pad Circular Array Start position"))
  236. else:
  237. self.destination = point
  238. self.make()
  239. self.flag_for_circ_array = None
  240. return
  241. def set_origin(self, origin):
  242. self.origin = origin
  243. def utility_geometry(self, data=None, static=None):
  244. if self.dont_execute is True:
  245. self.draw_app.select_tool('select')
  246. return
  247. self.pad_axis = self.draw_app.pad_axis_radio.get_value()
  248. self.pad_direction = self.draw_app.pad_direction_radio.get_value()
  249. self.pad_array = self.draw_app.array_type_combo.get_value()
  250. try:
  251. self.pad_array_size = int(self.draw_app.pad_array_size_entry.get_value())
  252. try:
  253. self.pad_pitch = float(self.draw_app.pad_pitch_entry.get_value())
  254. self.pad_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  255. self.pad_angle = float(self.draw_app.pad_angle_entry.get_value())
  256. except TypeError:
  257. self.draw_app.app.inform.emit(
  258. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  259. return
  260. except Exception as e:
  261. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  262. return
  263. if self.pad_array == 'Linear':
  264. if data[0] is None and data[1] is None:
  265. dx = self.draw_app.x
  266. dy = self.draw_app.y
  267. else:
  268. dx = data[0]
  269. dy = data[1]
  270. geo_list = []
  271. geo = None
  272. self.points = [dx, dy]
  273. for item in range(self.pad_array_size):
  274. if self.pad_axis == 'X':
  275. geo = self.util_shape(((dx + (self.pad_pitch * item)), dy))
  276. if self.pad_axis == 'Y':
  277. geo = self.util_shape((dx, (dy + (self.pad_pitch * item))))
  278. if self.pad_axis == 'A':
  279. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  280. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  281. geo = self.util_shape(
  282. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  283. )
  284. if static is None or static is False:
  285. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  286. else:
  287. geo_list.append(geo)
  288. # self.origin = data
  289. self.last_dx = dx
  290. self.last_dy = dy
  291. return DrawToolUtilityShape(geo_list)
  292. else:
  293. if data[0] is None and data[1] is None:
  294. cdx = self.draw_app.x
  295. cdy = self.draw_app.y
  296. else:
  297. cdx = data[0]
  298. cdy = data[1]
  299. if len(self.pt) > 0:
  300. temp_points = [x for x in self.pt]
  301. temp_points.append([cdx, cdy])
  302. return DrawToolUtilityShape(LineString(temp_points))
  303. def util_shape(self, point):
  304. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  305. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  306. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  307. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  308. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  309. try:
  310. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  311. except KeyError:
  312. pass
  313. try:
  314. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  315. except KeyError:
  316. pass
  317. if point[0] is None and point[1] is None:
  318. point_x = self.draw_app.x
  319. point_y = self.draw_app.y
  320. else:
  321. point_x = point[0]
  322. point_y = point[1]
  323. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  324. if ap_type == 'C':
  325. center = Point([point_x, point_y])
  326. return center.buffer(self.radius)
  327. elif ap_type == 'R':
  328. p1 = (point_x - self.half_width, point_y - self.half_height)
  329. p2 = (point_x + self.half_width, point_y - self.half_height)
  330. p3 = (point_x + self.half_width, point_y + self.half_height)
  331. p4 = (point_x - self.half_width, point_y + self.half_height)
  332. return Polygon([p1, p2, p3, p4, p1])
  333. elif ap_type == 'O':
  334. geo = []
  335. if self.half_height > self.half_width:
  336. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  337. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  338. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  339. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  340. down_center = (point_x, point_y - self.half_height + self.half_width)
  341. d_start_angle = math.pi
  342. d_stop_angle = 0.0
  343. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  344. up_center = (point_x, point_y + self.half_height - self.half_width)
  345. u_start_angle = 0.0
  346. u_stop_angle = math.pi
  347. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  348. geo.append(p1)
  349. for pt in down_arc:
  350. geo.append(pt)
  351. geo.append(p2)
  352. geo.append(p3)
  353. for pt in up_arc:
  354. geo.append(pt)
  355. geo.append(p4)
  356. return Polygon(geo)
  357. else:
  358. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  359. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  360. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  361. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  362. left_center = (point_x - self.half_width + self.half_height, point_y)
  363. d_start_angle = math.pi / 2
  364. d_stop_angle = 1.5 * math.pi
  365. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  366. right_center = (point_x + self.half_width - self.half_height, point_y)
  367. u_start_angle = 1.5 * math.pi
  368. u_stop_angle = math.pi / 2
  369. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  370. geo.append(p1)
  371. geo.append(p2)
  372. for pt in right_arc:
  373. geo.append(pt)
  374. geo.append(p3)
  375. geo.append(p4)
  376. for pt in left_arc:
  377. geo.append(pt)
  378. return Polygon(geo)
  379. else:
  380. self.draw_app.app.inform.emit(_(
  381. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  382. return None
  383. def make(self):
  384. self.geometry = []
  385. geo = None
  386. self.draw_app.current_storage = self.storage_obj
  387. if self.pad_array == 'Linear':
  388. for item in range(self.pad_array_size):
  389. if self.pad_axis == 'X':
  390. geo = self.util_shape(((self.points[0] + (self.pad_pitch * item)), self.points[1]))
  391. if self.pad_axis == 'Y':
  392. geo = self.util_shape((self.points[0], (self.points[1] + (self.pad_pitch * item))))
  393. if self.pad_axis == 'A':
  394. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  395. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  396. geo = self.util_shape(
  397. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  398. )
  399. self.geometry.append(DrawToolShape(geo))
  400. else:
  401. if (self.pad_angle * self.pad_array_size) > 360:
  402. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many Pads for the selected spacing angle."))
  403. return
  404. radius = distance(self.destination, self.origin)
  405. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  406. for i in range(self.pad_array_size):
  407. angle_radians = math.radians(self.pad_angle * i)
  408. if self.pad_direction == 'CW':
  409. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  410. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  411. else:
  412. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  413. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  414. geo = self.util_shape((x, y))
  415. if self.pad_direction == 'CW':
  416. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  417. else:
  418. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  419. self.geometry.append(DrawToolShape(geo))
  420. self.complete = True
  421. self.draw_app.app.inform.emit(_("[success] Done. Pad Array added."))
  422. self.draw_app.in_action = False
  423. self.draw_app.array_frame.hide()
  424. return
  425. def clean_up(self):
  426. self.draw_app.selected = []
  427. self.draw_app.apertures_table.clearSelection()
  428. self.draw_app.plot_all()
  429. class FCPoligonize(FCShapeTool):
  430. """
  431. Resulting type: Polygon
  432. """
  433. def __init__(self, draw_app):
  434. DrawTool.__init__(self, draw_app)
  435. self.name = 'poligonize'
  436. self.draw_app = draw_app
  437. self.start_msg = _("Select shape(s) and then click ...")
  438. self.draw_app.in_action = True
  439. self.make()
  440. def click(self, point):
  441. return ""
  442. def make(self):
  443. if not self.draw_app.selected:
  444. self.draw_app.in_action = False
  445. self.complete = True
  446. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Failed. Nothing selected."))
  447. self.draw_app.select_tool("select")
  448. return
  449. try:
  450. current_storage = self.draw_app.storage_dict['0']['solid_geometry']
  451. except KeyError:
  452. self.draw_app.on_aperture_add(apid='0')
  453. current_storage = self.draw_app.storage_dict['0']['solid_geometry']
  454. fused_geo = [Polygon(sh.geo.exterior) for sh in self.draw_app.selected]
  455. fused_geo = MultiPolygon(fused_geo)
  456. fused_geo = fused_geo.buffer(0.0000001)
  457. if isinstance(fused_geo, MultiPolygon):
  458. for geo in fused_geo:
  459. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(geo))
  460. else:
  461. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(fused_geo))
  462. self.draw_app.delete_selected()
  463. self.draw_app.plot_all()
  464. self.draw_app.in_action = False
  465. self.complete = True
  466. self.draw_app.app.inform.emit(_("[success] Done. Poligonize completed."))
  467. # MS: always return to the Select Tool if modifier key is not pressed
  468. # else return to the current tool
  469. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  470. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  471. modifier_to_use = Qt.ControlModifier
  472. else:
  473. modifier_to_use = Qt.ShiftModifier
  474. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  475. # in the selected list, we removed it. Therefore first click selects, second deselects.
  476. if key_modifier == modifier_to_use:
  477. self.draw_app.select_tool(self.draw_app.active_tool.name)
  478. else:
  479. self.draw_app.select_tool("select")
  480. return
  481. def clean_up(self):
  482. self.draw_app.selected = []
  483. self.draw_app.apertures_table.clearSelection()
  484. self.draw_app.plot_all()
  485. class FCRegion(FCShapeTool):
  486. """
  487. Resulting type: Polygon
  488. """
  489. def __init__(self, draw_app):
  490. DrawTool.__init__(self, draw_app)
  491. self.name = 'region'
  492. self.draw_app = draw_app
  493. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  494. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  495. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  496. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  497. self.temp_points = []
  498. self.start_msg = _("Click on 1st point ...")
  499. def click(self, point):
  500. self.draw_app.in_action = True
  501. self.points.append(point)
  502. if len(self.points) > 0:
  503. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  504. return "Click on next point or hit ENTER to complete ..."
  505. return ""
  506. def update_grid_info(self):
  507. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  508. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  509. def utility_geometry(self, data=None):
  510. if len(self.points) == 1:
  511. temp_points = [x for x in self.points]
  512. temp_points.append(data)
  513. return DrawToolUtilityShape(LineString(temp_points).buffer(self.buf_val, join_style=1))
  514. if len(self.points) > 1:
  515. temp_points = [x for x in self.points]
  516. temp_points.append(data)
  517. return DrawToolUtilityShape(LinearRing(temp_points).buffer(self.buf_val, join_style=1))
  518. return None
  519. def make(self):
  520. # self.geometry = LinearRing(self.points)
  521. self.geometry = DrawToolShape(Polygon(self.points).buffer(self.buf_val, join_style=2))
  522. self.draw_app.in_action = False
  523. self.complete = True
  524. self.draw_app.app.inform.emit(_("[success] Done. Region completed."))
  525. def clean_up(self):
  526. self.draw_app.selected = []
  527. self.draw_app.apertures_table.clearSelection()
  528. self.draw_app.plot_all()
  529. def on_key(self, key):
  530. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  531. if len(self.points) > 0:
  532. self.points = self.points[0:-1]
  533. # Remove any previous utility shape
  534. self.draw_app.tool_shape.clear(update=False)
  535. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  536. self.draw_app.draw_utility_geometry(geo=geo)
  537. return _("Backtracked one point ...")
  538. class FCTrack(FCRegion):
  539. """
  540. Resulting type: Polygon
  541. """
  542. def __init__(self, draw_app):
  543. FCRegion.__init__(self, draw_app)
  544. self.draw_app = draw_app
  545. self.draw_app.app.inform.emit(_('Track Mode 1: 45 degrees ...'))
  546. self.mode = 1
  547. def make(self):
  548. if len(self.temp_points) == 1:
  549. self.geometry = DrawToolShape(Point(self.temp_points).buffer(self.buf_val))
  550. else:
  551. self.geometry = DrawToolShape(LineString(self.temp_points).buffer(self.buf_val))
  552. self.name = 'track'
  553. self.draw_app.in_action = False
  554. self.complete = True
  555. self.draw_app.app.inform.emit(_("[success] Done. Path completed."))
  556. def clean_up(self):
  557. self.draw_app.selected = []
  558. self.draw_app.apertures_table.clearSelection()
  559. self.draw_app.plot_all()
  560. def click(self, point):
  561. self.draw_app.in_action = True
  562. self.points.append(point)
  563. if len(self.temp_points) == 1:
  564. g = DrawToolShape(Point(self.temp_points).buffer(self.buf_val))
  565. else:
  566. g = DrawToolShape(LineString(self.temp_points).buffer(self.buf_val))
  567. self.draw_app.add_gerber_shape(g, self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry'])
  568. self.draw_app.plot_all()
  569. if len(self.points) > 0:
  570. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  571. return "Click on next point or hit ENTER to complete ..."
  572. return ""
  573. def utility_geometry(self, data=None):
  574. self.update_grid_info()
  575. if len(self.points) == 0:
  576. return DrawToolUtilityShape(Point(data).buffer(self.buf_val))
  577. elif len(self.points) > 0:
  578. self.temp_points = [self.points[-1]]
  579. old_x = self.points[-1][0]
  580. old_y = self.points[-1][1]
  581. x = data[0]
  582. y = data[1]
  583. mx = abs(round((x - old_x) / self.gridx_size))
  584. my = abs(round((y - old_y) / self.gridy_size))
  585. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  586. if self.mode == 1:
  587. if x > old_x:
  588. if mx > my:
  589. self.temp_points.append((old_x + self.gridx_size*(mx-my), old_y))
  590. if mx < my:
  591. if y < old_y:
  592. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  593. else:
  594. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  595. if x < old_x:
  596. if mx > my:
  597. self.temp_points.append((old_x - self.gridx_size*(mx-my), old_y))
  598. if mx < my:
  599. if y < old_y:
  600. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  601. else:
  602. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  603. elif self.mode == 2:
  604. if x > old_x:
  605. if mx > my:
  606. self.temp_points.append((old_x + self.gridx_size*my, y))
  607. if mx < my:
  608. if y < old_y:
  609. self.temp_points.append((x, old_y - self.gridy_size * mx))
  610. else:
  611. self.temp_points.append((x, old_y + self.gridy_size * mx))
  612. if x < old_x:
  613. if mx > my:
  614. self.temp_points.append((old_x - self.gridx_size * my, y))
  615. if mx < my:
  616. if y < old_y:
  617. self.temp_points.append((x, old_y - self.gridy_size * mx))
  618. else:
  619. self.temp_points.append((x, old_y + self.gridy_size * mx))
  620. elif self.mode == 3:
  621. self.temp_points.append((old_x, y))
  622. elif self.mode == 4:
  623. self.temp_points.append((x, old_y))
  624. else:
  625. pass
  626. self.temp_points.append(data)
  627. if len(self.temp_points) == 1:
  628. return DrawToolUtilityShape(Point(self.temp_points).buffer(self.buf_val))
  629. return DrawToolUtilityShape(LineString(self.temp_points).buffer(self.buf_val))
  630. def on_key(self, key):
  631. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  632. if len(self.points) > 0:
  633. self.temp_points = self.points[0:-1]
  634. # Remove any previous utility shape
  635. self.draw_app.tool_shape.clear(update=False)
  636. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  637. self.draw_app.draw_utility_geometry(geo=geo)
  638. return _("Backtracked one point ...")
  639. if key == 'T' or key == QtCore.Qt.Key_T:
  640. if self.mode == 1:
  641. self.mode = 2
  642. msg = _('Track Mode 2: Reverse 45 degrees ...')
  643. elif self.mode == 2:
  644. self.mode = 3
  645. msg = _('Track Mode 3: 90 degrees ...')
  646. elif self.mode == 3:
  647. self.mode = 4
  648. msg = _('Track Mode 4: Reverse 90 degrees ...')
  649. elif self.mode == 4:
  650. self.mode = 5
  651. msg = _('Track Mode 5: Free angle ...')
  652. else:
  653. self.mode = 1
  654. msg = _('Track Mode 1: 45 degrees ...')
  655. # Remove any previous utility shape
  656. self.draw_app.tool_shape.clear(update=False)
  657. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  658. self.draw_app.draw_utility_geometry(geo=geo)
  659. return msg
  660. if key == 'R' or key == QtCore.Qt.Key_R:
  661. if self.mode == 1:
  662. self.mode = 5
  663. msg = _('Track Mode 5: Free angle ...')
  664. elif self.mode == 5:
  665. self.mode = 4
  666. msg = _('Track Mode 4: Reverse 90 degrees ...')
  667. elif self.mode == 4:
  668. self.mode = 3
  669. msg = _('Track Mode 3: 90 degrees ...')
  670. elif self.mode == 3:
  671. self.mode = 2
  672. msg = _('Track Mode 2: Reverse 45 degrees ...')
  673. else:
  674. self.mode = 1
  675. msg = _('Track Mode 1: 45 degrees ...')
  676. # Remove any previous utility shape
  677. self.draw_app.tool_shape.clear(update=False)
  678. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  679. self.draw_app.draw_utility_geometry(geo=geo)
  680. return msg
  681. class FCScale(FCShapeTool):
  682. def __init__(self, draw_app):
  683. FCShapeTool.__init__(self, draw_app)
  684. self.name = 'scale'
  685. # self.shape_buffer = self.draw_app.shape_buffer
  686. self.draw_app = draw_app
  687. self.app = draw_app.app
  688. self.start_msg = _("Scale the selected Gerber apertures ...")
  689. self.origin = (0, 0)
  690. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  691. self.draw_app.app.ui.splitter.setSizes([1, 1])
  692. self.activate_scale()
  693. def activate_scale(self):
  694. self.draw_app.hide_tool('all')
  695. self.draw_app.scale_tool_frame.show()
  696. try:
  697. self.draw_app.scale_button.clicked.disconnect()
  698. except TypeError:
  699. pass
  700. self.draw_app.scale_button.clicked.connect(self.on_scale_click)
  701. def deactivate_scale(self):
  702. self.draw_app.scale_button.clicked.disconnect()
  703. self.complete = True
  704. self.draw_app.select_tool("select")
  705. self.draw_app.hide_tool(self.name)
  706. def on_scale_click(self):
  707. self.draw_app.on_scale()
  708. self.deactivate_scale()
  709. def clean_up(self):
  710. self.draw_app.selected = []
  711. self.draw_app.apertures_table.clearSelection()
  712. self.draw_app.plot_all()
  713. class FCBuffer(FCShapeTool):
  714. def __init__(self, draw_app):
  715. FCShapeTool.__init__(self, draw_app)
  716. self.name = 'buffer'
  717. # self.shape_buffer = self.draw_app.shape_buffer
  718. self.draw_app = draw_app
  719. self.app = draw_app.app
  720. self.start_msg = _("Buffer the selected apertures ...")
  721. self.origin = (0, 0)
  722. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  723. self.draw_app.app.ui.splitter.setSizes([1, 1])
  724. self.activate_buffer()
  725. def activate_buffer(self):
  726. self.draw_app.hide_tool('all')
  727. self.draw_app.buffer_tool_frame.show()
  728. try:
  729. self.draw_app.buffer_button.clicked.disconnect()
  730. except TypeError:
  731. pass
  732. self.draw_app.buffer_button.clicked.connect(self.on_buffer_click)
  733. def deactivate_buffer(self):
  734. self.draw_app.buffer_button.clicked.disconnect()
  735. self.complete = True
  736. self.draw_app.select_tool("select")
  737. self.draw_app.hide_tool(self.name)
  738. def on_buffer_click(self):
  739. self.draw_app.on_buffer()
  740. self.deactivate_buffer()
  741. def clean_up(self):
  742. self.draw_app.selected = []
  743. self.draw_app.apertures_table.clearSelection()
  744. self.draw_app.plot_all()
  745. class FCApertureMove(FCShapeTool):
  746. def __init__(self, draw_app):
  747. DrawTool.__init__(self, draw_app)
  748. self.name = 'move'
  749. # self.shape_buffer = self.draw_app.shape_buffer
  750. self.origin = None
  751. self.destination = None
  752. self.selected_apertures = []
  753. if self.draw_app.launched_from_shortcuts is True:
  754. self.draw_app.launched_from_shortcuts = False
  755. self.draw_app.app.inform.emit(_("Click on target location ..."))
  756. else:
  757. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  758. self.current_storage = None
  759. self.geometry = []
  760. for index in self.draw_app.apertures_table.selectedIndexes():
  761. row = index.row()
  762. # on column 1 in tool tables we hold the aperture codes, and we retrieve them as strings
  763. aperture_on_row = self.draw_app.apertures_table.item(row, 1).text()
  764. self.selected_apertures.append(aperture_on_row)
  765. # Switch notebook to Selected page
  766. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  767. def set_origin(self, origin):
  768. self.origin = origin
  769. def click(self, point):
  770. if len(self.draw_app.get_selected()) == 0:
  771. return "Nothing to move."
  772. if self.origin is None:
  773. self.set_origin(point)
  774. self.draw_app.app.inform.emit(_("Click on target location ..."))
  775. return
  776. else:
  777. self.destination = point
  778. self.make()
  779. # MS: always return to the Select Tool
  780. self.draw_app.select_tool("select")
  781. return
  782. def make(self):
  783. # Create new geometry
  784. dx = self.destination[0] - self.origin[0]
  785. dy = self.destination[1] - self.origin[1]
  786. sel_shapes_to_be_deleted = []
  787. for sel_dia in self.selected_apertures:
  788. self.current_storage = self.draw_app.storage_dict[sel_dia]['solid_geometry']
  789. for select_shape in self.draw_app.get_selected():
  790. if select_shape in self.current_storage:
  791. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  792. self.current_storage.remove(select_shape)
  793. sel_shapes_to_be_deleted.append(select_shape)
  794. self.draw_app.on_grb_shape_complete(self.current_storage)
  795. self.geometry = []
  796. for shp in sel_shapes_to_be_deleted:
  797. self.draw_app.selected.remove(shp)
  798. sel_shapes_to_be_deleted = []
  799. self.draw_app.build_ui()
  800. self.draw_app.app.inform.emit(_("[success] Done. Apertures Move completed."))
  801. def clean_up(self):
  802. self.draw_app.selected = []
  803. self.draw_app.apertures_table.clearSelection()
  804. self.draw_app.plot_all()
  805. def utility_geometry(self, data=None):
  806. """
  807. Temporary geometry on screen while using this tool.
  808. :param data:
  809. :return:
  810. """
  811. geo_list = []
  812. if self.origin is None:
  813. return None
  814. if len(self.draw_app.get_selected()) == 0:
  815. return None
  816. dx = data[0] - self.origin[0]
  817. dy = data[1] - self.origin[1]
  818. for geom in self.draw_app.get_selected():
  819. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  820. return DrawToolUtilityShape(geo_list)
  821. class FCApertureCopy(FCApertureMove):
  822. def __init__(self, draw_app):
  823. FCApertureMove.__init__(self, draw_app)
  824. self.name = 'copy'
  825. def make(self):
  826. # Create new geometry
  827. dx = self.destination[0] - self.origin[0]
  828. dy = self.destination[1] - self.origin[1]
  829. sel_shapes_to_be_deleted = []
  830. for sel_dia in self.selected_apertures:
  831. self.current_storage = self.draw_app.storage_dict[sel_dia]['solid_geometry']
  832. for select_shape in self.draw_app.get_selected():
  833. if select_shape in self.current_storage:
  834. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  835. sel_shapes_to_be_deleted.append(select_shape)
  836. self.draw_app.on_grb_shape_complete(self.current_storage)
  837. self.geometry = []
  838. for shp in sel_shapes_to_be_deleted:
  839. self.draw_app.selected.remove(shp)
  840. sel_shapes_to_be_deleted = []
  841. self.draw_app.build_ui()
  842. self.draw_app.app.inform.emit(_("[success] Done. Apertures copied."))
  843. class FCApertureSelect(DrawTool):
  844. def __init__(self, grb_editor_app):
  845. DrawTool.__init__(self, grb_editor_app)
  846. self.name = 'select'
  847. self.origin = None
  848. self.grb_editor_app = grb_editor_app
  849. self.storage = self.grb_editor_app.storage_dict
  850. # self.selected = self.grb_editor_app.selected
  851. # here we store all shapes that were selected
  852. self.sel_storage = []
  853. self.grb_editor_app.apertures_table.clearSelection()
  854. self.grb_editor_app.hide_tool('all')
  855. self.grb_editor_app.hide_tool('select')
  856. def set_origin(self, origin):
  857. self.origin = origin
  858. def click(self, point):
  859. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  860. if self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control':
  861. if key_modifier == Qt.ControlModifier:
  862. pass
  863. else:
  864. self.grb_editor_app.selected = []
  865. else:
  866. if key_modifier == Qt.ShiftModifier:
  867. pass
  868. else:
  869. self.grb_editor_app.selected = []
  870. def click_release(self, point):
  871. self.grb_editor_app.apertures_table.clearSelection()
  872. sel_aperture = set()
  873. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  874. for storage in self.grb_editor_app.storage_dict:
  875. for shape in self.grb_editor_app.storage_dict[storage]['solid_geometry']:
  876. if Point(point).within(shape.geo):
  877. if (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control' and
  878. key_modifier == Qt.ControlModifier) or \
  879. (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Shift' and
  880. key_modifier == Qt.ShiftModifier):
  881. if shape in self.draw_app.selected:
  882. self.draw_app.selected.remove(shape)
  883. else:
  884. # add the object to the selected shapes
  885. self.draw_app.selected.append(shape)
  886. sel_aperture.add(storage)
  887. else:
  888. self.draw_app.selected.append(shape)
  889. sel_aperture.add(storage)
  890. # select the aperture in the Apertures Table that is associated with the selected shape
  891. try:
  892. self.draw_app.apertures_table.cellPressed.disconnect()
  893. except:
  894. pass
  895. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  896. for aper in sel_aperture:
  897. for row in range(self.grb_editor_app.apertures_table.rowCount()):
  898. if str(aper) == self.grb_editor_app.apertures_table.item(row, 1).text():
  899. self.grb_editor_app.apertures_table.selectRow(row)
  900. self.draw_app.last_aperture_selected = aper
  901. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  902. self.draw_app.apertures_table.cellPressed.connect(self.draw_app.on_row_selected)
  903. return ""
  904. def clean_up(self):
  905. self.draw_app.plot_all()
  906. class FCTransform(FCShapeTool):
  907. def __init__(self, draw_app):
  908. FCShapeTool.__init__(self, draw_app)
  909. self.name = 'transformation'
  910. # self.shape_buffer = self.draw_app.shape_buffer
  911. self.draw_app = draw_app
  912. self.app = draw_app.app
  913. self.start_msg = _("Shape transformations ...")
  914. self.origin = (0, 0)
  915. self.draw_app.transform_tool.run()
  916. def clean_up(self):
  917. self.draw_app.selected = []
  918. self.draw_app.apertures_table.clearSelection()
  919. self.draw_app.plot_all()
  920. class FlatCAMGrbEditor(QtCore.QObject):
  921. draw_shape_idx = -1
  922. def __init__(self, app):
  923. assert isinstance(app, FlatCAMApp.App), \
  924. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  925. super(FlatCAMGrbEditor, self).__init__()
  926. self.app = app
  927. self.canvas = self.app.plotcanvas
  928. ## Current application units in Upper Case
  929. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  930. self.grb_edit_widget = QtWidgets.QWidget()
  931. layout = QtWidgets.QVBoxLayout()
  932. self.grb_edit_widget.setLayout(layout)
  933. ## Page Title box (spacing between children)
  934. self.title_box = QtWidgets.QHBoxLayout()
  935. layout.addLayout(self.title_box)
  936. ## Page Title icon
  937. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  938. self.icon = QtWidgets.QLabel()
  939. self.icon.setPixmap(pixmap)
  940. self.title_box.addWidget(self.icon, stretch=0)
  941. ## Title label
  942. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Gerber Editor'))
  943. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  944. self.title_box.addWidget(self.title_label, stretch=1)
  945. ## Object name
  946. self.name_box = QtWidgets.QHBoxLayout()
  947. layout.addLayout(self.name_box)
  948. name_label = QtWidgets.QLabel(_("Name:"))
  949. self.name_box.addWidget(name_label)
  950. self.name_entry = FCEntry()
  951. self.name_box.addWidget(self.name_entry)
  952. ## Box for custom widgets
  953. # This gets populated in offspring implementations.
  954. self.custom_box = QtWidgets.QVBoxLayout()
  955. layout.addLayout(self.custom_box)
  956. #### Gerber Apertures ####
  957. self.apertures_table_label = QtWidgets.QLabel(_('<b>Apertures:</b>'))
  958. self.apertures_table_label.setToolTip(
  959. _("Apertures Table for the Gerber Object.")
  960. )
  961. self.custom_box.addWidget(self.apertures_table_label)
  962. self.apertures_table = FCTable()
  963. # delegate = SpinBoxDelegate(units=self.units)
  964. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  965. self.custom_box.addWidget(self.apertures_table)
  966. self.apertures_table.setColumnCount(5)
  967. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  968. self.apertures_table.setSortingEnabled(False)
  969. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  970. _("Index"))
  971. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  972. _("Aperture Code"))
  973. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  974. _("Type of aperture: circular, rectangle, macros etc"))
  975. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  976. _("Aperture Size:"))
  977. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  978. _("Aperture Dimensions:\n"
  979. " - (width, height) for R, O type.\n"
  980. " - (dia, nVertices) for P type"))
  981. self.empty_label = QtWidgets.QLabel('')
  982. self.custom_box.addWidget(self.empty_label)
  983. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Apertures widgets
  984. # this way I can hide/show the frame
  985. self.apertures_frame = QtWidgets.QFrame()
  986. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  987. self.custom_box.addWidget(self.apertures_frame)
  988. self.apertures_box = QtWidgets.QVBoxLayout()
  989. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  990. self.apertures_frame.setLayout(self.apertures_box)
  991. #### Add/Delete an new Aperture ####
  992. grid1 = QtWidgets.QGridLayout()
  993. self.apertures_box.addLayout(grid1)
  994. apcode_lbl = QtWidgets.QLabel(_('Aperture Code:'))
  995. apcode_lbl.setToolTip(
  996. _("Code for the new aperture")
  997. )
  998. grid1.addWidget(apcode_lbl, 1, 0)
  999. self.apcode_entry = FCEntry()
  1000. self.apcode_entry.setValidator(QtGui.QIntValidator(0, 999))
  1001. grid1.addWidget(self.apcode_entry, 1, 1)
  1002. apsize_lbl = QtWidgets.QLabel(_('Aperture Size:'))
  1003. apsize_lbl.setToolTip(
  1004. _("Size for the new aperture.\n"
  1005. "If aperture type is 'R' or 'O' then\n"
  1006. "this value is automatically\n"
  1007. "calculated as:\n"
  1008. "sqrt(width**2 + height**2)")
  1009. )
  1010. grid1.addWidget(apsize_lbl, 2, 0)
  1011. self.apsize_entry = FCEntry()
  1012. self.apsize_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1013. grid1.addWidget(self.apsize_entry, 2, 1)
  1014. aptype_lbl = QtWidgets.QLabel(_('Aperture Type:'))
  1015. aptype_lbl.setToolTip(
  1016. _("Select the type of new aperture. Can be:\n"
  1017. "C = circular\n"
  1018. "R = rectangular\n"
  1019. "O = oblong")
  1020. )
  1021. grid1.addWidget(aptype_lbl, 3, 0)
  1022. self.aptype_cb = FCComboBox()
  1023. self.aptype_cb.addItems(['C', 'R', 'O'])
  1024. grid1.addWidget(self.aptype_cb, 3, 1)
  1025. self.apdim_lbl = QtWidgets.QLabel(_('Aperture Dim:'))
  1026. self.apdim_lbl.setToolTip(
  1027. _("Dimensions for the new aperture.\n"
  1028. "Active only for rectangular apertures (type R).\n"
  1029. "The format is (width, height)")
  1030. )
  1031. grid1.addWidget(self.apdim_lbl, 4, 0)
  1032. self.apdim_entry = EvalEntry2()
  1033. grid1.addWidget(self.apdim_entry, 4, 1)
  1034. apadd_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Add Aperture:'))
  1035. apadd_lbl.setToolTip(
  1036. _("Add an aperture to the aperture list")
  1037. )
  1038. grid1.addWidget(apadd_lbl, 5, 0)
  1039. self.addaperture_btn = QtWidgets.QPushButton(_('Go'))
  1040. self.addaperture_btn.setToolTip(
  1041. _( "Add a new aperture to the aperture list.")
  1042. )
  1043. grid1.addWidget(self.addaperture_btn, 5, 1)
  1044. apdelete_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Del Aperture:'))
  1045. apdelete_lbl.setToolTip(
  1046. _( "Delete a aperture in the aperture list.\n"
  1047. "It will delete also the associated geometry.")
  1048. )
  1049. grid1.addWidget(apdelete_lbl, 6, 0)
  1050. self.delaperture_btn = QtWidgets.QPushButton(_('Go'))
  1051. self.delaperture_btn.setToolTip(
  1052. _( "Delete a aperture in the aperture list")
  1053. )
  1054. grid1.addWidget(self.delaperture_btn, 6, 1)
  1055. ### BUFFER TOOL ###
  1056. self.buffer_tool_frame = QtWidgets.QFrame()
  1057. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  1058. self.custom_box.addWidget(self.buffer_tool_frame)
  1059. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  1060. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  1061. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  1062. self.buffer_tool_frame.hide()
  1063. # Title
  1064. buf_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Buffer Aperture:'))
  1065. buf_title_lbl.setToolTip(
  1066. _("Buffer a aperture in the aperture list")
  1067. )
  1068. self.buffer_tools_box.addWidget(buf_title_lbl)
  1069. # Form Layout
  1070. buf_form_layout = QtWidgets.QFormLayout()
  1071. self.buffer_tools_box.addLayout(buf_form_layout)
  1072. # Buffer distance
  1073. self.buffer_distance_entry = FCEntry()
  1074. buf_form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  1075. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  1076. self.buffer_corner_lbl.setToolTip(
  1077. _("There are 3 types of corners:\n"
  1078. " - 'Round': the corner is rounded.\n"
  1079. " - 'Square:' the corner is met in a sharp angle.\n"
  1080. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  1081. )
  1082. self.buffer_corner_cb = FCComboBox()
  1083. self.buffer_corner_cb.addItem(_("Round"))
  1084. self.buffer_corner_cb.addItem(_("Square"))
  1085. self.buffer_corner_cb.addItem(_("Beveled"))
  1086. buf_form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  1087. # Buttons
  1088. hlay_buf = QtWidgets.QHBoxLayout()
  1089. self.buffer_tools_box.addLayout(hlay_buf)
  1090. self.buffer_button = QtWidgets.QPushButton(_("Buffer"))
  1091. hlay_buf.addWidget(self.buffer_button)
  1092. ### SCALE TOOL ###
  1093. self.scale_tool_frame = QtWidgets.QFrame()
  1094. self.scale_tool_frame.setContentsMargins(0, 0, 0, 0)
  1095. self.custom_box.addWidget(self.scale_tool_frame)
  1096. self.scale_tools_box = QtWidgets.QVBoxLayout()
  1097. self.scale_tools_box.setContentsMargins(0, 0, 0, 0)
  1098. self.scale_tool_frame.setLayout(self.scale_tools_box)
  1099. self.scale_tool_frame.hide()
  1100. # Title
  1101. scale_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Scale Aperture:'))
  1102. scale_title_lbl.setToolTip(
  1103. _("Scale a aperture in the aperture list")
  1104. )
  1105. self.scale_tools_box.addWidget(scale_title_lbl)
  1106. # Form Layout
  1107. scale_form_layout = QtWidgets.QFormLayout()
  1108. self.scale_tools_box.addLayout(scale_form_layout)
  1109. self.scale_factor_lbl = QtWidgets.QLabel(_("Scale factor:"))
  1110. self.scale_factor_lbl.setToolTip(
  1111. _("The factor by which to scale the selected aperture.\n"
  1112. "Values can be between 0.0000 and 999.9999")
  1113. )
  1114. self.scale_factor_entry = FCEntry()
  1115. self.scale_factor_entry.setValidator(QtGui.QDoubleValidator(0.0000, 999.9999, 4))
  1116. scale_form_layout.addRow(self.scale_factor_lbl, self.scale_factor_entry)
  1117. # Buttons
  1118. hlay_scale = QtWidgets.QHBoxLayout()
  1119. self.scale_tools_box.addLayout(hlay_scale)
  1120. self.scale_button = QtWidgets.QPushButton(_("Scale"))
  1121. hlay_scale.addWidget(self.scale_button)
  1122. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1123. # all the add Pad array widgets
  1124. # this way I can hide/show the frame
  1125. self.array_frame = QtWidgets.QFrame()
  1126. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1127. self.custom_box.addWidget(self.array_frame)
  1128. self.array_box = QtWidgets.QVBoxLayout()
  1129. self.array_box.setContentsMargins(0, 0, 0, 0)
  1130. self.array_frame.setLayout(self.array_box)
  1131. #### Add Pad Array ####
  1132. self.emptyarray_label = QtWidgets.QLabel('')
  1133. self.array_box.addWidget(self.emptyarray_label)
  1134. self.padarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Pad Array"))
  1135. self.padarray_label.setToolTip(
  1136. _("Add an array of pads (linear or circular array)")
  1137. )
  1138. self.array_box.addWidget(self.padarray_label)
  1139. self.array_type_combo = FCComboBox()
  1140. self.array_type_combo.setToolTip(
  1141. _( "Select the type of pads array to create.\n"
  1142. "It can be Linear X(Y) or Circular")
  1143. )
  1144. self.array_type_combo.addItem(_("Linear"))
  1145. self.array_type_combo.addItem(_("Circular"))
  1146. self.array_box.addWidget(self.array_type_combo)
  1147. self.array_form = QtWidgets.QFormLayout()
  1148. self.array_box.addLayout(self.array_form)
  1149. self.pad_array_size_label = QtWidgets.QLabel(_('Nr of pads:'))
  1150. self.pad_array_size_label.setToolTip(
  1151. _("Specify how many pads to be in the array.")
  1152. )
  1153. self.pad_array_size_label.setFixedWidth(100)
  1154. self.pad_array_size_entry = LengthEntry()
  1155. self.array_form.addRow(self.pad_array_size_label, self.pad_array_size_entry)
  1156. self.array_linear_frame = QtWidgets.QFrame()
  1157. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1158. self.array_box.addWidget(self.array_linear_frame)
  1159. self.linear_box = QtWidgets.QVBoxLayout()
  1160. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1161. self.array_linear_frame.setLayout(self.linear_box)
  1162. self.linear_form = QtWidgets.QFormLayout()
  1163. self.linear_box.addLayout(self.linear_form)
  1164. self.pad_axis_label = QtWidgets.QLabel(_('Direction:'))
  1165. self.pad_axis_label.setToolTip(
  1166. _("Direction on which the linear array is oriented:\n"
  1167. "- 'X' - horizontal axis \n"
  1168. "- 'Y' - vertical axis or \n"
  1169. "- 'Angle' - a custom angle for the array inclination")
  1170. )
  1171. self.pad_axis_label.setFixedWidth(100)
  1172. self.pad_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  1173. {'label': 'Y', 'value': 'Y'},
  1174. {'label': _('Angle'), 'value': 'A'}])
  1175. self.pad_axis_radio.set_value('X')
  1176. self.linear_form.addRow(self.pad_axis_label, self.pad_axis_radio)
  1177. self.pad_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1178. self.pad_pitch_label.setToolTip(
  1179. _("Pitch = Distance between elements of the array.")
  1180. )
  1181. self.pad_pitch_label.setFixedWidth(100)
  1182. self.pad_pitch_entry = LengthEntry()
  1183. self.linear_form.addRow(self.pad_pitch_label, self.pad_pitch_entry)
  1184. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1185. self.linear_angle_label.setToolTip(
  1186. _( "Angle at which the linear array is placed.\n"
  1187. "The precision is of max 2 decimals.\n"
  1188. "Min value is: -359.99 degrees.\n"
  1189. "Max value is: 360.00 degrees.")
  1190. )
  1191. self.linear_angle_label.setFixedWidth(100)
  1192. self.linear_angle_spinner = FCDoubleSpinner()
  1193. self.linear_angle_spinner.set_precision(2)
  1194. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1195. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1196. self.array_circular_frame = QtWidgets.QFrame()
  1197. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1198. self.array_box.addWidget(self.array_circular_frame)
  1199. self.circular_box = QtWidgets.QVBoxLayout()
  1200. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1201. self.array_circular_frame.setLayout(self.circular_box)
  1202. self.pad_direction_label = QtWidgets.QLabel(_('Direction:'))
  1203. self.pad_direction_label.setToolTip(
  1204. _( "Direction for circular array."
  1205. "Can be CW = clockwise or CCW = counter clockwise.")
  1206. )
  1207. self.pad_direction_label.setFixedWidth(100)
  1208. self.circular_form = QtWidgets.QFormLayout()
  1209. self.circular_box.addLayout(self.circular_form)
  1210. self.pad_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  1211. {'label': 'CCW.', 'value': 'CCW'}])
  1212. self.pad_direction_radio.set_value('CW')
  1213. self.circular_form.addRow(self.pad_direction_label, self.pad_direction_radio)
  1214. self.pad_angle_label = QtWidgets.QLabel(_('Angle:'))
  1215. self.pad_angle_label.setToolTip(
  1216. _("Angle at which each element in circular array is placed.")
  1217. )
  1218. self.pad_angle_label.setFixedWidth(100)
  1219. self.pad_angle_entry = LengthEntry()
  1220. self.circular_form.addRow(self.pad_angle_label, self.pad_angle_entry)
  1221. self.array_circular_frame.hide()
  1222. self.linear_angle_spinner.hide()
  1223. self.linear_angle_label.hide()
  1224. self.array_frame.hide()
  1225. self.custom_box.addStretch()
  1226. ## Toolbar events and properties
  1227. self.tools_gerber = {
  1228. "select": {"button": self.app.ui.grb_select_btn,
  1229. "constructor": FCApertureSelect},
  1230. "pad": {"button": self.app.ui.grb_add_pad_btn,
  1231. "constructor": FCPad},
  1232. "array": {"button": self.app.ui.add_pad_ar_btn,
  1233. "constructor": FCPadArray},
  1234. "track": {"button": self.app.ui.grb_add_track_btn,
  1235. "constructor": FCTrack},
  1236. "region": {"button": self.app.ui.grb_add_region_btn,
  1237. "constructor": FCRegion},
  1238. "poligonize": {"button": self.app.ui.grb_convert_poly_btn,
  1239. "constructor": FCPoligonize},
  1240. "buffer": {"button": self.app.ui.aperture_buffer_btn,
  1241. "constructor": FCBuffer},
  1242. "scale": {"button": self.app.ui.aperture_scale_btn,
  1243. "constructor": FCScale},
  1244. "copy": {"button": self.app.ui.aperture_copy_btn,
  1245. "constructor": FCApertureCopy},
  1246. "transform": {"button": self.app.ui.grb_transform_btn,
  1247. "constructor": FCTransform},
  1248. "move": {"button": self.app.ui.aperture_move_btn,
  1249. "constructor": FCApertureMove},
  1250. }
  1251. ### Data
  1252. self.active_tool = None
  1253. self.storage_dict = {}
  1254. self.current_storage = []
  1255. self.sorted_apid =[]
  1256. self.new_apertures = {}
  1257. self.new_aperture_macros = {}
  1258. # store here the plot promises, if empty the delayed plot will be activated
  1259. self.grb_plot_promises = []
  1260. # dictionary to store the tool_row and aperture codes in Tool_table
  1261. # it will be updated everytime self.build_ui() is called
  1262. self.olddia_newdia = {}
  1263. self.tool2tooldia = {}
  1264. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1265. # is cleared but as a side effect also the selected tool is cleared
  1266. self.last_aperture_selected = None
  1267. self.utility = []
  1268. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1269. self.launched_from_shortcuts = False
  1270. # this var will store the state of the toolbar before starting the editor
  1271. self.toolbar_old_state = False
  1272. # holds flattened geometry
  1273. self.flat_geometry = []
  1274. # Init GUI
  1275. self.apdim_lbl.hide()
  1276. self.apdim_entry.hide()
  1277. self.gerber_obj = None
  1278. self.gerber_obj_options = {}
  1279. self.buffer_distance_entry.set_value(0.01)
  1280. self.scale_factor_entry.set_value(1.0)
  1281. # VisPy Visuals
  1282. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1283. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1284. self.app.pool_recreated.connect(self.pool_recreated)
  1285. # Remove from scene
  1286. self.shapes.enabled = False
  1287. self.tool_shape.enabled = False
  1288. ## List of selected shapes.
  1289. self.selected = []
  1290. self.key = None # Currently pressed key
  1291. self.modifiers = None
  1292. self.x = None # Current mouse cursor pos
  1293. self.y = None
  1294. # Current snapped mouse pos
  1295. self.snap_x = None
  1296. self.snap_y = None
  1297. self.pos = None
  1298. # signal that there is an action active like polygon or path
  1299. self.in_action = False
  1300. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1301. self.launched_from_shortcuts = False
  1302. def make_callback(thetool):
  1303. def f():
  1304. self.on_tool_select(thetool)
  1305. return f
  1306. for tool in self.tools_gerber:
  1307. self.tools_gerber[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1308. self.tools_gerber[tool]["button"].setCheckable(True) # Checkable
  1309. self.options = {
  1310. "global_gridx": 0.1,
  1311. "global_gridy": 0.1,
  1312. "snap_max": 0.05,
  1313. "grid_snap": True,
  1314. "corner_snap": False,
  1315. "grid_gap_link": True
  1316. }
  1317. self.app.options_read_form()
  1318. for option in self.options:
  1319. if option in self.app.options:
  1320. self.options[option] = self.app.options[option]
  1321. # flag to show if the object was modified
  1322. self.is_modified = False
  1323. self.edited_obj_name = ""
  1324. self.tool_row = 0
  1325. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1326. self.editor_active = False
  1327. def entry2option(option, entry):
  1328. self.options[option] = float(entry.text())
  1329. self.transform_tool = TransformEditorTool(self.app, self)
  1330. # Signals
  1331. self.buffer_button.clicked.connect(self.on_buffer)
  1332. self.scale_button.clicked.connect(self.on_scale)
  1333. self.app.ui.aperture_delete_btn.triggered.connect(self.on_delete_btn)
  1334. self.name_entry.returnPressed.connect(self.on_name_activate)
  1335. self.aptype_cb.currentIndexChanged[str].connect(self.on_aptype_changed)
  1336. self.addaperture_btn.clicked.connect(self.on_aperture_add)
  1337. self.apsize_entry.returnPressed.connect(self.on_aperture_add)
  1338. self.apdim_entry.returnPressed.connect(self.on_aperture_add)
  1339. self.delaperture_btn.clicked.connect(self.on_aperture_delete)
  1340. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1341. self.app.ui.grb_add_pad_menuitem.triggered.connect(self.on_pad_add)
  1342. self.app.ui.grb_add_pad_array_menuitem.triggered.connect(self.on_pad_add_array)
  1343. self.app.ui.grb_add_track_menuitem.triggered.connect(self.on_track_add)
  1344. self.app.ui.grb_add_region_menuitem.triggered.connect(self.on_region_add)
  1345. self.app.ui.grb_convert_poly_menuitem.triggered.connect(self.on_poligonize)
  1346. self.app.ui.grb_add_buffer_menuitem.triggered.connect(self.on_buffer)
  1347. self.app.ui.grb_add_scale_menuitem.triggered.connect(self.on_scale)
  1348. self.app.ui.grb_transform_menuitem.triggered.connect(self.transform_tool.run)
  1349. self.app.ui.grb_copy_menuitem.triggered.connect(self.on_copy_button)
  1350. self.app.ui.grb_delete_menuitem.triggered.connect(self.on_delete_btn)
  1351. self.app.ui.grb_move_menuitem.triggered.connect(self.on_move_button)
  1352. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1353. self.pad_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1354. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1355. self.editor_active = False
  1356. def pool_recreated(self, pool):
  1357. self.shapes.pool = pool
  1358. self.tool_shape.pool = pool
  1359. def set_ui(self):
  1360. # updated units
  1361. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1362. self.olddia_newdia.clear()
  1363. self.tool2tooldia.clear()
  1364. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1365. for key in self.storage_dict:
  1366. self.olddia_newdia[key] = key
  1367. sort_temp = []
  1368. for aperture in self.olddia_newdia:
  1369. sort_temp.append(int(aperture))
  1370. self.sorted_apid = sorted(sort_temp)
  1371. # populate self.intial_table_rows dict with the tool number as keys and aperture codes as values
  1372. for i in range(len(self.sorted_apid)):
  1373. tt_aperture = self.sorted_apid[i]
  1374. self.tool2tooldia[i + 1] = tt_aperture
  1375. if self.units == "IN":
  1376. self.apsize_entry.set_value(0.039)
  1377. else:
  1378. self.apsize_entry.set_value(1.00)
  1379. # Init GUI
  1380. self.pad_array_size_entry.set_value(5)
  1381. self.pad_pitch_entry.set_value(2.54)
  1382. self.pad_angle_entry.set_value(12)
  1383. self.pad_direction_radio.set_value('CW')
  1384. self.pad_axis_radio.set_value('X')
  1385. def build_ui(self, first_run=None):
  1386. try:
  1387. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1388. self.apertures_table.itemChanged.disconnect()
  1389. except:
  1390. pass
  1391. try:
  1392. self.apertures_table.cellPressed.disconnect()
  1393. except:
  1394. pass
  1395. # updated units
  1396. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1397. # make a new name for the new Excellon object (the one with edited content)
  1398. self.edited_obj_name = self.gerber_obj.options['name']
  1399. self.name_entry.set_value(self.edited_obj_name)
  1400. self.apertures_row = 0
  1401. aper_no = self.apertures_row + 1
  1402. sort = []
  1403. for k, v in list(self.storage_dict.items()):
  1404. sort.append(int(k))
  1405. sorted_apertures = sorted(sort)
  1406. sort = []
  1407. for k, v in list(self.gerber_obj.aperture_macros.items()):
  1408. sort.append(k)
  1409. sorted_macros = sorted(sort)
  1410. n = len(sorted_apertures) + len(sorted_macros)
  1411. self.apertures_table.setRowCount(n)
  1412. for ap_code in sorted_apertures:
  1413. ap_code = str(ap_code)
  1414. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1415. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1416. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1417. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1418. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1419. ap_type_item = QtWidgets.QTableWidgetItem(str(self.storage_dict[ap_code]['type']))
  1420. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1421. if str(self.storage_dict[ap_code]['type']) == 'R' or str(self.storage_dict[ap_code]['type']) == 'O':
  1422. ap_dim_item = QtWidgets.QTableWidgetItem(
  1423. '%.4f, %.4f' % (self.storage_dict[ap_code]['width'],
  1424. self.storage_dict[ap_code]['height']
  1425. )
  1426. )
  1427. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1428. elif str(self.storage_dict[ap_code]['type']) == 'P':
  1429. ap_dim_item = QtWidgets.QTableWidgetItem(
  1430. '%.4f, %.4f' % (self.storage_dict[ap_code]['diam'],
  1431. self.storage_dict[ap_code]['nVertices'])
  1432. )
  1433. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1434. else:
  1435. ap_dim_item = QtWidgets.QTableWidgetItem('')
  1436. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1437. try:
  1438. if self.storage_dict[ap_code]['size'] is not None:
  1439. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  1440. float(self.storage_dict[ap_code]['size']))
  1441. else:
  1442. ap_size_item = QtWidgets.QTableWidgetItem('')
  1443. except KeyError:
  1444. ap_size_item = QtWidgets.QTableWidgetItem('')
  1445. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1446. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1447. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1448. self.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  1449. self.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  1450. self.apertures_row += 1
  1451. if first_run is True:
  1452. # set now the last aperture selected
  1453. self.last_aperture_selected = ap_code
  1454. for ap_code in sorted_macros:
  1455. ap_code = str(ap_code)
  1456. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1457. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1458. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1459. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1460. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  1461. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1462. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1463. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1464. self.apertures_row += 1
  1465. if first_run is True:
  1466. # set now the last aperture selected
  1467. self.last_aperture_selected = ap_code
  1468. self.apertures_table.selectColumn(0)
  1469. self.apertures_table.resizeColumnsToContents()
  1470. self.apertures_table.resizeRowsToContents()
  1471. vertical_header = self.apertures_table.verticalHeader()
  1472. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1473. vertical_header.hide()
  1474. self.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1475. horizontal_header = self.apertures_table.horizontalHeader()
  1476. horizontal_header.setMinimumSectionSize(10)
  1477. horizontal_header.setDefaultSectionSize(70)
  1478. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1479. horizontal_header.resizeSection(0, 20)
  1480. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  1481. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1482. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1483. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  1484. self.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1485. self.apertures_table.setSortingEnabled(False)
  1486. self.apertures_table.setMinimumHeight(self.apertures_table.getHeight())
  1487. self.apertures_table.setMaximumHeight(self.apertures_table.getHeight())
  1488. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1489. self.apertures_table.clearSelection()
  1490. # Remove anything else in the GUI Selected Tab
  1491. self.app.ui.selected_scroll_area.takeWidget()
  1492. # Put ourself in the GUI Selected Tab
  1493. self.app.ui.selected_scroll_area.setWidget(self.grb_edit_widget)
  1494. # Switch notebook to Selected page
  1495. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1496. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1497. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1498. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1499. # for convenience set the next aperture code in the apcode field
  1500. try:
  1501. self.apcode_entry.set_value(max(self.tool2tooldia.values()) + 1)
  1502. except ValueError:
  1503. # this means that the edited object has no apertures so we start with 10 (Gerber specifications)
  1504. self.apcode_entry.set_value(10)
  1505. def on_aperture_add(self, apid=None):
  1506. self.is_modified = True
  1507. if apid:
  1508. ap_id = apid
  1509. else:
  1510. try:
  1511. ap_id = str(self.apcode_entry.get_value())
  1512. except ValueError:
  1513. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1514. "Add it and retry."))
  1515. return
  1516. if ap_id == '':
  1517. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1518. "Add it and retry."))
  1519. return
  1520. if ap_id == '0':
  1521. if ap_id not in self.olddia_newdia:
  1522. self.storage_dict[ap_id] = {}
  1523. self.storage_dict[ap_id]['type'] = 'REG'
  1524. size_val = 0
  1525. self.apsize_entry.set_value(size_val)
  1526. self.storage_dict[ap_id]['size'] = size_val
  1527. self.storage_dict[ap_id]['solid_geometry'] = []
  1528. self.storage_dict[ap_id]['follow_geometry'] = []
  1529. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1530. # each time a aperture code is edited or added
  1531. self.olddia_newdia[ap_id] = ap_id
  1532. else:
  1533. if ap_id not in self.olddia_newdia:
  1534. self.storage_dict[ap_id] = {}
  1535. type_val = self.aptype_cb.currentText()
  1536. self.storage_dict[ap_id]['type'] = type_val
  1537. if type_val == 'R' or type_val == 'O':
  1538. try:
  1539. dims = self.apdim_entry.get_value()
  1540. self.storage_dict[ap_id]['width'] = dims[0]
  1541. self.storage_dict[ap_id]['height'] = dims[1]
  1542. size_val = math.sqrt((dims[0] ** 2) + (dims[1] ** 2))
  1543. self.apsize_entry.set_value(size_val)
  1544. except Exception as e:
  1545. log.error("FlatCAMGrbEditor.on_aperture_add() --> the R or O aperture dims has to be in a "
  1546. "tuple format (x,y)\nError: %s" % str(e))
  1547. self.app.inform.emit(_("[WARNING_NOTCL] Aperture dimensions value is missing or wrong format. "
  1548. "Add it in format (width, height) and retry."))
  1549. return
  1550. else:
  1551. try:
  1552. size_val = float(self.apsize_entry.get_value())
  1553. except ValueError:
  1554. # try to convert comma to decimal point. if it's still not working error message and return
  1555. try:
  1556. size_val = float(self.apsize_entry.get_value().replace(',', '.'))
  1557. self.apsize_entry.set_value(size_val)
  1558. except ValueError:
  1559. self.app.inform.emit(_("[WARNING_NOTCL] Aperture size value is missing or wrong format. "
  1560. "Add it and retry."))
  1561. return
  1562. self.storage_dict[ap_id]['size'] = size_val
  1563. self.storage_dict[ap_id]['solid_geometry'] = []
  1564. self.storage_dict[ap_id]['follow_geometry'] = []
  1565. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1566. # each time a aperture code is edited or added
  1567. self.olddia_newdia[ap_id] = ap_id
  1568. else:
  1569. self.app.inform.emit(_("[WARNING_NOTCL] Aperture already in the aperture table."))
  1570. return
  1571. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1572. # we add a new entry in the tool2tooldia dict
  1573. self.tool2tooldia[len(self.olddia_newdia)] = int(ap_id)
  1574. self.app.inform.emit(_("[success] Added new aperture with code: {apid}").format(apid=str(ap_id)))
  1575. self.build_ui()
  1576. self.last_aperture_selected = ap_id
  1577. # make a quick sort through the tool2tooldia dict so we find which row to select
  1578. row_to_be_selected = None
  1579. for key in sorted(self.tool2tooldia):
  1580. if self.tool2tooldia[key] == int(ap_id):
  1581. row_to_be_selected = int(key) - 1
  1582. break
  1583. self.apertures_table.selectRow(row_to_be_selected)
  1584. def on_aperture_delete(self, apid=None):
  1585. self.is_modified = True
  1586. deleted_apcode_list = []
  1587. deleted_tool_offset_list = []
  1588. try:
  1589. if apid is None or apid is False:
  1590. # deleted_tool_dia = float(self.apertures_table.item(self.apertures_table.currentRow(), 1).text())
  1591. for index in self.apertures_table.selectionModel().selectedRows():
  1592. row = index.row()
  1593. deleted_apcode_list.append(self.apertures_table.item(row, 1).text())
  1594. else:
  1595. if isinstance(apid, list):
  1596. for dd in apid:
  1597. deleted_apcode_list.append(dd)
  1598. else:
  1599. deleted_apcode_list.append(apid)
  1600. except:
  1601. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1602. return
  1603. for deleted_aperture in deleted_apcode_list:
  1604. # delete the storage used for that tool
  1605. self.storage_dict.pop(deleted_aperture, None)
  1606. # I've added this flag_del variable because dictionary don't like
  1607. # having keys deleted while iterating through them
  1608. flag_del = []
  1609. for deleted_tool in self.tool2tooldia:
  1610. if self.tool2tooldia[deleted_tool] == deleted_aperture:
  1611. flag_del.append(deleted_tool)
  1612. if flag_del:
  1613. for aperture_to_be_deleted in flag_del:
  1614. # delete the tool
  1615. self.tool2tooldia.pop(aperture_to_be_deleted, None)
  1616. flag_del = []
  1617. self.olddia_newdia.pop(deleted_aperture, None)
  1618. self.app.inform.emit(_("[success] Deleted aperture with code: {del_dia}").format(
  1619. del_dia=str(deleted_aperture)))
  1620. self.plot_all()
  1621. self.build_ui()
  1622. def on_tool_edit(self, item_changed):
  1623. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1624. self.apertures_table.itemChanged.disconnect()
  1625. # self.apertures_table.cellPressed.disconnect()
  1626. self.is_modified = True
  1627. geometry = []
  1628. current_table_dia_edited = None
  1629. if self.apertures_table.currentItem() is not None:
  1630. try:
  1631. current_table_dia_edited = float(self.apertures_table.currentItem().text())
  1632. except ValueError as e:
  1633. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1634. self.apertures_table.setCurrentItem(None)
  1635. return
  1636. row_of_item_changed = self.apertures_table.currentRow()
  1637. # rows start with 0, tools start with 1 so we adjust the value by 1
  1638. key_in_tool2tooldia = row_of_item_changed + 1
  1639. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1640. # aperture code is not used so we create a new tool with the desired diameter
  1641. if current_table_dia_edited not in self.olddia_newdia.values():
  1642. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1643. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1644. # update the dict that holds tool_no as key and tool_dia as value
  1645. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1646. # update the tool offset
  1647. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  1648. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  1649. self.plot_all()
  1650. else:
  1651. # aperture code is already in use so we move the pads from the prior tool to the new tool
  1652. factor = current_table_dia_edited / dia_changed
  1653. for shape in self.storage_dict[dia_changed].get_objects():
  1654. geometry.append(DrawToolShape(
  1655. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  1656. self.points_edit[current_table_dia_edited].append((0, 0))
  1657. self.add_gerber_shape(geometry, self.storage_dict[current_table_dia_edited])
  1658. self.on_aperture_delete(apid=dia_changed)
  1659. # delete the tool offset
  1660. self.gerber_obj.tool_offset.pop(dia_changed, None)
  1661. # we reactivate the signals after the after the tool editing
  1662. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1663. # self.apertures_table.cellPressed.connect(self.on_row_selected)
  1664. def on_name_activate(self):
  1665. self.edited_obj_name = self.name_entry.get_value()
  1666. def on_aptype_changed(self, current_text):
  1667. if current_text == 'R' or current_text == 'O':
  1668. self.apdim_lbl.show()
  1669. self.apdim_entry.show()
  1670. self.apsize_entry.setReadOnly(True)
  1671. else:
  1672. self.apdim_lbl.hide()
  1673. self.apdim_entry.hide()
  1674. self.apsize_entry.setReadOnly(False)
  1675. def activate_grb_editor(self):
  1676. # adjust the status of the menu entries related to the editor
  1677. self.app.ui.menueditedit.setDisabled(True)
  1678. self.app.ui.menueditok.setDisabled(False)
  1679. # adjust the visibility of some of the canvas context menu
  1680. self.app.ui.popmenu_edit.setVisible(False)
  1681. self.app.ui.popmenu_save.setVisible(True)
  1682. self.connect_canvas_event_handlers()
  1683. # init working objects
  1684. self.storage_dict = {}
  1685. self.current_storage = []
  1686. self.sorted_apid = []
  1687. self.new_apertures = {}
  1688. self.new_aperture_macros = {}
  1689. self.grb_plot_promises = []
  1690. self.olddia_newdia = {}
  1691. self.tool2tooldia = {}
  1692. self.shapes.enabled = True
  1693. self.tool_shape.enabled = True
  1694. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1695. self.app.ui.corner_snap_btn.setEnabled(True)
  1696. self.app.ui.snap_magnet.setVisible(True)
  1697. self.app.ui.corner_snap_btn.setVisible(True)
  1698. self.app.ui.grb_editor_menu.setDisabled(False)
  1699. self.app.ui.grb_editor_menu.menuAction().setVisible(True)
  1700. self.app.ui.update_obj_btn.setEnabled(True)
  1701. self.app.ui.grb_editor_cmenu.setEnabled(True)
  1702. self.app.ui.grb_edit_toolbar.setDisabled(False)
  1703. self.app.ui.grb_edit_toolbar.setVisible(True)
  1704. # self.app.ui.snap_toolbar.setDisabled(False)
  1705. # start with GRID toolbar activated
  1706. if self.app.ui.grid_snap_btn.isChecked() is False:
  1707. self.app.ui.grid_snap_btn.trigger()
  1708. # adjust the visibility of some of the canvas context menu
  1709. self.app.ui.popmenu_edit.setVisible(False)
  1710. self.app.ui.popmenu_save.setVisible(True)
  1711. # Tell the App that the editor is active
  1712. self.editor_active = True
  1713. def deactivate_grb_editor(self):
  1714. # adjust the status of the menu entries related to the editor
  1715. self.app.ui.menueditedit.setDisabled(False)
  1716. self.app.ui.menueditok.setDisabled(True)
  1717. # adjust the visibility of some of the canvas context menu
  1718. self.app.ui.popmenu_edit.setVisible(True)
  1719. self.app.ui.popmenu_save.setVisible(False)
  1720. self.disconnect_canvas_event_handlers()
  1721. self.clear()
  1722. self.app.ui.grb_edit_toolbar.setDisabled(True)
  1723. settings = QSettings("Open Source", "FlatCAM")
  1724. if settings.contains("layout"):
  1725. layout = settings.value('layout', type=str)
  1726. if layout == 'standard':
  1727. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1728. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1729. self.app.ui.corner_snap_btn.setEnabled(False)
  1730. self.app.ui.snap_magnet.setVisible(False)
  1731. self.app.ui.corner_snap_btn.setVisible(False)
  1732. elif layout == 'compact':
  1733. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1734. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1735. self.app.ui.corner_snap_btn.setEnabled(False)
  1736. self.app.ui.snap_magnet.setVisible(True)
  1737. self.app.ui.corner_snap_btn.setVisible(True)
  1738. else:
  1739. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1740. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1741. self.app.ui.corner_snap_btn.setEnabled(False)
  1742. self.app.ui.snap_magnet.setVisible(False)
  1743. self.app.ui.corner_snap_btn.setVisible(False)
  1744. # set the Editor Toolbar visibility to what was before entering in the Editor
  1745. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1746. else self.app.ui.grb_edit_toolbar.setVisible(True)
  1747. # Disable visuals
  1748. self.shapes.enabled = False
  1749. self.tool_shape.enabled = False
  1750. # self.app.app_cursor.enabled = False
  1751. # Tell the app that the editor is no longer active
  1752. self.editor_active = False
  1753. self.app.ui.grb_editor_menu.setDisabled(True)
  1754. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  1755. self.app.ui.update_obj_btn.setEnabled(False)
  1756. self.app.ui.g_editor_cmenu.setEnabled(False)
  1757. self.app.ui.grb_editor_cmenu.setEnabled(False)
  1758. self.app.ui.e_editor_cmenu.setEnabled(False)
  1759. # adjust the visibility of some of the canvas context menu
  1760. self.app.ui.popmenu_edit.setVisible(True)
  1761. self.app.ui.popmenu_save.setVisible(False)
  1762. # Show original geometry
  1763. if self.gerber_obj:
  1764. self.gerber_obj.visible = True
  1765. def connect_canvas_event_handlers(self):
  1766. ## Canvas events
  1767. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1768. # but those from FlatCAMGeoEditor
  1769. # first connect to new, then disconnect the old handlers
  1770. # don't ask why but if there is nothing connected I've seen issues
  1771. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1772. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1773. self.canvas.vis_connect('mouse_release', self.on_grb_click_release)
  1774. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1775. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1776. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1777. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1778. self.app.collection.view.clicked.disconnect()
  1779. def disconnect_canvas_event_handlers(self):
  1780. # we restore the key and mouse control to FlatCAMApp method
  1781. # first connect to new, then disconnect the old handlers
  1782. # don't ask why but if there is nothing connected I've seen issues
  1783. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1784. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1785. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1786. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1787. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1788. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1789. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1790. self.canvas.vis_disconnect('mouse_release', self.on_grb_click_release)
  1791. def clear(self):
  1792. self.active_tool = None
  1793. # self.shape_buffer = []
  1794. self.selected = []
  1795. self.shapes.clear(update=True)
  1796. self.tool_shape.clear(update=True)
  1797. def flatten(self, geometry=None, reset=True, pathonly=False):
  1798. """
  1799. Creates a list of non-iterable linear geometry objects.
  1800. Polygons are expanded into its exterior pathonly param if specified.
  1801. Results are placed in flat_geometry
  1802. :param geometry: Shapely type or list or list of list of such.
  1803. :param reset: Clears the contents of self.flat_geometry.
  1804. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  1805. """
  1806. if reset:
  1807. self.flat_geometry = []
  1808. ## If iterable, expand recursively.
  1809. try:
  1810. for geo in geometry:
  1811. if geo is not None:
  1812. self.flatten(geometry=geo, reset=False, pathonly=pathonly)
  1813. ## Not iterable, do the actual indexing and add.
  1814. except TypeError:
  1815. if pathonly and type(geometry) == Polygon:
  1816. self.flat_geometry.append(geometry.exterior)
  1817. self.flatten(geometry=geometry.interiors,
  1818. reset=False,
  1819. pathonly=True)
  1820. else:
  1821. self.flat_geometry.append(geometry)
  1822. return self.flat_geometry
  1823. def edit_fcgerber(self, orig_grb_obj):
  1824. """
  1825. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  1826. into the editor.
  1827. :param fcgeometry: FlatCAMExcellon
  1828. :return: None
  1829. """
  1830. self.deactivate_grb_editor()
  1831. self.activate_grb_editor()
  1832. # create a reference to the source object
  1833. self.gerber_obj = orig_grb_obj
  1834. self.gerber_obj_options = orig_grb_obj.options
  1835. # Hide original geometry
  1836. orig_grb_obj.visible = False
  1837. # Set selection tolerance
  1838. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1839. self.select_tool("select")
  1840. # we activate this after the initial build as we don't need to see the tool been populated
  1841. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1842. # and then add it to the storage elements (each storage elements is a member of a list
  1843. def job_thread(self, apid):
  1844. with self.app.proc_container.new(_("Adding aperture: %s geo ...") % str(apid)):
  1845. solid_storage_elem = []
  1846. follow_storage_elem = []
  1847. self.storage_dict[apid] = {}
  1848. # add the Gerber geometry to editor storage
  1849. for k, v in self.gerber_obj.apertures[apid].items():
  1850. try:
  1851. if k == 'solid_geometry':
  1852. for geo in v:
  1853. if geo:
  1854. self.add_gerber_shape(DrawToolShape(geo), solid_storage_elem)
  1855. self.storage_dict[apid][k] = solid_storage_elem
  1856. elif k == 'follow_geometry':
  1857. for geo in v:
  1858. if geo is not None:
  1859. self.add_gerber_shape(DrawToolShape(geo), follow_storage_elem)
  1860. self.storage_dict[apid][k] = follow_storage_elem
  1861. else:
  1862. self.storage_dict[apid][k] = v
  1863. except Exception as e:
  1864. log.debug("FlatCAMGrbEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  1865. # Check promises and clear if exists
  1866. while True:
  1867. try:
  1868. self.grb_plot_promises.remove(apid)
  1869. time.sleep(0.5)
  1870. except ValueError:
  1871. break
  1872. for apid in self.gerber_obj.apertures:
  1873. self.grb_plot_promises.append(apid)
  1874. self.app.worker_task.emit({'fcn': job_thread, 'params': [self, apid]})
  1875. # do the delayed plot only if there is something to plot (the gerber is not empty)
  1876. if bool(self.gerber_obj.apertures):
  1877. self.start_delayed_plot(check_period=1000)
  1878. else:
  1879. self.set_ui()
  1880. # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  1881. self.build_ui(first_run=True)
  1882. def update_fcgerber(self, grb_obj):
  1883. """
  1884. Create a new Gerber object that contain the edited content of the source Gerber object
  1885. :param grb_obj: FlatCAMGerber
  1886. :return: None
  1887. """
  1888. new_grb_name = self.edited_obj_name
  1889. # if the 'delayed plot' malfunctioned stop the QTimer
  1890. try:
  1891. self.plot_thread.stop()
  1892. except:
  1893. pass
  1894. if "_edit" in self.edited_obj_name:
  1895. try:
  1896. id = int(self.edited_obj_name[-1]) + 1
  1897. new_grb_name= self.edited_obj_name[:-1] + str(id)
  1898. except ValueError:
  1899. new_grb_name += "_1"
  1900. else:
  1901. new_grb_name = self.edited_obj_name + "_edit"
  1902. self.app.worker_task.emit({'fcn': self.new_edited_gerber,
  1903. 'params': [new_grb_name]})
  1904. # reset the tool table
  1905. self.apertures_table.clear()
  1906. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  1907. self.last_aperture_selected = None
  1908. # restore GUI to the Selected TAB
  1909. # Remove anything else in the GUI
  1910. self.app.ui.selected_scroll_area.takeWidget()
  1911. # Switch notebook to Selected page
  1912. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1913. def update_options(self, obj):
  1914. try:
  1915. if not obj.options:
  1916. obj.options = {}
  1917. obj.options['xmin'] = 0
  1918. obj.options['ymin'] = 0
  1919. obj.options['xmax'] = 0
  1920. obj.options['ymax'] = 0
  1921. return True
  1922. else:
  1923. return False
  1924. except AttributeError:
  1925. obj.options = {}
  1926. return True
  1927. def new_edited_gerber(self, outname):
  1928. """
  1929. Creates a new Gerber object for the edited Gerber. Thread-safe.
  1930. :param outname: Name of the resulting object. None causes the name to be that of the file.
  1931. :type outname: str
  1932. :return: None
  1933. """
  1934. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  1935. self.gerber_obj.options['name'].upper())
  1936. out_name = outname
  1937. local_storage_dict = deepcopy(self.storage_dict)
  1938. # How the object should be initialized
  1939. def obj_init(grb_obj, app_obj):
  1940. poly_buffer = []
  1941. follow_buffer = []
  1942. for storage_apid, storage_val in local_storage_dict.items():
  1943. grb_obj.apertures[storage_apid] = {}
  1944. for k, v in storage_val.items():
  1945. if k == 'solid_geometry':
  1946. grb_obj.apertures[storage_apid][k] = []
  1947. for geo in v:
  1948. new_geo = deepcopy(geo.geo)
  1949. grb_obj.apertures[storage_apid][k].append(new_geo)
  1950. poly_buffer.append(new_geo)
  1951. elif k == 'follow_geometry':
  1952. grb_obj.apertures[storage_apid][k] = []
  1953. for geo in v:
  1954. new_geo = deepcopy(geo.geo)
  1955. grb_obj.apertures[storage_apid][k].append(new_geo)
  1956. follow_buffer.append(new_geo)
  1957. else:
  1958. grb_obj.apertures[storage_apid][k] = deepcopy(v)
  1959. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  1960. new_poly = MultiPolygon(poly_buffer)
  1961. new_poly = new_poly.buffer(0.00000001)
  1962. new_poly = new_poly.buffer(-0.00000001)
  1963. grb_obj.solid_geometry = new_poly
  1964. grb_obj.follow_geometry = deepcopy(follow_buffer)
  1965. for k, v in self.gerber_obj_options.items():
  1966. if k == 'name':
  1967. grb_obj.options[k] = out_name
  1968. else:
  1969. grb_obj.options[k] = deepcopy(v)
  1970. grb_obj.source_file = []
  1971. grb_obj.multigeo = False
  1972. grb_obj.follow = False
  1973. try:
  1974. grb_obj.create_geometry()
  1975. except KeyError:
  1976. self.app.inform.emit(
  1977. _( "[ERROR_NOTCL] There are no Aperture definitions in the file. Aborting Gerber creation.")
  1978. )
  1979. except:
  1980. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1981. msg += traceback.format_exc()
  1982. app_obj.inform.emit(msg)
  1983. raise
  1984. # raise
  1985. with self.app.proc_container.new(_("Creating Gerber.")):
  1986. try:
  1987. self.app.new_object("gerber", outname, obj_init)
  1988. except Exception as e:
  1989. log.error("Error on object creation: %s" % str(e))
  1990. self.app.progress.emit(100)
  1991. return
  1992. self.app.inform.emit(_("[success] Gerber editing finished."))
  1993. # self.progress.emit(100)
  1994. def on_tool_select(self, tool):
  1995. """
  1996. Behavior of the toolbar. Tool initialization.
  1997. :rtype : None
  1998. """
  1999. current_tool = tool
  2000. self.app.log.debug("on_tool_select('%s')" % tool)
  2001. if self.last_aperture_selected is None and current_tool is not 'select':
  2002. # self.draw_app.select_tool('select')
  2003. self.complete = True
  2004. current_tool = 'select'
  2005. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No aperture is selected"))
  2006. # This is to make the group behave as radio group
  2007. if current_tool in self.tools_gerber:
  2008. if self.tools_gerber[current_tool]["button"].isChecked():
  2009. self.app.log.debug("%s is checked." % current_tool)
  2010. for t in self.tools_gerber:
  2011. if t != current_tool:
  2012. self.tools_gerber[t]["button"].setChecked(False)
  2013. # this is where the Editor toolbar classes (button's) are instantiated
  2014. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  2015. # self.app.inform.emit(self.active_tool.start_msg)
  2016. else:
  2017. self.app.log.debug("%s is NOT checked." % current_tool)
  2018. for t in self.tools_gerber:
  2019. self.tools_gerber[t]["button"].setChecked(False)
  2020. self.select_tool('select')
  2021. self.active_tool = FCApertureSelect(self)
  2022. def on_row_selected(self, row, col):
  2023. if col == 0:
  2024. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2025. if self.app.defaults["global_mselect_key"] == 'Control':
  2026. modifier_to_use = Qt.ControlModifier
  2027. else:
  2028. modifier_to_use = Qt.ShiftModifier
  2029. if key_modifier == modifier_to_use:
  2030. pass
  2031. else:
  2032. self.selected = []
  2033. try:
  2034. # selected_apid = str(self.tool2tooldia[row + 1])
  2035. selected_apid = self.apertures_table.item(row, 1).text()
  2036. self.last_aperture_selected = copy(selected_apid)
  2037. for obj in self.storage_dict[selected_apid]['solid_geometry']:
  2038. self.selected.append(obj)
  2039. except Exception as e:
  2040. self.app.log.debug(str(e))
  2041. self.plot_all()
  2042. def toolbar_tool_toggle(self, key):
  2043. self.options[key] = self.sender().isChecked()
  2044. return self.options[key]
  2045. def on_grb_shape_complete(self, storage=None, specific_shape=None):
  2046. self.app.log.debug("on_shape_complete()")
  2047. if specific_shape:
  2048. geo = specific_shape
  2049. else:
  2050. geo = self.active_tool.geometry
  2051. if geo is None:
  2052. return
  2053. if storage is not None:
  2054. # Add shape
  2055. self.add_gerber_shape(geo, storage)
  2056. else:
  2057. stora = self.storage_dict[self.last_aperture_selected]['solid_geometry']
  2058. self.add_gerber_shape(geo, storage=stora)
  2059. # Remove any utility shapes
  2060. self.delete_utility_geometry()
  2061. self.tool_shape.clear(update=True)
  2062. # Replot and reset tool.
  2063. self.plot_all()
  2064. def add_gerber_shape(self, shape, storage):
  2065. """
  2066. Adds a shape to the shape storage.
  2067. :param shape: Shape to be added.
  2068. :type shape: DrawToolShape
  2069. :return: None
  2070. """
  2071. # List of DrawToolShape?
  2072. if isinstance(shape, list):
  2073. for subshape in shape:
  2074. self.add_gerber_shape(subshape, storage)
  2075. return
  2076. assert isinstance(shape, DrawToolShape), \
  2077. "Expected a DrawToolShape, got %s" % str(type(shape))
  2078. assert shape.geo is not None, \
  2079. "Shape object has empty geometry (None)"
  2080. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2081. not isinstance(shape.geo, list), \
  2082. "Shape objects has empty geometry ([])"
  2083. if isinstance(shape, DrawToolUtilityShape):
  2084. self.utility.append(shape)
  2085. else:
  2086. storage.append(shape) # TODO: Check performance
  2087. def on_canvas_click(self, event):
  2088. """
  2089. event.x and .y have canvas coordinates
  2090. event.xdaya and .ydata have plot coordinates
  2091. :param event: Event object dispatched by Matplotlib
  2092. :return: None
  2093. """
  2094. if event.button is 1:
  2095. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2096. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2097. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2098. ### Snap coordinates
  2099. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2100. self.pos = (x, y)
  2101. # Selection with left mouse button
  2102. if self.active_tool is not None and event.button is 1:
  2103. # Dispatch event to active_tool
  2104. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2105. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2106. # If it is a shape generating tool
  2107. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2108. if self.current_storage is not None:
  2109. self.on_grb_shape_complete(self.current_storage)
  2110. self.build_ui()
  2111. # MS: always return to the Select Tool if modifier key is not pressed
  2112. # else return to the current tool
  2113. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2114. if self.app.defaults["global_mselect_key"] == 'Control':
  2115. modifier_to_use = Qt.ControlModifier
  2116. else:
  2117. modifier_to_use = Qt.ShiftModifier
  2118. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2119. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2120. if key_modifier == modifier_to_use:
  2121. self.select_tool(self.active_tool.name)
  2122. else:
  2123. self.select_tool("select")
  2124. return
  2125. if isinstance(self.active_tool, FCApertureSelect):
  2126. # self.app.log.debug("Replotting after click.")
  2127. self.plot_all()
  2128. else:
  2129. self.app.log.debug("No active tool to respond to click!")
  2130. def on_grb_click_release(self, event):
  2131. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2132. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2133. if self.app.grid_status():
  2134. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2135. else:
  2136. pos = (pos_canvas[0], pos_canvas[1])
  2137. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2138. # canvas menu
  2139. try:
  2140. if event.button == 2: # right click
  2141. if self.app.panning_action is True:
  2142. self.app.panning_action = False
  2143. else:
  2144. if self.in_action is False:
  2145. if self.active_tool.complete is False and not isinstance(self.active_tool, FCApertureSelect):
  2146. self.active_tool.complete = True
  2147. self.delete_utility_geometry()
  2148. self.select_tool('select')
  2149. else:
  2150. self.app.cursor = QtGui.QCursor()
  2151. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2152. else:
  2153. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2154. # right mouse click will finish the action
  2155. if isinstance(self.active_tool, FCShapeTool):
  2156. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  2157. self.active_tool.make()
  2158. if self.active_tool.complete:
  2159. self.on_grb_shape_complete()
  2160. self.app.inform.emit(_("[success] Done."))
  2161. # MS: always return to the Select Tool if modifier key is not pressed
  2162. # else return to the current tool but not for FCTrack
  2163. if isinstance(self.active_tool, FCTrack):
  2164. self.select_tool(self.active_tool.name)
  2165. else:
  2166. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2167. if (self.app.defaults["global_mselect_key"] == 'Control' and
  2168. key_modifier == Qt.ControlModifier) or \
  2169. (self.app.defaults["global_mselect_key"] == 'Shift' and
  2170. key_modifier == Qt.ShiftModifier):
  2171. self.select_tool(self.active_tool.name)
  2172. else:
  2173. self.select_tool("select")
  2174. except Exception as e:
  2175. log.warning("Error: %s" % str(e))
  2176. raise
  2177. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2178. # selection and then select a type of selection ("enclosing" or "touching")
  2179. try:
  2180. if event.button == 1: # left click
  2181. if self.app.selection_type is not None:
  2182. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2183. self.app.selection_type = None
  2184. elif isinstance(self.active_tool, FCApertureSelect):
  2185. # Dispatch event to active_tool
  2186. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2187. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2188. # self.app.inform.emit(msg)
  2189. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2190. # if there are selected objects then plot them
  2191. if self.selected:
  2192. self.plot_all()
  2193. except Exception as e:
  2194. log.warning("Error: %s" % str(e))
  2195. raise
  2196. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2197. """
  2198. :param start_pos: mouse position when the selection LMB click was done
  2199. :param end_pos: mouse position when the left mouse button is released
  2200. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2201. :type Bool
  2202. :return:
  2203. """
  2204. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2205. sel_aperture = set()
  2206. self.apertures_table.clearSelection()
  2207. self.app.delete_selection_shape()
  2208. for storage in self.storage_dict:
  2209. for obj in self.storage_dict[storage]['solid_geometry']:
  2210. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2211. (sel_type is False and poly_selection.intersects(obj.geo)):
  2212. if self.key == self.app.defaults["global_mselect_key"]:
  2213. if obj in self.selected:
  2214. self.selected.remove(obj)
  2215. else:
  2216. # add the object to the selected shapes
  2217. self.selected.append(obj)
  2218. sel_aperture.add(storage)
  2219. else:
  2220. self.selected.append(obj)
  2221. sel_aperture.add(storage)
  2222. try:
  2223. self.apertures_table.cellPressed.disconnect()
  2224. except:
  2225. pass
  2226. # select the aperture code of the selected geometry, in the tool table
  2227. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2228. for aper in sel_aperture:
  2229. for row in range(self.apertures_table.rowCount()):
  2230. if str(aper) == self.apertures_table.item(row, 1).text():
  2231. self.apertures_table.selectRow(row)
  2232. self.last_aperture_selected = aper
  2233. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2234. self.apertures_table.cellPressed.connect(self.on_row_selected)
  2235. self.plot_all()
  2236. def on_canvas_move(self, event):
  2237. """
  2238. Called on 'mouse_move' event
  2239. event.pos have canvas screen coordinates
  2240. :param event: Event object dispatched by VisPy SceneCavas
  2241. :return: None
  2242. """
  2243. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2244. event.xdata, event.ydata = pos[0], pos[1]
  2245. self.x = event.xdata
  2246. self.y = event.ydata
  2247. # Prevent updates on pan
  2248. # if len(event.buttons) > 0:
  2249. # return
  2250. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2251. if event.button == 2:
  2252. self.app.panning_action = True
  2253. return
  2254. else:
  2255. self.app.panning_action = False
  2256. try:
  2257. x = float(event.xdata)
  2258. y = float(event.ydata)
  2259. except TypeError:
  2260. return
  2261. if self.active_tool is None:
  2262. return
  2263. ### Snap coordinates
  2264. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  2265. self.snap_x = x
  2266. self.snap_y = y
  2267. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2268. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2269. "<b>Y</b>: %.4f" % (x, y))
  2270. if self.pos is None:
  2271. self.pos = (0, 0)
  2272. dx = x - self.pos[0]
  2273. dy = y - self.pos[1]
  2274. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2275. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2276. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2277. ### Utility geometry (animated)
  2278. geo = self.active_tool.utility_geometry(data=(x, y))
  2279. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2280. # Remove any previous utility shape
  2281. self.tool_shape.clear(update=True)
  2282. self.draw_utility_geometry(geo=geo)
  2283. ### Selection area on canvas section ###
  2284. if event.is_dragging == 1 and event.button == 1:
  2285. dx = pos[0] - self.pos[0]
  2286. self.app.delete_selection_shape()
  2287. if dx < 0:
  2288. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2289. color=self.app.defaults["global_alt_sel_line"],
  2290. face_color=self.app.defaults['global_alt_sel_fill'])
  2291. self.app.selection_type = False
  2292. else:
  2293. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2294. self.app.selection_type = True
  2295. else:
  2296. self.app.selection_type = None
  2297. # Update cursor
  2298. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2299. def on_canvas_key_release(self, event):
  2300. self.key = None
  2301. def draw_utility_geometry(self, geo):
  2302. if type(geo.geo) == list:
  2303. for el in geo.geo:
  2304. # Add the new utility shape
  2305. self.tool_shape.add(
  2306. shape=el, color=(self.app.defaults["global_draw_color"] + '80'),
  2307. # face_color=self.app.defaults['global_alt_sel_fill'],
  2308. update=False, layer=0, tolerance=None)
  2309. else:
  2310. # Add the new utility shape
  2311. self.tool_shape.add(
  2312. shape=geo.geo,
  2313. color=(self.app.defaults["global_draw_color"] + '80'),
  2314. # face_color=self.app.defaults['global_alt_sel_fill'],
  2315. update=False, layer=0, tolerance=None)
  2316. self.tool_shape.redraw()
  2317. def plot_all(self):
  2318. """
  2319. Plots all shapes in the editor.
  2320. :return: None
  2321. :rtype: None
  2322. """
  2323. with self.app.proc_container.new("Plotting"):
  2324. # self.app.log.debug("plot_all()")
  2325. self.shapes.clear(update=True)
  2326. for storage in self.storage_dict:
  2327. for shape in self.storage_dict[storage]['solid_geometry']:
  2328. if shape.geo is None:
  2329. continue
  2330. if shape in self.selected:
  2331. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'],
  2332. linewidth=2)
  2333. continue
  2334. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2335. for shape in self.utility:
  2336. self.plot_shape(geometry=shape.geo, linewidth=1)
  2337. continue
  2338. self.shapes.redraw()
  2339. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2340. """
  2341. Plots a geometric object or list of objects without rendering. Plotted objects
  2342. are returned as a list. This allows for efficient/animated rendering.
  2343. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2344. :param color: Shape color
  2345. :param linewidth: Width of lines in # of pixels.
  2346. :return: List of plotted elements.
  2347. """
  2348. # plot_elements = []
  2349. if geometry is None:
  2350. geometry = self.active_tool.geometry
  2351. try:
  2352. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0)
  2353. except AttributeError:
  2354. if type(geometry) == Point:
  2355. return
  2356. self.shapes.add(shape=geometry, color=color, face_color=color+'AF', layer=0)
  2357. def start_delayed_plot(self, check_period):
  2358. # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  2359. # self.plot_thread.start()
  2360. log.debug("FlatCAMGrbEditor --> Delayed Plot started.")
  2361. self.plot_thread = QtCore.QTimer()
  2362. self.plot_thread.setInterval(check_period)
  2363. self.plot_thread.timeout.connect(self.check_plot_finished)
  2364. self.plot_thread.start()
  2365. def check_plot_finished(self):
  2366. # print(self.grb_plot_promises)
  2367. try:
  2368. if not self.grb_plot_promises:
  2369. self.plot_thread.stop()
  2370. self.set_ui()
  2371. # now that we have data, create the GUI interface and add it to the Tool Tab
  2372. self.build_ui(first_run=True)
  2373. self.plot_all()
  2374. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  2375. # - perhaps is a bug in VisPy implementation
  2376. self.app.app_cursor.enabled = False
  2377. self.app.app_cursor.enabled = True
  2378. log.debug("FlatCAMGrbEditor --> delayed_plot finished")
  2379. except Exception:
  2380. traceback.print_exc()
  2381. def on_shape_complete(self):
  2382. self.app.log.debug("on_shape_complete()")
  2383. # Add shape
  2384. self.add_gerber_shape(self.active_tool.geometry)
  2385. # Remove any utility shapes
  2386. self.delete_utility_geometry()
  2387. self.tool_shape.clear(update=True)
  2388. # Replot and reset tool.
  2389. self.plot_all()
  2390. # self.active_tool = type(self.active_tool)(self)
  2391. def get_selected(self):
  2392. """
  2393. Returns list of shapes that are selected in the editor.
  2394. :return: List of shapes.
  2395. """
  2396. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2397. return self.selected
  2398. def delete_selected(self):
  2399. temp_ref = [s for s in self.selected]
  2400. for shape_sel in temp_ref:
  2401. self.delete_shape(shape_sel)
  2402. self.selected = []
  2403. self.build_ui()
  2404. self.app.inform.emit(_("[success] Done. Apertures deleted."))
  2405. def delete_shape(self, shape):
  2406. self.is_modified = True
  2407. if shape in self.utility:
  2408. self.utility.remove(shape)
  2409. return
  2410. for storage in self.storage_dict:
  2411. # try:
  2412. # self.storage_dict[storage].remove(shape)
  2413. # except:
  2414. # pass
  2415. if shape in self.storage_dict[storage]['solid_geometry']:
  2416. self.storage_dict[storage]['solid_geometry'].remove(shape)
  2417. if shape in self.selected:
  2418. self.selected.remove(shape) # TODO: Check performance
  2419. def delete_utility_geometry(self):
  2420. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2421. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2422. for_deletion = [shape for shape in self.utility]
  2423. for shape in for_deletion:
  2424. self.delete_shape(shape)
  2425. self.tool_shape.clear(update=True)
  2426. self.tool_shape.redraw()
  2427. def on_delete_btn(self):
  2428. self.delete_selected()
  2429. self.plot_all()
  2430. def select_tool(self, toolname):
  2431. """
  2432. Selects a drawing tool. Impacts the object and GUI.
  2433. :param toolname: Name of the tool.
  2434. :return: None
  2435. """
  2436. self.tools_gerber[toolname]["button"].setChecked(True)
  2437. self.on_tool_select(toolname)
  2438. def set_selected(self, shape):
  2439. # Remove and add to the end.
  2440. if shape in self.selected:
  2441. self.selected.remove(shape)
  2442. self.selected.append(shape)
  2443. def set_unselected(self, shape):
  2444. if shape in self.selected:
  2445. self.selected.remove(shape)
  2446. def on_array_type_combo(self):
  2447. if self.array_type_combo.currentIndex() == 0:
  2448. self.array_circular_frame.hide()
  2449. self.array_linear_frame.show()
  2450. else:
  2451. self.delete_utility_geometry()
  2452. self.array_circular_frame.show()
  2453. self.array_linear_frame.hide()
  2454. self.app.inform.emit(_("Click on the circular array Center position"))
  2455. def on_linear_angle_radio(self):
  2456. val = self.pad_axis_radio.get_value()
  2457. if val == 'A':
  2458. self.linear_angle_spinner.show()
  2459. self.linear_angle_label.show()
  2460. else:
  2461. self.linear_angle_spinner.hide()
  2462. self.linear_angle_label.hide()
  2463. def on_copy_button(self):
  2464. self.select_tool('copy')
  2465. return
  2466. def on_move_button(self):
  2467. self.select_tool('move')
  2468. return
  2469. def on_pad_add(self):
  2470. self.select_tool('pad')
  2471. def on_pad_add_array(self):
  2472. self.select_tool('array')
  2473. def on_track_add(self):
  2474. self.select_tool('track')
  2475. def on_region_add(self):
  2476. self.select_tool('region')
  2477. def on_poligonize(self):
  2478. self.select_tool('poligonize')
  2479. def on_buffer(self):
  2480. buff_value = 0.01
  2481. log.debug("FlatCAMGrbEditor.on_buffer()")
  2482. try:
  2483. buff_value = float(self.buffer_distance_entry.get_value())
  2484. except ValueError:
  2485. # try to convert comma to decimal point. if it's still not working error message and return
  2486. try:
  2487. buff_value = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  2488. self.buffer_distance_entry.set_value(buff_value)
  2489. except ValueError:
  2490. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2491. "Add it and retry."))
  2492. return
  2493. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2494. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2495. join_style = self.buffer_corner_cb.currentIndex() + 1
  2496. def buffer_recursion(geom, selection):
  2497. if type(geom) == list or type(geom) is MultiPolygon:
  2498. geoms = list()
  2499. for local_geom in geom:
  2500. geoms.append(buffer_recursion(local_geom, selection=selection))
  2501. return geoms
  2502. else:
  2503. if geom in selection:
  2504. return DrawToolShape(geom.geo.buffer(buff_value, join_style=join_style))
  2505. else:
  2506. return geom
  2507. if not self.apertures_table.selectedItems():
  2508. self.app.inform.emit(_(
  2509. "[WARNING_NOTCL] No aperture to buffer. Select at least one aperture and try again."
  2510. ))
  2511. return
  2512. for x in self.apertures_table.selectedItems():
  2513. try:
  2514. apid = self.apertures_table.item(x.row(), 1).text()
  2515. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  2516. self.storage_dict[apid]['solid_geometry'] = []
  2517. self.storage_dict[apid]['solid_geometry'] = temp_storage
  2518. except Exception as e:
  2519. log.debug("FlatCAMGrbEditor.buffer() --> %s" % str(e))
  2520. self.plot_all()
  2521. self.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2522. def on_scale(self):
  2523. scale_factor = 1.0
  2524. log.debug("FlatCAMGrbEditor.on_scale()")
  2525. try:
  2526. scale_factor = float(self.scale_factor_entry.get_value())
  2527. except ValueError:
  2528. # try to convert comma to decimal point. if it's still not working error message and return
  2529. try:
  2530. scale_factor = float(self.scale_factor_entry.get_value().replace(',', '.'))
  2531. self.scale_factor_entry.set_value(scale_factor)
  2532. except ValueError:
  2533. self.app.inform.emit(_("[WARNING_NOTCL] Scale factor value is missing or wrong format. "
  2534. "Add it and retry."))
  2535. return
  2536. def scale_recursion(geom, selection):
  2537. if type(geom) == list or type(geom) is MultiPolygon:
  2538. geoms = list()
  2539. for local_geom in geom:
  2540. geoms.append(scale_recursion(local_geom, selection=selection))
  2541. return geoms
  2542. else:
  2543. if geom in selection:
  2544. return DrawToolShape(affinity.scale(geom.geo, scale_factor, scale_factor, origin='center'))
  2545. else:
  2546. return geom
  2547. if not self.apertures_table.selectedItems():
  2548. self.app.inform.emit(_(
  2549. "[WARNING_NOTCL] No aperture to scale. Select at least one aperture and try again."
  2550. ))
  2551. return
  2552. for x in self.apertures_table.selectedItems():
  2553. try:
  2554. apid = self.apertures_table.item(x.row(), 1).text()
  2555. temp_storage = deepcopy(scale_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  2556. self.storage_dict[apid]['solid_geometry'] = []
  2557. self.storage_dict[apid]['solid_geometry'] = temp_storage
  2558. except Exception as e:
  2559. log.debug("FlatCAMGrbEditor.on_scale() --> %s" % str(e))
  2560. self.plot_all()
  2561. self.app.inform.emit(_("[success] Done. Scale Tool completed."))
  2562. def on_transform(self):
  2563. if type(self.active_tool) == FCTransform:
  2564. self.select_tool('select')
  2565. else:
  2566. self.select_tool('transform')
  2567. def hide_tool(self, tool_name):
  2568. # self.app.ui.notebook.setTabText(2, _("Tools"))
  2569. if tool_name == 'all':
  2570. self.apertures_frame.hide()
  2571. if tool_name == 'select':
  2572. self.apertures_frame.show()
  2573. if tool_name == 'buffer' or tool_name == 'all':
  2574. self.buffer_tool_frame.hide()
  2575. if tool_name == 'scale' or tool_name == 'all':
  2576. self.scale_tool_frame.hide()
  2577. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2578. class TransformEditorTool(FlatCAMTool):
  2579. """
  2580. Inputs to specify how to paint the selected polygons.
  2581. """
  2582. toolName = _("Transform Tool")
  2583. rotateName = _("Rotate")
  2584. skewName = _("Skew/Shear")
  2585. scaleName = _("Scale")
  2586. flipName = _("Mirror (Flip)")
  2587. offsetName = _("Offset")
  2588. def __init__(self, app, draw_app):
  2589. FlatCAMTool.__init__(self, app)
  2590. self.app = app
  2591. self.draw_app = draw_app
  2592. self.transform_lay = QtWidgets.QVBoxLayout()
  2593. self.layout.addLayout(self.transform_lay)
  2594. ## Title
  2595. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  2596. title_label.setStyleSheet("""
  2597. QLabel
  2598. {
  2599. font-size: 16px;
  2600. font-weight: bold;
  2601. }
  2602. """)
  2603. self.transform_lay.addWidget(title_label)
  2604. self.empty_label = QtWidgets.QLabel("")
  2605. self.empty_label.setFixedWidth(50)
  2606. self.empty_label1 = QtWidgets.QLabel("")
  2607. self.empty_label1.setFixedWidth(70)
  2608. self.empty_label2 = QtWidgets.QLabel("")
  2609. self.empty_label2.setFixedWidth(70)
  2610. self.empty_label3 = QtWidgets.QLabel("")
  2611. self.empty_label3.setFixedWidth(70)
  2612. self.empty_label4 = QtWidgets.QLabel("")
  2613. self.empty_label4.setFixedWidth(70)
  2614. self.transform_lay.addWidget(self.empty_label)
  2615. ## Rotate Title
  2616. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  2617. self.transform_lay.addWidget(rotate_title_label)
  2618. ## Layout
  2619. form_layout = QtWidgets.QFormLayout()
  2620. self.transform_lay.addLayout(form_layout)
  2621. form_child = QtWidgets.QHBoxLayout()
  2622. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  2623. self.rotate_label.setToolTip(
  2624. _("Angle for Rotation action, in degrees.\n"
  2625. "Float number between -360 and 359.\n"
  2626. "Positive numbers for CW motion.\n"
  2627. "Negative numbers for CCW motion.")
  2628. )
  2629. self.rotate_label.setFixedWidth(50)
  2630. self.rotate_entry = FCEntry()
  2631. # self.rotate_entry.setFixedWidth(60)
  2632. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2633. self.rotate_button = FCButton()
  2634. self.rotate_button.set_value(_("Rotate"))
  2635. self.rotate_button.setToolTip(
  2636. _("Rotate the selected shape(s).\n"
  2637. "The point of reference is the middle of\n"
  2638. "the bounding box for all selected shapes.")
  2639. )
  2640. self.rotate_button.setFixedWidth(60)
  2641. form_child.addWidget(self.rotate_entry)
  2642. form_child.addWidget(self.rotate_button)
  2643. form_layout.addRow(self.rotate_label, form_child)
  2644. self.transform_lay.addWidget(self.empty_label1)
  2645. ## Skew Title
  2646. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  2647. self.transform_lay.addWidget(skew_title_label)
  2648. ## Form Layout
  2649. form1_layout = QtWidgets.QFormLayout()
  2650. self.transform_lay.addLayout(form1_layout)
  2651. form1_child_1 = QtWidgets.QHBoxLayout()
  2652. form1_child_2 = QtWidgets.QHBoxLayout()
  2653. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  2654. self.skewx_label.setToolTip(
  2655. _("Angle for Skew action, in degrees.\n"
  2656. "Float number between -360 and 359.")
  2657. )
  2658. self.skewx_label.setFixedWidth(50)
  2659. self.skewx_entry = FCEntry()
  2660. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2661. # self.skewx_entry.setFixedWidth(60)
  2662. self.skewx_button = FCButton()
  2663. self.skewx_button.set_value(_("Skew X"))
  2664. self.skewx_button.setToolTip(
  2665. _("Skew/shear the selected shape(s).\n"
  2666. "The point of reference is the middle of\n"
  2667. "the bounding box for all selected shapes."))
  2668. self.skewx_button.setFixedWidth(60)
  2669. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  2670. self.skewy_label.setToolTip(
  2671. _("Angle for Skew action, in degrees.\n"
  2672. "Float number between -360 and 359.")
  2673. )
  2674. self.skewy_label.setFixedWidth(50)
  2675. self.skewy_entry = FCEntry()
  2676. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2677. # self.skewy_entry.setFixedWidth(60)
  2678. self.skewy_button = FCButton()
  2679. self.skewy_button.set_value(_("Skew Y"))
  2680. self.skewy_button.setToolTip(
  2681. _("Skew/shear the selected shape(s).\n"
  2682. "The point of reference is the middle of\n"
  2683. "the bounding box for all selected shapes."))
  2684. self.skewy_button.setFixedWidth(60)
  2685. form1_child_1.addWidget(self.skewx_entry)
  2686. form1_child_1.addWidget(self.skewx_button)
  2687. form1_child_2.addWidget(self.skewy_entry)
  2688. form1_child_2.addWidget(self.skewy_button)
  2689. form1_layout.addRow(self.skewx_label, form1_child_1)
  2690. form1_layout.addRow(self.skewy_label, form1_child_2)
  2691. self.transform_lay.addWidget(self.empty_label2)
  2692. ## Scale Title
  2693. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  2694. self.transform_lay.addWidget(scale_title_label)
  2695. ## Form Layout
  2696. form2_layout = QtWidgets.QFormLayout()
  2697. self.transform_lay.addLayout(form2_layout)
  2698. form2_child_1 = QtWidgets.QHBoxLayout()
  2699. form2_child_2 = QtWidgets.QHBoxLayout()
  2700. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  2701. self.scalex_label.setToolTip(
  2702. _("Factor for Scale action over X axis.")
  2703. )
  2704. self.scalex_label.setFixedWidth(50)
  2705. self.scalex_entry = FCEntry()
  2706. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2707. # self.scalex_entry.setFixedWidth(60)
  2708. self.scalex_button = FCButton()
  2709. self.scalex_button.set_value(_("Scale X"))
  2710. self.scalex_button.setToolTip(
  2711. _("Scale the selected shape(s).\n"
  2712. "The point of reference depends on \n"
  2713. "the Scale reference checkbox state."))
  2714. self.scalex_button.setFixedWidth(60)
  2715. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  2716. self.scaley_label.setToolTip(
  2717. _("Factor for Scale action over Y axis.")
  2718. )
  2719. self.scaley_label.setFixedWidth(50)
  2720. self.scaley_entry = FCEntry()
  2721. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2722. # self.scaley_entry.setFixedWidth(60)
  2723. self.scaley_button = FCButton()
  2724. self.scaley_button.set_value(_("Scale Y"))
  2725. self.scaley_button.setToolTip(
  2726. _("Scale the selected shape(s).\n"
  2727. "The point of reference depends on \n"
  2728. "the Scale reference checkbox state."))
  2729. self.scaley_button.setFixedWidth(60)
  2730. self.scale_link_cb = FCCheckBox()
  2731. self.scale_link_cb.set_value(True)
  2732. self.scale_link_cb.setText(_("Link"))
  2733. self.scale_link_cb.setToolTip(
  2734. _("Scale the selected shape(s)\n"
  2735. "using the Scale Factor X for both axis."))
  2736. self.scale_link_cb.setFixedWidth(50)
  2737. self.scale_zero_ref_cb = FCCheckBox()
  2738. self.scale_zero_ref_cb.set_value(True)
  2739. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  2740. self.scale_zero_ref_cb.setToolTip(
  2741. _("Scale the selected shape(s)\n"
  2742. "using the origin reference when checked,\n"
  2743. "and the center of the biggest bounding box\n"
  2744. "of the selected shapes when unchecked."))
  2745. form2_child_1.addWidget(self.scalex_entry)
  2746. form2_child_1.addWidget(self.scalex_button)
  2747. form2_child_2.addWidget(self.scaley_entry)
  2748. form2_child_2.addWidget(self.scaley_button)
  2749. form2_layout.addRow(self.scalex_label, form2_child_1)
  2750. form2_layout.addRow(self.scaley_label, form2_child_2)
  2751. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  2752. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button],
  2753. logic=False)
  2754. self.transform_lay.addWidget(self.empty_label3)
  2755. ## Offset Title
  2756. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  2757. self.transform_lay.addWidget(offset_title_label)
  2758. ## Form Layout
  2759. form3_layout = QtWidgets.QFormLayout()
  2760. self.transform_lay.addLayout(form3_layout)
  2761. form3_child_1 = QtWidgets.QHBoxLayout()
  2762. form3_child_2 = QtWidgets.QHBoxLayout()
  2763. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  2764. self.offx_label.setToolTip(
  2765. _("Value for Offset action on X axis.")
  2766. )
  2767. self.offx_label.setFixedWidth(50)
  2768. self.offx_entry = FCEntry()
  2769. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2770. # self.offx_entry.setFixedWidth(60)
  2771. self.offx_button = FCButton()
  2772. self.offx_button.set_value(_("Offset X"))
  2773. self.offx_button.setToolTip(
  2774. _("Offset the selected shape(s).\n"
  2775. "The point of reference is the middle of\n"
  2776. "the bounding box for all selected shapes.\n")
  2777. )
  2778. self.offx_button.setFixedWidth(60)
  2779. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  2780. self.offy_label.setToolTip(
  2781. _("Value for Offset action on Y axis.")
  2782. )
  2783. self.offy_label.setFixedWidth(50)
  2784. self.offy_entry = FCEntry()
  2785. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2786. # self.offy_entry.setFixedWidth(60)
  2787. self.offy_button = FCButton()
  2788. self.offy_button.set_value(_("Offset Y"))
  2789. self.offy_button.setToolTip(
  2790. _("Offset the selected shape(s).\n"
  2791. "The point of reference is the middle of\n"
  2792. "the bounding box for all selected shapes.\n")
  2793. )
  2794. self.offy_button.setFixedWidth(60)
  2795. form3_child_1.addWidget(self.offx_entry)
  2796. form3_child_1.addWidget(self.offx_button)
  2797. form3_child_2.addWidget(self.offy_entry)
  2798. form3_child_2.addWidget(self.offy_button)
  2799. form3_layout.addRow(self.offx_label, form3_child_1)
  2800. form3_layout.addRow(self.offy_label, form3_child_2)
  2801. self.transform_lay.addWidget(self.empty_label4)
  2802. ## Flip Title
  2803. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  2804. self.transform_lay.addWidget(flip_title_label)
  2805. ## Form Layout
  2806. form4_layout = QtWidgets.QFormLayout()
  2807. form4_child_hlay = QtWidgets.QHBoxLayout()
  2808. self.transform_lay.addLayout(form4_child_hlay)
  2809. self.transform_lay.addLayout(form4_layout)
  2810. form4_child_1 = QtWidgets.QHBoxLayout()
  2811. self.flipx_button = FCButton()
  2812. self.flipx_button.set_value(_("Flip on X"))
  2813. self.flipx_button.setToolTip(
  2814. _("Flip the selected shape(s) over the X axis.\n"
  2815. "Does not create a new shape.")
  2816. )
  2817. self.flipx_button.setFixedWidth(60)
  2818. self.flipy_button = FCButton()
  2819. self.flipy_button.set_value(_("Flip on Y"))
  2820. self.flipy_button.setToolTip(
  2821. _("Flip the selected shape(s) over the X axis.\n"
  2822. "Does not create a new shape.")
  2823. )
  2824. self.flipy_button.setFixedWidth(60)
  2825. self.flip_ref_cb = FCCheckBox()
  2826. self.flip_ref_cb.set_value(True)
  2827. self.flip_ref_cb.setText(_("Ref Pt"))
  2828. self.flip_ref_cb.setToolTip(
  2829. _("Flip the selected shape(s)\n"
  2830. "around the point in Point Entry Field.\n"
  2831. "\n"
  2832. "The point coordinates can be captured by\n"
  2833. "left click on canvas together with pressing\n"
  2834. "SHIFT key. \n"
  2835. "Then click Add button to insert coordinates.\n"
  2836. "Or enter the coords in format (x, y) in the\n"
  2837. "Point Entry field and click Flip on X(Y)")
  2838. )
  2839. self.flip_ref_cb.setFixedWidth(50)
  2840. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  2841. self.flip_ref_label.setToolTip(
  2842. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  2843. "The 'x' in (x, y) will be used when using Flip on X and\n"
  2844. "the 'y' in (x, y) will be used when using Flip on Y.")
  2845. )
  2846. self.flip_ref_label.setFixedWidth(50)
  2847. self.flip_ref_entry = EvalEntry2("(0, 0)")
  2848. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2849. # self.flip_ref_entry.setFixedWidth(60)
  2850. self.flip_ref_button = FCButton()
  2851. self.flip_ref_button.set_value(_("Add"))
  2852. self.flip_ref_button.setToolTip(
  2853. _("The point coordinates can be captured by\n"
  2854. "left click on canvas together with pressing\n"
  2855. "SHIFT key. Then click Add button to insert.")
  2856. )
  2857. self.flip_ref_button.setFixedWidth(60)
  2858. form4_child_hlay.addStretch()
  2859. form4_child_hlay.addWidget(self.flipx_button)
  2860. form4_child_hlay.addWidget(self.flipy_button)
  2861. form4_child_1.addWidget(self.flip_ref_entry)
  2862. form4_child_1.addWidget(self.flip_ref_button)
  2863. form4_layout.addRow(self.flip_ref_cb)
  2864. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  2865. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  2866. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  2867. self.transform_lay.addStretch()
  2868. ## Signals
  2869. self.rotate_button.clicked.connect(self.on_rotate)
  2870. self.skewx_button.clicked.connect(self.on_skewx)
  2871. self.skewy_button.clicked.connect(self.on_skewy)
  2872. self.scalex_button.clicked.connect(self.on_scalex)
  2873. self.scaley_button.clicked.connect(self.on_scaley)
  2874. self.offx_button.clicked.connect(self.on_offx)
  2875. self.offy_button.clicked.connect(self.on_offy)
  2876. self.flipx_button.clicked.connect(self.on_flipx)
  2877. self.flipy_button.clicked.connect(self.on_flipy)
  2878. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  2879. self.rotate_entry.returnPressed.connect(self.on_rotate)
  2880. self.skewx_entry.returnPressed.connect(self.on_skewx)
  2881. self.skewy_entry.returnPressed.connect(self.on_skewy)
  2882. self.scalex_entry.returnPressed.connect(self.on_scalex)
  2883. self.scaley_entry.returnPressed.connect(self.on_scaley)
  2884. self.offx_entry.returnPressed.connect(self.on_offx)
  2885. self.offy_entry.returnPressed.connect(self.on_offy)
  2886. self.set_tool_ui()
  2887. def run(self, toggle=True):
  2888. self.app.report_usage("Geo Editor Transform Tool()")
  2889. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  2890. if self.app.ui.splitter.sizes()[0] == 0:
  2891. self.app.ui.splitter.setSizes([1, 1])
  2892. if toggle:
  2893. try:
  2894. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  2895. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2896. else:
  2897. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  2898. except AttributeError:
  2899. pass
  2900. FlatCAMTool.run(self)
  2901. self.set_tool_ui()
  2902. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  2903. def install(self, icon=None, separator=None, **kwargs):
  2904. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  2905. def set_tool_ui(self):
  2906. ## Initialize form
  2907. if self.app.defaults["tools_transform_rotate"]:
  2908. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  2909. else:
  2910. self.rotate_entry.set_value(0.0)
  2911. if self.app.defaults["tools_transform_skew_x"]:
  2912. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  2913. else:
  2914. self.skewx_entry.set_value(0.0)
  2915. if self.app.defaults["tools_transform_skew_y"]:
  2916. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  2917. else:
  2918. self.skewy_entry.set_value(0.0)
  2919. if self.app.defaults["tools_transform_scale_x"]:
  2920. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  2921. else:
  2922. self.scalex_entry.set_value(1.0)
  2923. if self.app.defaults["tools_transform_scale_y"]:
  2924. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  2925. else:
  2926. self.scaley_entry.set_value(1.0)
  2927. if self.app.defaults["tools_transform_scale_link"]:
  2928. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  2929. else:
  2930. self.scale_link_cb.set_value(True)
  2931. if self.app.defaults["tools_transform_scale_reference"]:
  2932. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  2933. else:
  2934. self.scale_zero_ref_cb.set_value(True)
  2935. if self.app.defaults["tools_transform_offset_x"]:
  2936. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  2937. else:
  2938. self.offx_entry.set_value(0.0)
  2939. if self.app.defaults["tools_transform_offset_y"]:
  2940. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  2941. else:
  2942. self.offy_entry.set_value(0.0)
  2943. if self.app.defaults["tools_transform_mirror_reference"]:
  2944. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  2945. else:
  2946. self.flip_ref_cb.set_value(False)
  2947. if self.app.defaults["tools_transform_mirror_point"]:
  2948. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  2949. else:
  2950. self.flip_ref_entry.set_value((0, 0))
  2951. def template(self):
  2952. if not self.fcdraw.selected:
  2953. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  2954. return
  2955. self.draw_app.select_tool("select")
  2956. self.app.ui.notebook.setTabText(2, "Tools")
  2957. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  2958. self.app.ui.splitter.setSizes([0, 1])
  2959. def on_rotate(self, sig=None, val=None):
  2960. if val:
  2961. value = val
  2962. else:
  2963. try:
  2964. value = float(self.rotate_entry.get_value())
  2965. except ValueError:
  2966. # try to convert comma to decimal point. if it's still not working error message and return
  2967. try:
  2968. value = float(self.rotate_entry.get_value().replace(',', '.'))
  2969. except ValueError:
  2970. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  2971. "use a number."))
  2972. return
  2973. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  2974. 'params': [value]})
  2975. # self.on_rotate_action(value)
  2976. return
  2977. def on_flipx(self):
  2978. # self.on_flip("Y")
  2979. axis = 'Y'
  2980. self.app.worker_task.emit({'fcn': self.on_flip,
  2981. 'params': [axis]})
  2982. return
  2983. def on_flipy(self):
  2984. # self.on_flip("X")
  2985. axis = 'X'
  2986. self.app.worker_task.emit({'fcn': self.on_flip,
  2987. 'params': [axis]})
  2988. return
  2989. def on_flip_add_coords(self):
  2990. val = self.app.clipboard.text()
  2991. self.flip_ref_entry.set_value(val)
  2992. def on_skewx(self, sig=None, val=None):
  2993. if val:
  2994. value = val
  2995. else:
  2996. try:
  2997. value = float(self.skewx_entry.get_value())
  2998. except ValueError:
  2999. # try to convert comma to decimal point. if it's still not working error message and return
  3000. try:
  3001. value = float(self.skewx_entry.get_value().replace(',', '.'))
  3002. except ValueError:
  3003. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  3004. "use a number."))
  3005. return
  3006. # self.on_skew("X", value)
  3007. axis = 'X'
  3008. self.app.worker_task.emit({'fcn': self.on_skew,
  3009. 'params': [axis, value]})
  3010. return
  3011. def on_skewy(self, sig=None, val=None):
  3012. if val:
  3013. value = val
  3014. else:
  3015. try:
  3016. value = float(self.skewy_entry.get_value())
  3017. except ValueError:
  3018. # try to convert comma to decimal point. if it's still not working error message and return
  3019. try:
  3020. value = float(self.skewy_entry.get_value().replace(',', '.'))
  3021. except ValueError:
  3022. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  3023. "use a number."))
  3024. return
  3025. # self.on_skew("Y", value)
  3026. axis = 'Y'
  3027. self.app.worker_task.emit({'fcn': self.on_skew,
  3028. 'params': [axis, value]})
  3029. return
  3030. def on_scalex(self, sig=None, val=None):
  3031. if val:
  3032. xvalue = val
  3033. else:
  3034. try:
  3035. xvalue = float(self.scalex_entry.get_value())
  3036. except ValueError:
  3037. # try to convert comma to decimal point. if it's still not working error message and return
  3038. try:
  3039. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  3040. except ValueError:
  3041. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  3042. "use a number."))
  3043. return
  3044. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3045. if xvalue == 0:
  3046. xvalue = 1
  3047. if self.scale_link_cb.get_value():
  3048. yvalue = xvalue
  3049. else:
  3050. yvalue = 1
  3051. axis = 'X'
  3052. point = (0, 0)
  3053. if self.scale_zero_ref_cb.get_value():
  3054. self.app.worker_task.emit({'fcn': self.on_scale,
  3055. 'params': [axis, xvalue, yvalue, point]})
  3056. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  3057. else:
  3058. # self.on_scale("X", xvalue, yvalue)
  3059. self.app.worker_task.emit({'fcn': self.on_scale,
  3060. 'params': [axis, xvalue, yvalue]})
  3061. return
  3062. def on_scaley(self, sig=None, val=None):
  3063. xvalue = 1
  3064. if val:
  3065. yvalue = val
  3066. else:
  3067. try:
  3068. yvalue = float(self.scaley_entry.get_value())
  3069. except ValueError:
  3070. # try to convert comma to decimal point. if it's still not working error message and return
  3071. try:
  3072. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  3073. except ValueError:
  3074. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  3075. "use a number."))
  3076. return
  3077. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3078. if yvalue == 0:
  3079. yvalue = 1
  3080. axis = 'Y'
  3081. point = (0, 0)
  3082. if self.scale_zero_ref_cb.get_value():
  3083. self.app.worker_task.emit({'fcn': self.on_scale,
  3084. 'params': [axis, xvalue, yvalue, point]})
  3085. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  3086. else:
  3087. # self.on_scale("Y", xvalue, yvalue)
  3088. self.app.worker_task.emit({'fcn': self.on_scale,
  3089. 'params': [axis, xvalue, yvalue]})
  3090. return
  3091. def on_offx(self, sig=None, val=None):
  3092. if val:
  3093. value = val
  3094. else:
  3095. try:
  3096. value = float(self.offx_entry.get_value())
  3097. except ValueError:
  3098. # try to convert comma to decimal point. if it's still not working error message and return
  3099. try:
  3100. value = float(self.offx_entry.get_value().replace(',', '.'))
  3101. except ValueError:
  3102. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  3103. "use a number."))
  3104. return
  3105. # self.on_offset("X", value)
  3106. axis = 'X'
  3107. self.app.worker_task.emit({'fcn': self.on_offset,
  3108. 'params': [axis, value]})
  3109. return
  3110. def on_offy(self, sig=None, val=None):
  3111. if val:
  3112. value = val
  3113. else:
  3114. try:
  3115. value = float(self.offy_entry.get_value())
  3116. except ValueError:
  3117. # try to convert comma to decimal point. if it's still not working error message and return
  3118. try:
  3119. value = float(self.offy_entry.get_value().replace(',', '.'))
  3120. except ValueError:
  3121. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  3122. "use a number."))
  3123. return
  3124. # self.on_offset("Y", value)
  3125. axis = 'Y'
  3126. self.app.worker_task.emit({'fcn': self.on_offset,
  3127. 'params': [axis, value]})
  3128. return
  3129. def on_rotate_action(self, num):
  3130. shape_list = self.draw_app.selected
  3131. xminlist = []
  3132. yminlist = []
  3133. xmaxlist = []
  3134. ymaxlist = []
  3135. if not shape_list:
  3136. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  3137. return
  3138. else:
  3139. with self.app.proc_container.new(_("Appying Rotate")):
  3140. try:
  3141. # first get a bounding box to fit all
  3142. for sha in shape_list:
  3143. xmin, ymin, xmax, ymax = sha.bounds()
  3144. xminlist.append(xmin)
  3145. yminlist.append(ymin)
  3146. xmaxlist.append(xmax)
  3147. ymaxlist.append(ymax)
  3148. # get the minimum x,y and maximum x,y for all objects selected
  3149. xminimal = min(xminlist)
  3150. yminimal = min(yminlist)
  3151. xmaximal = max(xmaxlist)
  3152. ymaximal = max(ymaxlist)
  3153. self.app.progress.emit(20)
  3154. for sel_sha in shape_list:
  3155. px = 0.5 * (xminimal + xmaximal)
  3156. py = 0.5 * (yminimal + ymaximal)
  3157. sel_sha.rotate(-num, point=(px, py))
  3158. self.draw_app.plot_all()
  3159. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  3160. # self.draw_app.transform_complete.emit()
  3161. self.app.inform.emit(_("[success] Done. Rotate completed."))
  3162. self.app.progress.emit(100)
  3163. except Exception as e:
  3164. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3165. return
  3166. def on_flip(self, axis):
  3167. shape_list = self.draw_app.selected
  3168. xminlist = []
  3169. yminlist = []
  3170. xmaxlist = []
  3171. ymaxlist = []
  3172. if not shape_list:
  3173. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  3174. return
  3175. else:
  3176. with self.app.proc_container.new(_("Applying Flip")):
  3177. try:
  3178. # get mirroring coords from the point entry
  3179. if self.flip_ref_cb.isChecked():
  3180. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  3181. # get mirroing coords from the center of an all-enclosing bounding box
  3182. else:
  3183. # first get a bounding box to fit all
  3184. for sha in shape_list:
  3185. xmin, ymin, xmax, ymax = sha.bounds()
  3186. xminlist.append(xmin)
  3187. yminlist.append(ymin)
  3188. xmaxlist.append(xmax)
  3189. ymaxlist.append(ymax)
  3190. # get the minimum x,y and maximum x,y for all objects selected
  3191. xminimal = min(xminlist)
  3192. yminimal = min(yminlist)
  3193. xmaximal = max(xmaxlist)
  3194. ymaximal = max(ymaxlist)
  3195. px = 0.5 * (xminimal + xmaximal)
  3196. py = 0.5 * (yminimal + ymaximal)
  3197. self.app.progress.emit(20)
  3198. # execute mirroring
  3199. for sha in shape_list:
  3200. if axis is 'X':
  3201. sha.mirror('X', (px, py))
  3202. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  3203. elif axis is 'Y':
  3204. sha.mirror('Y', (px, py))
  3205. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  3206. self.draw_app.plot_all()
  3207. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3208. #
  3209. # self.draw_app.transform_complete.emit()
  3210. self.app.progress.emit(100)
  3211. except Exception as e:
  3212. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3213. return
  3214. def on_skew(self, axis, num):
  3215. shape_list = self.draw_app.selected
  3216. xminlist = []
  3217. yminlist = []
  3218. if not shape_list:
  3219. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  3220. return
  3221. else:
  3222. with self.app.proc_container.new(_("Applying Skew")):
  3223. try:
  3224. # first get a bounding box to fit all
  3225. for sha in shape_list:
  3226. xmin, ymin, xmax, ymax = sha.bounds()
  3227. xminlist.append(xmin)
  3228. yminlist.append(ymin)
  3229. # get the minimum x,y and maximum x,y for all objects selected
  3230. xminimal = min(xminlist)
  3231. yminimal = min(yminlist)
  3232. self.app.progress.emit(20)
  3233. for sha in shape_list:
  3234. if axis is 'X':
  3235. sha.skew(num, 0, point=(xminimal, yminimal))
  3236. elif axis is 'Y':
  3237. sha.skew(0, num, point=(xminimal, yminimal))
  3238. self.draw_app.plot_all()
  3239. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3240. #
  3241. # self.draw_app.transform_complete.emit()
  3242. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  3243. self.app.progress.emit(100)
  3244. except Exception as e:
  3245. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  3246. return
  3247. def on_scale(self, axis, xfactor, yfactor, point=None):
  3248. shape_list = self.draw_app.selected
  3249. xminlist = []
  3250. yminlist = []
  3251. xmaxlist = []
  3252. ymaxlist = []
  3253. if not shape_list:
  3254. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  3255. return
  3256. else:
  3257. with self.app.proc_container.new(_("Applying Scale")):
  3258. try:
  3259. # first get a bounding box to fit all
  3260. for sha in shape_list:
  3261. xmin, ymin, xmax, ymax = sha.bounds()
  3262. xminlist.append(xmin)
  3263. yminlist.append(ymin)
  3264. xmaxlist.append(xmax)
  3265. ymaxlist.append(ymax)
  3266. # get the minimum x,y and maximum x,y for all objects selected
  3267. xminimal = min(xminlist)
  3268. yminimal = min(yminlist)
  3269. xmaximal = max(xmaxlist)
  3270. ymaximal = max(ymaxlist)
  3271. self.app.progress.emit(20)
  3272. if point is None:
  3273. px = 0.5 * (xminimal + xmaximal)
  3274. py = 0.5 * (yminimal + ymaximal)
  3275. else:
  3276. px = 0
  3277. py = 0
  3278. for sha in shape_list:
  3279. sha.scale(xfactor, yfactor, point=(px, py))
  3280. self.draw_app.plot_all()
  3281. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3282. #
  3283. # self.draw_app.transform_complete.emit()
  3284. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  3285. self.app.progress.emit(100)
  3286. except Exception as e:
  3287. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  3288. return
  3289. def on_offset(self, axis, num):
  3290. shape_list = self.draw_app.selected
  3291. xminlist = []
  3292. yminlist = []
  3293. if not shape_list:
  3294. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  3295. return
  3296. else:
  3297. with self.app.proc_container.new(_("Applying Offset")):
  3298. try:
  3299. # first get a bounding box to fit all
  3300. for sha in shape_list:
  3301. xmin, ymin, xmax, ymax = sha.bounds()
  3302. xminlist.append(xmin)
  3303. yminlist.append(ymin)
  3304. # get the minimum x,y and maximum x,y for all objects selected
  3305. xminimal = min(xminlist)
  3306. yminimal = min(yminlist)
  3307. self.app.progress.emit(20)
  3308. for sha in shape_list:
  3309. if axis is 'X':
  3310. sha.offset((num, 0))
  3311. elif axis is 'Y':
  3312. sha.offset((0, num))
  3313. self.draw_app.plot_all()
  3314. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3315. #
  3316. # self.draw_app.transform_complete.emit()
  3317. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  3318. self.app.progress.emit(100)
  3319. except Exception as e:
  3320. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  3321. return
  3322. def on_rotate_key(self):
  3323. val_box = FCInputDialog(title=_("Rotate ..."),
  3324. text=_('Enter an Angle Value (degrees):'),
  3325. min=-359.9999, max=360.0000, decimals=4,
  3326. init_val=float(self.app.defaults['tools_transform_rotate']))
  3327. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  3328. val, ok = val_box.get_value()
  3329. if ok:
  3330. self.on_rotate(val=val)
  3331. self.app.inform.emit(
  3332. _("[success] Geometry shape rotate done...")
  3333. )
  3334. return
  3335. else:
  3336. self.app.inform.emit(
  3337. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  3338. )
  3339. def on_offx_key(self):
  3340. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3341. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  3342. text=(_('Enter a distance Value (%s):') % str(units)),
  3343. min=-9999.9999, max=10000.0000, decimals=4,
  3344. init_val=float(self.app.defaults['tools_transform_offset_x']))
  3345. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  3346. val, ok = val_box.get_value()
  3347. if ok:
  3348. self.on_offx(val=val)
  3349. self.app.inform.emit(
  3350. _("[success] Geometry shape offset on X axis done..."))
  3351. return
  3352. else:
  3353. self.app.inform.emit(
  3354. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  3355. def on_offy_key(self):
  3356. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3357. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  3358. text=(_('Enter a distance Value (%s):') % str(units)),
  3359. min=-9999.9999, max=10000.0000, decimals=4,
  3360. init_val=float(self.app.defaults['tools_transform_offset_y']))
  3361. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  3362. val, ok = val_box.get_value()
  3363. if ok:
  3364. self.on_offx(val=val)
  3365. self.app.inform.emit(
  3366. _("[success] Geometry shape offset on Y axis done..."))
  3367. return
  3368. else:
  3369. self.app.inform.emit(
  3370. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  3371. def on_skewx_key(self):
  3372. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  3373. text=_('Enter an Angle Value (degrees):'),
  3374. min=-359.9999, max=360.0000, decimals=4,
  3375. init_val=float(self.app.defaults['tools_transform_skew_x']))
  3376. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  3377. val, ok = val_box.get_value()
  3378. if ok:
  3379. self.on_skewx(val=val)
  3380. self.app.inform.emit(
  3381. _("[success] Geometry shape skew on X axis done..."))
  3382. return
  3383. else:
  3384. self.app.inform.emit(
  3385. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  3386. def on_skewy_key(self):
  3387. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  3388. text=_('Enter an Angle Value (degrees):'),
  3389. min=-359.9999, max=360.0000, decimals=4,
  3390. init_val=float(self.app.defaults['tools_transform_skew_y']))
  3391. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  3392. val, ok = val_box.get_value()
  3393. if ok:
  3394. self.on_skewx(val=val)
  3395. self.app.inform.emit(
  3396. _("[success] Geometry shape skew on Y axis done..."))
  3397. return
  3398. else:
  3399. self.app.inform.emit(
  3400. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))