FlatCAMGrbEditor.py 160 KB

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