FlatCAMGrbEditor.py 210 KB

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