FlatCAMGrbEditor.py 165 KB

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