FlatCAMGrbEditor.py 190 KB

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