FlatCAMGrbEditor.py 234 KB

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