FlatCAMGrbEditor.py 157 KB

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