FlatCAMGrbEditor.py 178 KB

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