FlatCAMGrbEditor.py 163 KB

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