FlatCAMGrbEditor.py 203 KB

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