FlatCAMGrbEditor.py 193 KB

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