FlatCAMGrbEditor.py 154 KB

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