FlatCAMGrbEditor.py 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974
  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 = EvalEntry()
  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.delaperture_btn.clicked.connect(self.on_aperture_delete)
  1186. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1187. self.app.ui.grb_add_pad_menuitem.triggered.connect(self.on_pad_add)
  1188. self.app.ui.grb_add_pad_array_menuitem.triggered.connect(self.on_pad_add_array)
  1189. self.app.ui.grb_add_track_menuitem.triggered.connect(self.on_track_add)
  1190. self.app.ui.grb_add_region_menuitem.triggered.connect(self.on_region_add)
  1191. self.app.ui.grb_convert_poly_menuitem.triggered.connect(self.on_poligonize)
  1192. self.app.ui.grb_add_buffer_menuitem.triggered.connect(self.on_buffer)
  1193. self.app.ui.grb_add_scale_menuitem.triggered.connect(self.on_scale)
  1194. self.app.ui.grb_transform_menuitem.triggered.connect(self.transform_tool.run)
  1195. self.app.ui.grb_copy_menuitem.triggered.connect(self.on_copy_button)
  1196. self.app.ui.grb_delete_menuitem.triggered.connect(self.on_delete_btn)
  1197. self.app.ui.grb_move_menuitem.triggered.connect(self.on_move_button)
  1198. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1199. self.pad_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1200. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1201. self.editor_active = False
  1202. def pool_recreated(self, pool):
  1203. self.shapes.pool = pool
  1204. self.tool_shape.pool = pool
  1205. def set_ui(self):
  1206. # updated units
  1207. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1208. self.olddia_newdia.clear()
  1209. self.tool2tooldia.clear()
  1210. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1211. for key in self.storage_dict:
  1212. self.olddia_newdia[key] = key
  1213. sort_temp = []
  1214. for aperture in self.olddia_newdia:
  1215. sort_temp.append(int(aperture))
  1216. self.sorted_apid = sorted(sort_temp)
  1217. # populate self.intial_table_rows dict with the tool number as keys and aperture codes as values
  1218. for i in range(len(self.sorted_apid)):
  1219. tt_aperture = self.sorted_apid[i]
  1220. self.tool2tooldia[i + 1] = tt_aperture
  1221. if self.units == "IN":
  1222. self.apsize_entry.set_value(0.039)
  1223. else:
  1224. self.apsize_entry.set_value(1.00)
  1225. # Init GUI
  1226. self.pad_array_size_entry.set_value(5)
  1227. self.pad_pitch_entry.set_value(2.54)
  1228. self.pad_angle_entry.set_value(12)
  1229. self.pad_direction_radio.set_value('CW')
  1230. self.pad_axis_radio.set_value('X')
  1231. def build_ui(self, first_run=None):
  1232. try:
  1233. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1234. self.apertures_table.itemChanged.disconnect()
  1235. except:
  1236. pass
  1237. try:
  1238. self.apertures_table.cellPressed.disconnect()
  1239. except:
  1240. pass
  1241. # updated units
  1242. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1243. # make a new name for the new Excellon object (the one with edited content)
  1244. self.edited_obj_name = self.gerber_obj.options['name']
  1245. self.name_entry.set_value(self.edited_obj_name)
  1246. self.apertures_row = 0
  1247. aper_no = self.apertures_row + 1
  1248. sort = []
  1249. for k, v in list(self.storage_dict.items()):
  1250. sort.append(int(k))
  1251. sorted_apertures = sorted(sort)
  1252. sort = []
  1253. for k, v in list(self.gerber_obj.aperture_macros.items()):
  1254. sort.append(k)
  1255. sorted_macros = sorted(sort)
  1256. n = len(sorted_apertures) + len(sorted_macros)
  1257. self.apertures_table.setRowCount(n)
  1258. for ap_code in sorted_apertures:
  1259. ap_code = str(ap_code)
  1260. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1261. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1262. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1263. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1264. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1265. ap_type_item = QtWidgets.QTableWidgetItem(str(self.storage_dict[ap_code]['type']))
  1266. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1267. if str(self.storage_dict[ap_code]['type']) == 'R' or str(self.storage_dict[ap_code]['type']) == 'O':
  1268. ap_dim_item = QtWidgets.QTableWidgetItem(
  1269. '%.4f, %.4f' % (self.storage_dict[ap_code]['width'],
  1270. self.storage_dict[ap_code]['height']
  1271. )
  1272. )
  1273. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1274. elif str(self.storage_dict[ap_code]['type']) == 'P':
  1275. ap_dim_item = QtWidgets.QTableWidgetItem(
  1276. '%.4f, %.4f' % (self.storage_dict[ap_code]['diam'],
  1277. self.storage_dict[ap_code]['nVertices'])
  1278. )
  1279. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1280. else:
  1281. ap_dim_item = QtWidgets.QTableWidgetItem('')
  1282. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1283. try:
  1284. if self.storage_dict[ap_code]['size'] is not None:
  1285. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  1286. float(self.storage_dict[ap_code]['size']))
  1287. else:
  1288. ap_size_item = QtWidgets.QTableWidgetItem('')
  1289. except KeyError:
  1290. ap_size_item = QtWidgets.QTableWidgetItem('')
  1291. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1292. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1293. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1294. self.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  1295. self.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  1296. self.apertures_row += 1
  1297. if first_run is True:
  1298. # set now the last aperture selected
  1299. self.last_aperture_selected = ap_code
  1300. for ap_code in sorted_macros:
  1301. ap_code = str(ap_code)
  1302. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1303. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1304. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1305. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1306. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  1307. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1308. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1309. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1310. self.apertures_row += 1
  1311. if first_run is True:
  1312. # set now the last aperture selected
  1313. self.last_aperture_selected = ap_code
  1314. self.apertures_table.selectColumn(0)
  1315. self.apertures_table.resizeColumnsToContents()
  1316. self.apertures_table.resizeRowsToContents()
  1317. vertical_header = self.apertures_table.verticalHeader()
  1318. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1319. vertical_header.hide()
  1320. self.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1321. horizontal_header = self.apertures_table.horizontalHeader()
  1322. horizontal_header.setMinimumSectionSize(10)
  1323. horizontal_header.setDefaultSectionSize(70)
  1324. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1325. horizontal_header.resizeSection(0, 20)
  1326. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  1327. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1328. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1329. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  1330. self.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1331. self.apertures_table.setSortingEnabled(False)
  1332. self.apertures_table.setMinimumHeight(self.apertures_table.getHeight())
  1333. self.apertures_table.setMaximumHeight(self.apertures_table.getHeight())
  1334. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1335. self.apertures_table.clearSelection()
  1336. # Remove anything else in the GUI Selected Tab
  1337. self.app.ui.selected_scroll_area.takeWidget()
  1338. # Put ourself in the GUI Selected Tab
  1339. self.app.ui.selected_scroll_area.setWidget(self.grb_edit_widget)
  1340. # Switch notebook to Selected page
  1341. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1342. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1343. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1344. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1345. # for convenience set the next aperture code in the apcode field
  1346. try:
  1347. self.apcode_entry.set_value(max(self.tool2tooldia.values()) + 1)
  1348. except ValueError:
  1349. # this means that the edited object has no apertures so we start with 10 (Gerber specifications)
  1350. self.apcode_entry.set_value(10)
  1351. def on_aperture_add(self, apid=None):
  1352. self.is_modified = True
  1353. if apid:
  1354. ap_id = apid
  1355. else:
  1356. try:
  1357. ap_id = str(self.apcode_entry.get_value())
  1358. except ValueError:
  1359. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1360. "Add it and retry."))
  1361. return
  1362. if ap_id == '':
  1363. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1364. "Add it and retry."))
  1365. return
  1366. if ap_id == '0':
  1367. if ap_id not in self.olddia_newdia:
  1368. self.storage_dict[ap_id] = {}
  1369. self.storage_dict[ap_id]['type'] = 'REG'
  1370. size_val = 0
  1371. self.apsize_entry.set_value(size_val)
  1372. self.storage_dict[ap_id]['size'] = size_val
  1373. self.storage_dict[ap_id]['solid_geometry'] = []
  1374. self.storage_dict[ap_id]['follow_geometry'] = []
  1375. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1376. # each time a aperture code is edited or added
  1377. self.olddia_newdia[ap_id] = ap_id
  1378. else:
  1379. if ap_id not in self.olddia_newdia:
  1380. self.storage_dict[ap_id] = {}
  1381. type_val = self.aptype_cb.currentText()
  1382. self.storage_dict[ap_id]['type'] = type_val
  1383. if type_val == 'R' or type_val == 'O':
  1384. try:
  1385. dims = self.apdim_entry.get_value()
  1386. self.storage_dict[ap_id]['width'] = dims[0]
  1387. self.storage_dict[ap_id]['height'] = dims[1]
  1388. size_val = math.sqrt((dims[0] ** 2) + (dims[1] ** 2))
  1389. self.apsize_entry.set_value(size_val)
  1390. except Exception as e:
  1391. log.error("FlatCAMGrbEditor.on_aperture_add() --> the R or O aperture dims has to be in a "
  1392. "tuple format (x,y)\nError: %s" % str(e))
  1393. self.app.inform.emit(_("[WARNING_NOTCL] Aperture dimensions value is missing or wrong format. "
  1394. "Add it in format (width, height) and retry."))
  1395. return
  1396. else:
  1397. try:
  1398. size_val = float(self.apsize_entry.get_value())
  1399. except ValueError:
  1400. # try to convert comma to decimal point. if it's still not working error message and return
  1401. try:
  1402. size_val = float(self.apsize_entry.get_value().replace(',', '.'))
  1403. self.apsize_entry.set_value(size_val)
  1404. except ValueError:
  1405. self.app.inform.emit(_("[WARNING_NOTCL] Aperture size value is missing or wrong format. "
  1406. "Add it and retry."))
  1407. return
  1408. self.storage_dict[ap_id]['size'] = size_val
  1409. self.storage_dict[ap_id]['solid_geometry'] = []
  1410. self.storage_dict[ap_id]['follow_geometry'] = []
  1411. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1412. # each time a aperture code is edited or added
  1413. self.olddia_newdia[ap_id] = ap_id
  1414. else:
  1415. self.app.inform.emit(_("[WARNING_NOTCL] Aperture already in the aperture table."))
  1416. return
  1417. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1418. # we add a new entry in the tool2tooldia dict
  1419. self.tool2tooldia[len(self.olddia_newdia)] = int(ap_id)
  1420. self.app.inform.emit(_("[success] Added new aperture with code: {apid}").format(apid=str(ap_id)))
  1421. self.build_ui()
  1422. self.last_aperture_selected = ap_id
  1423. # make a quick sort through the tool2tooldia dict so we find which row to select
  1424. row_to_be_selected = None
  1425. for key in sorted(self.tool2tooldia):
  1426. if self.tool2tooldia[key] == int(ap_id):
  1427. row_to_be_selected = int(key) - 1
  1428. break
  1429. self.apertures_table.selectRow(row_to_be_selected)
  1430. def on_aperture_delete(self, apid=None):
  1431. self.is_modified = True
  1432. deleted_apcode_list = []
  1433. deleted_tool_offset_list = []
  1434. try:
  1435. if apid is None or apid is False:
  1436. # deleted_tool_dia = float(self.apertures_table.item(self.apertures_table.currentRow(), 1).text())
  1437. for index in self.apertures_table.selectionModel().selectedRows():
  1438. row = index.row()
  1439. deleted_apcode_list.append(self.apertures_table.item(row, 1).text())
  1440. else:
  1441. if isinstance(apid, list):
  1442. for dd in apid:
  1443. deleted_apcode_list.append(dd)
  1444. else:
  1445. deleted_apcode_list.append(apid)
  1446. except:
  1447. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1448. return
  1449. for deleted_aperture in deleted_apcode_list:
  1450. # delete the storage used for that tool
  1451. self.storage_dict.pop(deleted_aperture, None)
  1452. # I've added this flag_del variable because dictionary don't like
  1453. # having keys deleted while iterating through them
  1454. flag_del = []
  1455. for deleted_tool in self.tool2tooldia:
  1456. if self.tool2tooldia[deleted_tool] == deleted_aperture:
  1457. flag_del.append(deleted_tool)
  1458. if flag_del:
  1459. for aperture_to_be_deleted in flag_del:
  1460. # delete the tool
  1461. self.tool2tooldia.pop(aperture_to_be_deleted, None)
  1462. flag_del = []
  1463. self.olddia_newdia.pop(deleted_aperture, None)
  1464. self.app.inform.emit(_("[success] Deleted aperture with code: {del_dia}").format(
  1465. del_dia=str(deleted_aperture)))
  1466. self.plot_all()
  1467. self.build_ui()
  1468. def on_tool_edit(self, item_changed):
  1469. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1470. self.apertures_table.itemChanged.disconnect()
  1471. # self.apertures_table.cellPressed.disconnect()
  1472. self.is_modified = True
  1473. geometry = []
  1474. current_table_dia_edited = None
  1475. if self.apertures_table.currentItem() is not None:
  1476. try:
  1477. current_table_dia_edited = float(self.apertures_table.currentItem().text())
  1478. except ValueError as e:
  1479. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1480. self.apertures_table.setCurrentItem(None)
  1481. return
  1482. row_of_item_changed = self.apertures_table.currentRow()
  1483. # rows start with 0, tools start with 1 so we adjust the value by 1
  1484. key_in_tool2tooldia = row_of_item_changed + 1
  1485. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1486. # aperture code is not used so we create a new tool with the desired diameter
  1487. if current_table_dia_edited not in self.olddia_newdia.values():
  1488. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1489. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1490. # update the dict that holds tool_no as key and tool_dia as value
  1491. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1492. # update the tool offset
  1493. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  1494. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  1495. self.plot_all()
  1496. else:
  1497. # aperture code is already in use so we move the pads from the prior tool to the new tool
  1498. factor = current_table_dia_edited / dia_changed
  1499. for shape in self.storage_dict[dia_changed].get_objects():
  1500. geometry.append(DrawToolShape(
  1501. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  1502. self.points_edit[current_table_dia_edited].append((0, 0))
  1503. self.add_gerber_shape(geometry, self.storage_dict[current_table_dia_edited])
  1504. self.on_aperture_delete(apid=dia_changed)
  1505. # delete the tool offset
  1506. self.gerber_obj.tool_offset.pop(dia_changed, None)
  1507. # we reactivate the signals after the after the tool editing
  1508. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1509. # self.apertures_table.cellPressed.connect(self.on_row_selected)
  1510. def on_name_activate(self):
  1511. self.edited_obj_name = self.name_entry.get_value()
  1512. def on_aptype_changed(self, current_text):
  1513. if current_text == 'R' or current_text == 'O':
  1514. self.apdim_lbl.show()
  1515. self.apdim_entry.show()
  1516. self.apsize_entry.setReadOnly(True)
  1517. else:
  1518. self.apdim_lbl.hide()
  1519. self.apdim_entry.hide()
  1520. self.apsize_entry.setReadOnly(False)
  1521. def activate_grb_editor(self):
  1522. # adjust the status of the menu entries related to the editor
  1523. self.app.ui.menueditedit.setDisabled(True)
  1524. self.app.ui.menueditok.setDisabled(False)
  1525. # adjust the visibility of some of the canvas context menu
  1526. self.app.ui.popmenu_edit.setVisible(False)
  1527. self.app.ui.popmenu_save.setVisible(True)
  1528. self.connect_canvas_event_handlers()
  1529. # init working objects
  1530. self.storage_dict = {}
  1531. self.current_storage = []
  1532. self.sorted_apid = []
  1533. self.new_apertures = {}
  1534. self.new_aperture_macros = {}
  1535. self.grb_plot_promises = []
  1536. self.olddia_newdia = {}
  1537. self.tool2tooldia = {}
  1538. self.shapes.enabled = True
  1539. self.tool_shape.enabled = True
  1540. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1541. self.app.ui.corner_snap_btn.setEnabled(True)
  1542. self.app.ui.snap_magnet.setVisible(True)
  1543. self.app.ui.corner_snap_btn.setVisible(True)
  1544. self.app.ui.grb_editor_menu.setDisabled(False)
  1545. self.app.ui.grb_editor_menu.menuAction().setVisible(True)
  1546. self.app.ui.update_obj_btn.setEnabled(True)
  1547. self.app.ui.grb_editor_cmenu.setEnabled(True)
  1548. self.app.ui.grb_edit_toolbar.setDisabled(False)
  1549. self.app.ui.grb_edit_toolbar.setVisible(True)
  1550. # self.app.ui.snap_toolbar.setDisabled(False)
  1551. # start with GRID toolbar activated
  1552. if self.app.ui.grid_snap_btn.isChecked() is False:
  1553. self.app.ui.grid_snap_btn.trigger()
  1554. # adjust the visibility of some of the canvas context menu
  1555. self.app.ui.popmenu_edit.setVisible(False)
  1556. self.app.ui.popmenu_save.setVisible(True)
  1557. # Tell the App that the editor is active
  1558. self.editor_active = True
  1559. def deactivate_grb_editor(self):
  1560. # adjust the status of the menu entries related to the editor
  1561. self.app.ui.menueditedit.setDisabled(False)
  1562. self.app.ui.menueditok.setDisabled(True)
  1563. # adjust the visibility of some of the canvas context menu
  1564. self.app.ui.popmenu_edit.setVisible(True)
  1565. self.app.ui.popmenu_save.setVisible(False)
  1566. self.disconnect_canvas_event_handlers()
  1567. self.clear()
  1568. self.app.ui.grb_edit_toolbar.setDisabled(True)
  1569. settings = QSettings("Open Source", "FlatCAM")
  1570. if settings.contains("layout"):
  1571. layout = settings.value('layout', type=str)
  1572. if layout == 'standard':
  1573. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1574. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1575. self.app.ui.corner_snap_btn.setEnabled(False)
  1576. self.app.ui.snap_magnet.setVisible(False)
  1577. self.app.ui.corner_snap_btn.setVisible(False)
  1578. elif layout == 'compact':
  1579. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1580. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1581. self.app.ui.corner_snap_btn.setEnabled(False)
  1582. self.app.ui.snap_magnet.setVisible(True)
  1583. self.app.ui.corner_snap_btn.setVisible(True)
  1584. else:
  1585. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1586. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1587. self.app.ui.corner_snap_btn.setEnabled(False)
  1588. self.app.ui.snap_magnet.setVisible(False)
  1589. self.app.ui.corner_snap_btn.setVisible(False)
  1590. # set the Editor Toolbar visibility to what was before entering in the Editor
  1591. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1592. else self.app.ui.grb_edit_toolbar.setVisible(True)
  1593. # Disable visuals
  1594. self.shapes.enabled = False
  1595. self.tool_shape.enabled = False
  1596. # self.app.app_cursor.enabled = False
  1597. # Tell the app that the editor is no longer active
  1598. self.editor_active = False
  1599. self.app.ui.grb_editor_menu.setDisabled(True)
  1600. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  1601. self.app.ui.update_obj_btn.setEnabled(False)
  1602. self.app.ui.g_editor_cmenu.setEnabled(False)
  1603. self.app.ui.grb_editor_cmenu.setEnabled(False)
  1604. self.app.ui.e_editor_cmenu.setEnabled(False)
  1605. # adjust the visibility of some of the canvas context menu
  1606. self.app.ui.popmenu_edit.setVisible(True)
  1607. self.app.ui.popmenu_save.setVisible(False)
  1608. # Show original geometry
  1609. if self.gerber_obj:
  1610. self.gerber_obj.visible = True
  1611. def connect_canvas_event_handlers(self):
  1612. ## Canvas events
  1613. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1614. # but those from FlatCAMGeoEditor
  1615. # first connect to new, then disconnect the old handlers
  1616. # don't ask why but if there is nothing connected I've seen issues
  1617. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1618. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1619. self.canvas.vis_connect('mouse_release', self.on_grb_click_release)
  1620. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1621. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1622. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1623. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1624. self.app.collection.view.clicked.disconnect()
  1625. def disconnect_canvas_event_handlers(self):
  1626. # we restore the key and mouse control to FlatCAMApp method
  1627. # first connect to new, then disconnect the old handlers
  1628. # don't ask why but if there is nothing connected I've seen issues
  1629. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1630. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1631. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1632. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1633. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1634. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1635. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1636. self.canvas.vis_disconnect('mouse_release', self.on_grb_click_release)
  1637. def clear(self):
  1638. self.active_tool = None
  1639. # self.shape_buffer = []
  1640. self.selected = []
  1641. self.shapes.clear(update=True)
  1642. self.tool_shape.clear(update=True)
  1643. def flatten(self, geometry=None, reset=True, pathonly=False):
  1644. """
  1645. Creates a list of non-iterable linear geometry objects.
  1646. Polygons are expanded into its exterior pathonly param if specified.
  1647. Results are placed in flat_geometry
  1648. :param geometry: Shapely type or list or list of list of such.
  1649. :param reset: Clears the contents of self.flat_geometry.
  1650. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  1651. """
  1652. if reset:
  1653. self.flat_geometry = []
  1654. ## If iterable, expand recursively.
  1655. try:
  1656. for geo in geometry:
  1657. if geo is not None:
  1658. self.flatten(geometry=geo, reset=False, pathonly=pathonly)
  1659. ## Not iterable, do the actual indexing and add.
  1660. except TypeError:
  1661. if pathonly and type(geometry) == Polygon:
  1662. self.flat_geometry.append(geometry.exterior)
  1663. self.flatten(geometry=geometry.interiors,
  1664. reset=False,
  1665. pathonly=True)
  1666. else:
  1667. self.flat_geometry.append(geometry)
  1668. return self.flat_geometry
  1669. def edit_fcgerber(self, orig_grb_obj):
  1670. """
  1671. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  1672. into the editor.
  1673. :param fcgeometry: FlatCAMExcellon
  1674. :return: None
  1675. """
  1676. self.deactivate_grb_editor()
  1677. self.activate_grb_editor()
  1678. # create a reference to the source object
  1679. self.gerber_obj = orig_grb_obj
  1680. self.gerber_obj_options = orig_grb_obj.options
  1681. # Hide original geometry
  1682. orig_grb_obj.visible = False
  1683. # Set selection tolerance
  1684. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  1685. self.select_tool("select")
  1686. # we activate this after the initial build as we don't need to see the tool been populated
  1687. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1688. # and then add it to the storage elements (each storage elements is a member of a list
  1689. def job_thread(self, apid):
  1690. with self.app.proc_container.new(_("Adding aperture: %s geo ...") % str(apid)):
  1691. solid_storage_elem = []
  1692. follow_storage_elem = []
  1693. self.storage_dict[apid] = {}
  1694. # add the Gerber geometry to editor storage
  1695. for k, v in self.gerber_obj.apertures[apid].items():
  1696. try:
  1697. if k == 'solid_geometry':
  1698. for geo in v:
  1699. if geo:
  1700. self.add_gerber_shape(DrawToolShape(geo), solid_storage_elem)
  1701. self.storage_dict[apid][k] = solid_storage_elem
  1702. elif k == 'follow_geometry':
  1703. for geo in v:
  1704. if geo is not None:
  1705. self.add_gerber_shape(DrawToolShape(geo), follow_storage_elem)
  1706. self.storage_dict[apid][k] = follow_storage_elem
  1707. else:
  1708. self.storage_dict[apid][k] = v
  1709. except Exception as e:
  1710. log.debug("FlatCAMGrbEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  1711. # Check promises and clear if exists
  1712. while True:
  1713. try:
  1714. self.grb_plot_promises.remove(apid)
  1715. time.sleep(0.5)
  1716. except ValueError:
  1717. break
  1718. for apid in self.gerber_obj.apertures:
  1719. self.grb_plot_promises.append(apid)
  1720. self.app.worker_task.emit({'fcn': job_thread, 'params': [self, apid]})
  1721. # do the delayed plot only if there is something to plot (the gerber is not empty)
  1722. if bool(self.gerber_obj.apertures):
  1723. self.start_delayed_plot(check_period=1000)
  1724. else:
  1725. self.set_ui()
  1726. # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  1727. self.build_ui(first_run=True)
  1728. def update_fcgerber(self, grb_obj):
  1729. """
  1730. Create a new Gerber object that contain the edited content of the source Gerber object
  1731. :param grb_obj: FlatCAMGerber
  1732. :return: None
  1733. """
  1734. new_grb_name = self.edited_obj_name
  1735. # if the 'delayed plot' malfunctioned stop the QTimer
  1736. try:
  1737. self.plot_thread.stop()
  1738. except:
  1739. pass
  1740. if "_edit" in self.edited_obj_name:
  1741. try:
  1742. id = int(self.edited_obj_name[-1]) + 1
  1743. new_grb_name= self.edited_obj_name[:-1] + str(id)
  1744. except ValueError:
  1745. new_grb_name += "_1"
  1746. else:
  1747. new_grb_name = self.edited_obj_name + "_edit"
  1748. self.app.worker_task.emit({'fcn': self.new_edited_gerber,
  1749. 'params': [new_grb_name]})
  1750. # reset the tool table
  1751. self.apertures_table.clear()
  1752. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  1753. self.last_aperture_selected = None
  1754. # restore GUI to the Selected TAB
  1755. # Remove anything else in the GUI
  1756. self.app.ui.selected_scroll_area.takeWidget()
  1757. # Switch notebook to Selected page
  1758. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1759. def update_options(self, obj):
  1760. try:
  1761. if not obj.options:
  1762. obj.options = {}
  1763. obj.options['xmin'] = 0
  1764. obj.options['ymin'] = 0
  1765. obj.options['xmax'] = 0
  1766. obj.options['ymax'] = 0
  1767. return True
  1768. else:
  1769. return False
  1770. except AttributeError:
  1771. obj.options = {}
  1772. return True
  1773. def new_edited_gerber(self, outname):
  1774. """
  1775. Creates a new Gerber object for the edited Gerber. Thread-safe.
  1776. :param outname: Name of the resulting object. None causes the name to be that of the file.
  1777. :type outname: str
  1778. :return: None
  1779. """
  1780. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  1781. self.gerber_obj.options['name'].upper())
  1782. out_name = outname
  1783. local_storage_dict = deepcopy(self.storage_dict)
  1784. # How the object should be initialized
  1785. def obj_init(grb_obj, app_obj):
  1786. poly_buffer = []
  1787. follow_buffer = []
  1788. for storage_apid, storage_val in local_storage_dict.items():
  1789. grb_obj.apertures[storage_apid] = {}
  1790. for k, v in storage_val.items():
  1791. if k == 'solid_geometry':
  1792. grb_obj.apertures[storage_apid][k] = []
  1793. for geo in v:
  1794. new_geo = deepcopy(geo.geo)
  1795. grb_obj.apertures[storage_apid][k].append(new_geo)
  1796. poly_buffer.append(new_geo)
  1797. elif k == 'follow_geometry':
  1798. grb_obj.apertures[storage_apid][k] = []
  1799. for geo in v:
  1800. new_geo = deepcopy(geo.geo)
  1801. grb_obj.apertures[storage_apid][k].append(new_geo)
  1802. follow_buffer.append(new_geo)
  1803. else:
  1804. grb_obj.apertures[storage_apid][k] = deepcopy(v)
  1805. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  1806. new_poly = MultiPolygon(poly_buffer)
  1807. new_poly = new_poly.buffer(0.00000001)
  1808. new_poly = new_poly.buffer(-0.00000001)
  1809. grb_obj.solid_geometry = new_poly
  1810. grb_obj.follow_geometry = deepcopy(follow_buffer)
  1811. for k, v in self.gerber_obj_options.items():
  1812. if k == 'name':
  1813. grb_obj.options[k] = out_name
  1814. else:
  1815. grb_obj.options[k] = deepcopy(v)
  1816. grb_obj.source_file = []
  1817. grb_obj.multigeo = False
  1818. grb_obj.follow = False
  1819. try:
  1820. grb_obj.create_geometry()
  1821. except KeyError:
  1822. self.app.inform.emit(
  1823. _( "[ERROR_NOTCL] There are no Aperture definitions in the file. Aborting Gerber creation.")
  1824. )
  1825. except:
  1826. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  1827. msg += traceback.format_exc()
  1828. app_obj.inform.emit(msg)
  1829. raise
  1830. # raise
  1831. with self.app.proc_container.new(_("Creating Gerber.")):
  1832. try:
  1833. self.app.new_object("gerber", outname, obj_init)
  1834. except Exception as e:
  1835. log.error("Error on object creation: %s" % str(e))
  1836. self.app.progress.emit(100)
  1837. return
  1838. self.app.inform.emit(_("[success] Gerber editing finished."))
  1839. # self.progress.emit(100)
  1840. def on_tool_select(self, tool):
  1841. """
  1842. Behavior of the toolbar. Tool initialization.
  1843. :rtype : None
  1844. """
  1845. current_tool = tool
  1846. self.app.log.debug("on_tool_select('%s')" % tool)
  1847. if self.last_aperture_selected is None and current_tool is not 'select':
  1848. # self.draw_app.select_tool('select')
  1849. self.complete = True
  1850. current_tool = 'select'
  1851. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No aperture is selected"))
  1852. # This is to make the group behave as radio group
  1853. if current_tool in self.tools_gerber:
  1854. if self.tools_gerber[current_tool]["button"].isChecked():
  1855. self.app.log.debug("%s is checked." % current_tool)
  1856. for t in self.tools_gerber:
  1857. if t != current_tool:
  1858. self.tools_gerber[t]["button"].setChecked(False)
  1859. # this is where the Editor toolbar classes (button's) are instantiated
  1860. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  1861. # self.app.inform.emit(self.active_tool.start_msg)
  1862. else:
  1863. self.app.log.debug("%s is NOT checked." % current_tool)
  1864. for t in self.tools_gerber:
  1865. self.tools_gerber[t]["button"].setChecked(False)
  1866. self.select_tool('select')
  1867. self.active_tool = FCApertureSelect(self)
  1868. def on_row_selected(self, row, col):
  1869. if col == 0:
  1870. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1871. if self.app.defaults["global_mselect_key"] == 'Control':
  1872. modifier_to_use = Qt.ControlModifier
  1873. else:
  1874. modifier_to_use = Qt.ShiftModifier
  1875. if key_modifier == modifier_to_use:
  1876. pass
  1877. else:
  1878. self.selected = []
  1879. try:
  1880. # selected_apid = str(self.tool2tooldia[row + 1])
  1881. selected_apid = self.apertures_table.item(row, 1).text()
  1882. self.last_aperture_selected = copy(selected_apid)
  1883. for obj in self.storage_dict[selected_apid]['solid_geometry']:
  1884. self.selected.append(obj)
  1885. except Exception as e:
  1886. self.app.log.debug(str(e))
  1887. self.plot_all()
  1888. def toolbar_tool_toggle(self, key):
  1889. self.options[key] = self.sender().isChecked()
  1890. return self.options[key]
  1891. def on_grb_shape_complete(self, storage=None, specific_shape=None):
  1892. self.app.log.debug("on_shape_complete()")
  1893. if specific_shape:
  1894. geo = specific_shape
  1895. else:
  1896. geo = self.active_tool.geometry
  1897. if geo is None:
  1898. return
  1899. if storage is not None:
  1900. # Add shape
  1901. self.add_gerber_shape(geo, storage)
  1902. else:
  1903. stora = self.storage_dict[self.last_aperture_selected]['solid_geometry']
  1904. self.add_gerber_shape(geo, storage=stora)
  1905. # Remove any utility shapes
  1906. self.delete_utility_geometry()
  1907. self.tool_shape.clear(update=True)
  1908. # Replot and reset tool.
  1909. self.plot_all()
  1910. def add_gerber_shape(self, shape, storage):
  1911. """
  1912. Adds a shape to the shape storage.
  1913. :param shape: Shape to be added.
  1914. :type shape: DrawToolShape
  1915. :return: None
  1916. """
  1917. # List of DrawToolShape?
  1918. if isinstance(shape, list):
  1919. for subshape in shape:
  1920. self.add_gerber_shape(subshape, storage)
  1921. return
  1922. assert isinstance(shape, DrawToolShape), \
  1923. "Expected a DrawToolShape, got %s" % str(type(shape))
  1924. assert shape.geo is not None, \
  1925. "Shape object has empty geometry (None)"
  1926. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  1927. not isinstance(shape.geo, list), \
  1928. "Shape objects has empty geometry ([])"
  1929. if isinstance(shape, DrawToolUtilityShape):
  1930. self.utility.append(shape)
  1931. else:
  1932. storage.append(shape) # TODO: Check performance
  1933. def on_canvas_click(self, event):
  1934. """
  1935. event.x and .y have canvas coordinates
  1936. event.xdaya and .ydata have plot coordinates
  1937. :param event: Event object dispatched by Matplotlib
  1938. :return: None
  1939. """
  1940. if event.button is 1:
  1941. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1942. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  1943. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  1944. ### Snap coordinates
  1945. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  1946. self.pos = (x, y)
  1947. # Selection with left mouse button
  1948. if self.active_tool is not None and event.button is 1:
  1949. # Dispatch event to active_tool
  1950. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  1951. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  1952. # If it is a shape generating tool
  1953. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  1954. if self.current_storage is not None:
  1955. self.on_grb_shape_complete(self.current_storage)
  1956. self.build_ui()
  1957. # MS: always return to the Select Tool if modifier key is not pressed
  1958. # else return to the current tool
  1959. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1960. if self.app.defaults["global_mselect_key"] == 'Control':
  1961. modifier_to_use = Qt.ControlModifier
  1962. else:
  1963. modifier_to_use = Qt.ShiftModifier
  1964. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1965. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1966. if key_modifier == modifier_to_use:
  1967. self.select_tool(self.active_tool.name)
  1968. else:
  1969. self.select_tool("select")
  1970. return
  1971. if isinstance(self.active_tool, FCApertureSelect):
  1972. # self.app.log.debug("Replotting after click.")
  1973. self.plot_all()
  1974. else:
  1975. self.app.log.debug("No active tool to respond to click!")
  1976. def on_grb_click_release(self, event):
  1977. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  1978. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  1979. if self.app.grid_status():
  1980. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  1981. else:
  1982. pos = (pos_canvas[0], pos_canvas[1])
  1983. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  1984. # canvas menu
  1985. try:
  1986. if event.button == 2: # right click
  1987. if self.app.panning_action is True:
  1988. self.app.panning_action = False
  1989. else:
  1990. if self.in_action is False:
  1991. self.app.cursor = QtGui.QCursor()
  1992. self.app.ui.popMenu.popup(self.app.cursor.pos())
  1993. else:
  1994. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  1995. # right mouse click will finish the action
  1996. if isinstance(self.active_tool, FCShapeTool):
  1997. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  1998. self.active_tool.make()
  1999. if self.active_tool.complete:
  2000. self.on_grb_shape_complete()
  2001. self.app.inform.emit(_("[success] Done."))
  2002. # MS: always return to the Select Tool if modifier key is not pressed
  2003. # else return to the current tool
  2004. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2005. if (self.app.defaults["global_mselect_key"] == 'Control' and
  2006. key_modifier == Qt.ControlModifier) or \
  2007. (self.app.defaults["global_mselect_key"] == 'Shift' and
  2008. key_modifier == Qt.ShiftModifier):
  2009. self.select_tool(self.active_tool.name)
  2010. else:
  2011. self.select_tool("select")
  2012. except Exception as e:
  2013. log.warning("Error: %s" % str(e))
  2014. raise
  2015. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2016. # selection and then select a type of selection ("enclosing" or "touching")
  2017. try:
  2018. if event.button == 1: # left click
  2019. if self.app.selection_type is not None:
  2020. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2021. self.app.selection_type = None
  2022. elif isinstance(self.active_tool, FCApertureSelect):
  2023. # Dispatch event to active_tool
  2024. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2025. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2026. # self.app.inform.emit(msg)
  2027. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2028. # if there are selected objects then plot them
  2029. if self.selected:
  2030. self.plot_all()
  2031. except Exception as e:
  2032. log.warning("Error: %s" % str(e))
  2033. raise
  2034. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2035. """
  2036. :param start_pos: mouse position when the selection LMB click was done
  2037. :param end_pos: mouse position when the left mouse button is released
  2038. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2039. :type Bool
  2040. :return:
  2041. """
  2042. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2043. sel_aperture = set()
  2044. self.apertures_table.clearSelection()
  2045. self.app.delete_selection_shape()
  2046. for storage in self.storage_dict:
  2047. for obj in self.storage_dict[storage]['solid_geometry']:
  2048. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2049. (sel_type is False and poly_selection.intersects(obj.geo)):
  2050. if self.key == self.app.defaults["global_mselect_key"]:
  2051. if obj in self.selected:
  2052. self.selected.remove(obj)
  2053. else:
  2054. # add the object to the selected shapes
  2055. self.selected.append(obj)
  2056. sel_aperture.add(storage)
  2057. else:
  2058. self.selected.append(obj)
  2059. sel_aperture.add(storage)
  2060. try:
  2061. self.apertures_table.cellPressed.disconnect()
  2062. except:
  2063. pass
  2064. # select the aperture code of the selected geometry, in the tool table
  2065. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2066. for aper in sel_aperture:
  2067. for row in range(self.apertures_table.rowCount()):
  2068. if str(aper) == self.apertures_table.item(row, 1).text():
  2069. self.apertures_table.selectRow(row)
  2070. self.last_aperture_selected = aper
  2071. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2072. self.apertures_table.cellPressed.connect(self.on_row_selected)
  2073. self.plot_all()
  2074. def on_canvas_move(self, event):
  2075. """
  2076. Called on 'mouse_move' event
  2077. event.pos have canvas screen coordinates
  2078. :param event: Event object dispatched by VisPy SceneCavas
  2079. :return: None
  2080. """
  2081. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2082. event.xdata, event.ydata = pos[0], pos[1]
  2083. self.x = event.xdata
  2084. self.y = event.ydata
  2085. # Prevent updates on pan
  2086. # if len(event.buttons) > 0:
  2087. # return
  2088. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2089. if event.button == 2:
  2090. self.app.panning_action = True
  2091. return
  2092. else:
  2093. self.app.panning_action = False
  2094. try:
  2095. x = float(event.xdata)
  2096. y = float(event.ydata)
  2097. except TypeError:
  2098. return
  2099. if self.active_tool is None:
  2100. return
  2101. ### Snap coordinates
  2102. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  2103. self.snap_x = x
  2104. self.snap_y = y
  2105. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2106. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2107. "<b>Y</b>: %.4f" % (x, y))
  2108. if self.pos is None:
  2109. self.pos = (0, 0)
  2110. dx = x - self.pos[0]
  2111. dy = y - self.pos[1]
  2112. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2113. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2114. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2115. ### Utility geometry (animated)
  2116. geo = self.active_tool.utility_geometry(data=(x, y))
  2117. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2118. # Remove any previous utility shape
  2119. self.tool_shape.clear(update=True)
  2120. self.draw_utility_geometry(geo=geo)
  2121. ### Selection area on canvas section ###
  2122. dx = pos[0] - self.pos[0]
  2123. if event.is_dragging == 1 and event.button == 1:
  2124. self.app.delete_selection_shape()
  2125. if dx < 0:
  2126. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2127. color=self.app.defaults["global_alt_sel_line"],
  2128. face_color=self.app.defaults['global_alt_sel_fill'])
  2129. self.app.selection_type = False
  2130. else:
  2131. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2132. self.app.selection_type = True
  2133. else:
  2134. self.app.selection_type = None
  2135. # Update cursor
  2136. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2137. def on_canvas_key_release(self, event):
  2138. self.key = None
  2139. def draw_utility_geometry(self, geo):
  2140. if type(geo.geo) == list:
  2141. for el in geo.geo:
  2142. # Add the new utility shape
  2143. self.tool_shape.add(
  2144. shape=el, color=(self.app.defaults["global_draw_color"] + '80'),
  2145. update=False, layer=0, tolerance=None)
  2146. else:
  2147. # Add the new utility shape
  2148. self.tool_shape.add(
  2149. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2150. update=False, layer=0, tolerance=None)
  2151. self.tool_shape.redraw()
  2152. def plot_all(self):
  2153. """
  2154. Plots all shapes in the editor.
  2155. :return: None
  2156. :rtype: None
  2157. """
  2158. with self.app.proc_container.new("Plotting"):
  2159. # self.app.log.debug("plot_all()")
  2160. self.shapes.clear(update=True)
  2161. for storage in self.storage_dict:
  2162. for shape in self.storage_dict[storage]['solid_geometry']:
  2163. if shape.geo is None:
  2164. continue
  2165. if shape in self.selected:
  2166. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'],
  2167. linewidth=2)
  2168. continue
  2169. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2170. for shape in self.utility:
  2171. self.plot_shape(geometry=shape.geo, linewidth=1)
  2172. continue
  2173. self.shapes.redraw()
  2174. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2175. """
  2176. Plots a geometric object or list of objects without rendering. Plotted objects
  2177. are returned as a list. This allows for efficient/animated rendering.
  2178. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2179. :param color: Shape color
  2180. :param linewidth: Width of lines in # of pixels.
  2181. :return: List of plotted elements.
  2182. """
  2183. # plot_elements = []
  2184. if geometry is None:
  2185. geometry = self.active_tool.geometry
  2186. try:
  2187. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0)
  2188. except AttributeError:
  2189. if type(geometry) == Point:
  2190. return
  2191. self.shapes.add(shape=geometry, color=color, face_color=color+'AF', layer=0)
  2192. def start_delayed_plot(self, check_period):
  2193. # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  2194. # self.plot_thread.start()
  2195. log.debug("FlatCAMGrbEditor --> Delayed Plot started.")
  2196. self.plot_thread = QtCore.QTimer()
  2197. self.plot_thread.setInterval(check_period)
  2198. self.plot_thread.timeout.connect(self.check_plot_finished)
  2199. self.plot_thread.start()
  2200. def check_plot_finished(self):
  2201. # print(self.grb_plot_promises)
  2202. try:
  2203. if not self.grb_plot_promises:
  2204. self.plot_thread.stop()
  2205. self.set_ui()
  2206. # now that we have data, create the GUI interface and add it to the Tool Tab
  2207. self.build_ui(first_run=True)
  2208. self.plot_all()
  2209. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  2210. # - perhaps is a bug in VisPy implementation
  2211. self.app.app_cursor.enabled = False
  2212. self.app.app_cursor.enabled = True
  2213. log.debug("FlatCAMGrbEditor --> delayed_plot finished")
  2214. except Exception:
  2215. traceback.print_exc()
  2216. def on_shape_complete(self):
  2217. self.app.log.debug("on_shape_complete()")
  2218. # Add shape
  2219. self.add_gerber_shape(self.active_tool.geometry)
  2220. # Remove any utility shapes
  2221. self.delete_utility_geometry()
  2222. self.tool_shape.clear(update=True)
  2223. # Replot and reset tool.
  2224. self.plot_all()
  2225. # self.active_tool = type(self.active_tool)(self)
  2226. def get_selected(self):
  2227. """
  2228. Returns list of shapes that are selected in the editor.
  2229. :return: List of shapes.
  2230. """
  2231. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2232. return self.selected
  2233. def delete_selected(self):
  2234. temp_ref = [s for s in self.selected]
  2235. for shape_sel in temp_ref:
  2236. self.delete_shape(shape_sel)
  2237. self.selected = []
  2238. self.build_ui()
  2239. self.app.inform.emit(_("[success] Done. Apertures deleted."))
  2240. def delete_shape(self, shape):
  2241. self.is_modified = True
  2242. if shape in self.utility:
  2243. self.utility.remove(shape)
  2244. return
  2245. for storage in self.storage_dict:
  2246. # try:
  2247. # self.storage_dict[storage].remove(shape)
  2248. # except:
  2249. # pass
  2250. if shape in self.storage_dict[storage]['solid_geometry']:
  2251. self.storage_dict[storage]['solid_geometry'].remove(shape)
  2252. if shape in self.selected:
  2253. self.selected.remove(shape) # TODO: Check performance
  2254. def delete_utility_geometry(self):
  2255. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2256. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2257. for_deletion = [shape for shape in self.utility]
  2258. for shape in for_deletion:
  2259. self.delete_shape(shape)
  2260. self.tool_shape.clear(update=True)
  2261. self.tool_shape.redraw()
  2262. def on_delete_btn(self):
  2263. self.delete_selected()
  2264. self.plot_all()
  2265. def select_tool(self, toolname):
  2266. """
  2267. Selects a drawing tool. Impacts the object and GUI.
  2268. :param toolname: Name of the tool.
  2269. :return: None
  2270. """
  2271. self.tools_gerber[toolname]["button"].setChecked(True)
  2272. self.on_tool_select(toolname)
  2273. def set_selected(self, shape):
  2274. # Remove and add to the end.
  2275. if shape in self.selected:
  2276. self.selected.remove(shape)
  2277. self.selected.append(shape)
  2278. def set_unselected(self, shape):
  2279. if shape in self.selected:
  2280. self.selected.remove(shape)
  2281. def on_array_type_combo(self):
  2282. if self.array_type_combo.currentIndex() == 0:
  2283. self.array_circular_frame.hide()
  2284. self.array_linear_frame.show()
  2285. else:
  2286. self.delete_utility_geometry()
  2287. self.array_circular_frame.show()
  2288. self.array_linear_frame.hide()
  2289. self.app.inform.emit(_("Click on the circular array Center position"))
  2290. def on_linear_angle_radio(self):
  2291. val = self.pad_axis_radio.get_value()
  2292. if val == 'A':
  2293. self.linear_angle_spinner.show()
  2294. self.linear_angle_label.show()
  2295. else:
  2296. self.linear_angle_spinner.hide()
  2297. self.linear_angle_label.hide()
  2298. def on_copy_button(self):
  2299. self.select_tool('copy')
  2300. return
  2301. def on_move_button(self):
  2302. self.select_tool('move')
  2303. return
  2304. def on_pad_add(self):
  2305. self.select_tool('pad')
  2306. def on_pad_add_array(self):
  2307. self.select_tool('array')
  2308. def on_track_add(self):
  2309. self.select_tool('track')
  2310. def on_region_add(self):
  2311. self.select_tool('region')
  2312. def on_poligonize(self):
  2313. self.select_tool('poligonize')
  2314. def on_buffer(self):
  2315. buff_value = 0.01
  2316. log.debug("FlatCAMGrbEditor.on_buffer()")
  2317. try:
  2318. buff_value = float(self.buffer_distance_entry.get_value())
  2319. except ValueError:
  2320. # try to convert comma to decimal point. if it's still not working error message and return
  2321. try:
  2322. buff_value = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  2323. self.buffer_distance_entry.set_value(buff_value)
  2324. except ValueError:
  2325. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2326. "Add it and retry."))
  2327. return
  2328. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2329. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2330. join_style = self.buffer_corner_cb.currentIndex() + 1
  2331. def buffer_recursion(geom, selection):
  2332. if type(geom) == list or type(geom) is MultiPolygon:
  2333. geoms = list()
  2334. for local_geom in geom:
  2335. geoms.append(buffer_recursion(local_geom, selection=selection))
  2336. return geoms
  2337. else:
  2338. if geom in selection:
  2339. return DrawToolShape(geom.geo.buffer(buff_value, join_style=join_style))
  2340. else:
  2341. return geom
  2342. if not self.apertures_table.selectedItems():
  2343. self.app.inform.emit(_(
  2344. "[WARNING_NOTCL] No aperture to buffer. Select at least one aperture and try again."
  2345. ))
  2346. return
  2347. for x in self.apertures_table.selectedItems():
  2348. try:
  2349. apid = self.apertures_table.item(x.row(), 1).text()
  2350. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  2351. self.storage_dict[apid]['solid_geometry'] = []
  2352. self.storage_dict[apid]['solid_geometry'] = temp_storage
  2353. except Exception as e:
  2354. log.debug("FlatCAMGrbEditor.buffer() --> %s" % str(e))
  2355. self.plot_all()
  2356. self.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2357. def on_scale(self):
  2358. scale_factor = 1.0
  2359. log.debug("FlatCAMGrbEditor.on_scale()")
  2360. try:
  2361. scale_factor = float(self.scale_factor_entry.get_value())
  2362. except ValueError:
  2363. # try to convert comma to decimal point. if it's still not working error message and return
  2364. try:
  2365. scale_factor = float(self.scale_factor_entry.get_value().replace(',', '.'))
  2366. self.scale_factor_entry.set_value(scale_factor)
  2367. except ValueError:
  2368. self.app.inform.emit(_("[WARNING_NOTCL] Scale factor value is missing or wrong format. "
  2369. "Add it and retry."))
  2370. return
  2371. def scale_recursion(geom, selection):
  2372. if type(geom) == list or type(geom) is MultiPolygon:
  2373. geoms = list()
  2374. for local_geom in geom:
  2375. geoms.append(scale_recursion(local_geom, selection=selection))
  2376. return geoms
  2377. else:
  2378. if geom in selection:
  2379. return DrawToolShape(affinity.scale(geom.geo, scale_factor, scale_factor, origin='center'))
  2380. else:
  2381. return geom
  2382. if not self.apertures_table.selectedItems():
  2383. self.app.inform.emit(_(
  2384. "[WARNING_NOTCL] No aperture to scale. Select at least one aperture and try again."
  2385. ))
  2386. return
  2387. for x in self.apertures_table.selectedItems():
  2388. try:
  2389. apid = self.apertures_table.item(x.row(), 1).text()
  2390. temp_storage = deepcopy(scale_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  2391. self.storage_dict[apid]['solid_geometry'] = []
  2392. self.storage_dict[apid]['solid_geometry'] = temp_storage
  2393. except Exception as e:
  2394. log.debug("FlatCAMGrbEditor.on_scale() --> %s" % str(e))
  2395. self.plot_all()
  2396. self.app.inform.emit(_("[success] Done. Scale Tool completed."))
  2397. def on_transform(self):
  2398. if type(self.active_tool) == FCTransform:
  2399. self.select_tool('select')
  2400. else:
  2401. self.select_tool('transform')
  2402. def hide_tool(self, tool_name):
  2403. # self.app.ui.notebook.setTabText(2, _("Tools"))
  2404. if tool_name == 'all':
  2405. self.apertures_frame.hide()
  2406. if tool_name == 'select':
  2407. self.apertures_frame.show()
  2408. if tool_name == 'buffer' or tool_name == 'all':
  2409. self.buffer_tool_frame.hide()
  2410. if tool_name == 'scale' or tool_name == 'all':
  2411. self.scale_tool_frame.hide()
  2412. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2413. class TransformEditorTool(FlatCAMTool):
  2414. """
  2415. Inputs to specify how to paint the selected polygons.
  2416. """
  2417. toolName = _("Transform Tool")
  2418. rotateName = _("Rotate")
  2419. skewName = _("Skew/Shear")
  2420. scaleName = _("Scale")
  2421. flipName = _("Mirror (Flip)")
  2422. offsetName = _("Offset")
  2423. def __init__(self, app, draw_app):
  2424. FlatCAMTool.__init__(self, app)
  2425. self.app = app
  2426. self.draw_app = draw_app
  2427. self.transform_lay = QtWidgets.QVBoxLayout()
  2428. self.layout.addLayout(self.transform_lay)
  2429. ## Title
  2430. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  2431. title_label.setStyleSheet("""
  2432. QLabel
  2433. {
  2434. font-size: 16px;
  2435. font-weight: bold;
  2436. }
  2437. """)
  2438. self.transform_lay.addWidget(title_label)
  2439. self.empty_label = QtWidgets.QLabel("")
  2440. self.empty_label.setFixedWidth(50)
  2441. self.empty_label1 = QtWidgets.QLabel("")
  2442. self.empty_label1.setFixedWidth(70)
  2443. self.empty_label2 = QtWidgets.QLabel("")
  2444. self.empty_label2.setFixedWidth(70)
  2445. self.empty_label3 = QtWidgets.QLabel("")
  2446. self.empty_label3.setFixedWidth(70)
  2447. self.empty_label4 = QtWidgets.QLabel("")
  2448. self.empty_label4.setFixedWidth(70)
  2449. self.transform_lay.addWidget(self.empty_label)
  2450. ## Rotate Title
  2451. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  2452. self.transform_lay.addWidget(rotate_title_label)
  2453. ## Layout
  2454. form_layout = QtWidgets.QFormLayout()
  2455. self.transform_lay.addLayout(form_layout)
  2456. form_child = QtWidgets.QHBoxLayout()
  2457. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  2458. self.rotate_label.setToolTip(
  2459. _("Angle for Rotation action, in degrees.\n"
  2460. "Float number between -360 and 359.\n"
  2461. "Positive numbers for CW motion.\n"
  2462. "Negative numbers for CCW motion.")
  2463. )
  2464. self.rotate_label.setFixedWidth(50)
  2465. self.rotate_entry = FCEntry()
  2466. # self.rotate_entry.setFixedWidth(60)
  2467. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2468. self.rotate_button = FCButton()
  2469. self.rotate_button.set_value(_("Rotate"))
  2470. self.rotate_button.setToolTip(
  2471. _("Rotate the selected shape(s).\n"
  2472. "The point of reference is the middle of\n"
  2473. "the bounding box for all selected shapes.")
  2474. )
  2475. self.rotate_button.setFixedWidth(60)
  2476. form_child.addWidget(self.rotate_entry)
  2477. form_child.addWidget(self.rotate_button)
  2478. form_layout.addRow(self.rotate_label, form_child)
  2479. self.transform_lay.addWidget(self.empty_label1)
  2480. ## Skew Title
  2481. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  2482. self.transform_lay.addWidget(skew_title_label)
  2483. ## Form Layout
  2484. form1_layout = QtWidgets.QFormLayout()
  2485. self.transform_lay.addLayout(form1_layout)
  2486. form1_child_1 = QtWidgets.QHBoxLayout()
  2487. form1_child_2 = QtWidgets.QHBoxLayout()
  2488. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  2489. self.skewx_label.setToolTip(
  2490. _("Angle for Skew action, in degrees.\n"
  2491. "Float number between -360 and 359.")
  2492. )
  2493. self.skewx_label.setFixedWidth(50)
  2494. self.skewx_entry = FCEntry()
  2495. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2496. # self.skewx_entry.setFixedWidth(60)
  2497. self.skewx_button = FCButton()
  2498. self.skewx_button.set_value(_("Skew X"))
  2499. self.skewx_button.setToolTip(
  2500. _("Skew/shear the selected shape(s).\n"
  2501. "The point of reference is the middle of\n"
  2502. "the bounding box for all selected shapes."))
  2503. self.skewx_button.setFixedWidth(60)
  2504. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  2505. self.skewy_label.setToolTip(
  2506. _("Angle for Skew action, in degrees.\n"
  2507. "Float number between -360 and 359.")
  2508. )
  2509. self.skewy_label.setFixedWidth(50)
  2510. self.skewy_entry = FCEntry()
  2511. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2512. # self.skewy_entry.setFixedWidth(60)
  2513. self.skewy_button = FCButton()
  2514. self.skewy_button.set_value(_("Skew Y"))
  2515. self.skewy_button.setToolTip(
  2516. _("Skew/shear the selected shape(s).\n"
  2517. "The point of reference is the middle of\n"
  2518. "the bounding box for all selected shapes."))
  2519. self.skewy_button.setFixedWidth(60)
  2520. form1_child_1.addWidget(self.skewx_entry)
  2521. form1_child_1.addWidget(self.skewx_button)
  2522. form1_child_2.addWidget(self.skewy_entry)
  2523. form1_child_2.addWidget(self.skewy_button)
  2524. form1_layout.addRow(self.skewx_label, form1_child_1)
  2525. form1_layout.addRow(self.skewy_label, form1_child_2)
  2526. self.transform_lay.addWidget(self.empty_label2)
  2527. ## Scale Title
  2528. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  2529. self.transform_lay.addWidget(scale_title_label)
  2530. ## Form Layout
  2531. form2_layout = QtWidgets.QFormLayout()
  2532. self.transform_lay.addLayout(form2_layout)
  2533. form2_child_1 = QtWidgets.QHBoxLayout()
  2534. form2_child_2 = QtWidgets.QHBoxLayout()
  2535. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  2536. self.scalex_label.setToolTip(
  2537. _("Factor for Scale action over X axis.")
  2538. )
  2539. self.scalex_label.setFixedWidth(50)
  2540. self.scalex_entry = FCEntry()
  2541. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2542. # self.scalex_entry.setFixedWidth(60)
  2543. self.scalex_button = FCButton()
  2544. self.scalex_button.set_value(_("Scale X"))
  2545. self.scalex_button.setToolTip(
  2546. _("Scale the selected shape(s).\n"
  2547. "The point of reference depends on \n"
  2548. "the Scale reference checkbox state."))
  2549. self.scalex_button.setFixedWidth(60)
  2550. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  2551. self.scaley_label.setToolTip(
  2552. _("Factor for Scale action over Y axis.")
  2553. )
  2554. self.scaley_label.setFixedWidth(50)
  2555. self.scaley_entry = FCEntry()
  2556. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2557. # self.scaley_entry.setFixedWidth(60)
  2558. self.scaley_button = FCButton()
  2559. self.scaley_button.set_value(_("Scale Y"))
  2560. self.scaley_button.setToolTip(
  2561. _("Scale the selected shape(s).\n"
  2562. "The point of reference depends on \n"
  2563. "the Scale reference checkbox state."))
  2564. self.scaley_button.setFixedWidth(60)
  2565. self.scale_link_cb = FCCheckBox()
  2566. self.scale_link_cb.set_value(True)
  2567. self.scale_link_cb.setText(_("Link"))
  2568. self.scale_link_cb.setToolTip(
  2569. _("Scale the selected shape(s)\n"
  2570. "using the Scale Factor X for both axis."))
  2571. self.scale_link_cb.setFixedWidth(50)
  2572. self.scale_zero_ref_cb = FCCheckBox()
  2573. self.scale_zero_ref_cb.set_value(True)
  2574. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  2575. self.scale_zero_ref_cb.setToolTip(
  2576. _("Scale the selected shape(s)\n"
  2577. "using the origin reference when checked,\n"
  2578. "and the center of the biggest bounding box\n"
  2579. "of the selected shapes when unchecked."))
  2580. form2_child_1.addWidget(self.scalex_entry)
  2581. form2_child_1.addWidget(self.scalex_button)
  2582. form2_child_2.addWidget(self.scaley_entry)
  2583. form2_child_2.addWidget(self.scaley_button)
  2584. form2_layout.addRow(self.scalex_label, form2_child_1)
  2585. form2_layout.addRow(self.scaley_label, form2_child_2)
  2586. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  2587. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button],
  2588. logic=False)
  2589. self.transform_lay.addWidget(self.empty_label3)
  2590. ## Offset Title
  2591. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  2592. self.transform_lay.addWidget(offset_title_label)
  2593. ## Form Layout
  2594. form3_layout = QtWidgets.QFormLayout()
  2595. self.transform_lay.addLayout(form3_layout)
  2596. form3_child_1 = QtWidgets.QHBoxLayout()
  2597. form3_child_2 = QtWidgets.QHBoxLayout()
  2598. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  2599. self.offx_label.setToolTip(
  2600. _("Value for Offset action on X axis.")
  2601. )
  2602. self.offx_label.setFixedWidth(50)
  2603. self.offx_entry = FCEntry()
  2604. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2605. # self.offx_entry.setFixedWidth(60)
  2606. self.offx_button = FCButton()
  2607. self.offx_button.set_value(_("Offset X"))
  2608. self.offx_button.setToolTip(
  2609. _("Offset the selected shape(s).\n"
  2610. "The point of reference is the middle of\n"
  2611. "the bounding box for all selected shapes.\n")
  2612. )
  2613. self.offx_button.setFixedWidth(60)
  2614. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  2615. self.offy_label.setToolTip(
  2616. _("Value for Offset action on Y axis.")
  2617. )
  2618. self.offy_label.setFixedWidth(50)
  2619. self.offy_entry = FCEntry()
  2620. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2621. # self.offy_entry.setFixedWidth(60)
  2622. self.offy_button = FCButton()
  2623. self.offy_button.set_value(_("Offset Y"))
  2624. self.offy_button.setToolTip(
  2625. _("Offset the selected shape(s).\n"
  2626. "The point of reference is the middle of\n"
  2627. "the bounding box for all selected shapes.\n")
  2628. )
  2629. self.offy_button.setFixedWidth(60)
  2630. form3_child_1.addWidget(self.offx_entry)
  2631. form3_child_1.addWidget(self.offx_button)
  2632. form3_child_2.addWidget(self.offy_entry)
  2633. form3_child_2.addWidget(self.offy_button)
  2634. form3_layout.addRow(self.offx_label, form3_child_1)
  2635. form3_layout.addRow(self.offy_label, form3_child_2)
  2636. self.transform_lay.addWidget(self.empty_label4)
  2637. ## Flip Title
  2638. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  2639. self.transform_lay.addWidget(flip_title_label)
  2640. ## Form Layout
  2641. form4_layout = QtWidgets.QFormLayout()
  2642. form4_child_hlay = QtWidgets.QHBoxLayout()
  2643. self.transform_lay.addLayout(form4_child_hlay)
  2644. self.transform_lay.addLayout(form4_layout)
  2645. form4_child_1 = QtWidgets.QHBoxLayout()
  2646. self.flipx_button = FCButton()
  2647. self.flipx_button.set_value(_("Flip on X"))
  2648. self.flipx_button.setToolTip(
  2649. _("Flip the selected shape(s) over the X axis.\n"
  2650. "Does not create a new shape.")
  2651. )
  2652. self.flipx_button.setFixedWidth(60)
  2653. self.flipy_button = FCButton()
  2654. self.flipy_button.set_value(_("Flip on Y"))
  2655. self.flipy_button.setToolTip(
  2656. _("Flip the selected shape(s) over the X axis.\n"
  2657. "Does not create a new shape.")
  2658. )
  2659. self.flipy_button.setFixedWidth(60)
  2660. self.flip_ref_cb = FCCheckBox()
  2661. self.flip_ref_cb.set_value(True)
  2662. self.flip_ref_cb.setText(_("Ref Pt"))
  2663. self.flip_ref_cb.setToolTip(
  2664. _("Flip the selected shape(s)\n"
  2665. "around the point in Point Entry Field.\n"
  2666. "\n"
  2667. "The point coordinates can be captured by\n"
  2668. "left click on canvas together with pressing\n"
  2669. "SHIFT key. \n"
  2670. "Then click Add button to insert coordinates.\n"
  2671. "Or enter the coords in format (x, y) in the\n"
  2672. "Point Entry field and click Flip on X(Y)")
  2673. )
  2674. self.flip_ref_cb.setFixedWidth(50)
  2675. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  2676. self.flip_ref_label.setToolTip(
  2677. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  2678. "The 'x' in (x, y) will be used when using Flip on X and\n"
  2679. "the 'y' in (x, y) will be used when using Flip on Y.")
  2680. )
  2681. self.flip_ref_label.setFixedWidth(50)
  2682. self.flip_ref_entry = EvalEntry2("(0, 0)")
  2683. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2684. # self.flip_ref_entry.setFixedWidth(60)
  2685. self.flip_ref_button = FCButton()
  2686. self.flip_ref_button.set_value(_("Add"))
  2687. self.flip_ref_button.setToolTip(
  2688. _("The point coordinates can be captured by\n"
  2689. "left click on canvas together with pressing\n"
  2690. "SHIFT key. Then click Add button to insert.")
  2691. )
  2692. self.flip_ref_button.setFixedWidth(60)
  2693. form4_child_hlay.addStretch()
  2694. form4_child_hlay.addWidget(self.flipx_button)
  2695. form4_child_hlay.addWidget(self.flipy_button)
  2696. form4_child_1.addWidget(self.flip_ref_entry)
  2697. form4_child_1.addWidget(self.flip_ref_button)
  2698. form4_layout.addRow(self.flip_ref_cb)
  2699. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  2700. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  2701. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  2702. self.transform_lay.addStretch()
  2703. ## Signals
  2704. self.rotate_button.clicked.connect(self.on_rotate)
  2705. self.skewx_button.clicked.connect(self.on_skewx)
  2706. self.skewy_button.clicked.connect(self.on_skewy)
  2707. self.scalex_button.clicked.connect(self.on_scalex)
  2708. self.scaley_button.clicked.connect(self.on_scaley)
  2709. self.offx_button.clicked.connect(self.on_offx)
  2710. self.offy_button.clicked.connect(self.on_offy)
  2711. self.flipx_button.clicked.connect(self.on_flipx)
  2712. self.flipy_button.clicked.connect(self.on_flipy)
  2713. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  2714. self.rotate_entry.returnPressed.connect(self.on_rotate)
  2715. self.skewx_entry.returnPressed.connect(self.on_skewx)
  2716. self.skewy_entry.returnPressed.connect(self.on_skewy)
  2717. self.scalex_entry.returnPressed.connect(self.on_scalex)
  2718. self.scaley_entry.returnPressed.connect(self.on_scaley)
  2719. self.offx_entry.returnPressed.connect(self.on_offx)
  2720. self.offy_entry.returnPressed.connect(self.on_offy)
  2721. self.set_tool_ui()
  2722. def run(self, toggle=True):
  2723. self.app.report_usage("Geo Editor Transform Tool()")
  2724. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  2725. if self.app.ui.splitter.sizes()[0] == 0:
  2726. self.app.ui.splitter.setSizes([1, 1])
  2727. if toggle:
  2728. try:
  2729. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  2730. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2731. else:
  2732. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  2733. except AttributeError:
  2734. pass
  2735. FlatCAMTool.run(self)
  2736. self.set_tool_ui()
  2737. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  2738. def install(self, icon=None, separator=None, **kwargs):
  2739. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  2740. def set_tool_ui(self):
  2741. ## Initialize form
  2742. if self.app.defaults["tools_transform_rotate"]:
  2743. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  2744. else:
  2745. self.rotate_entry.set_value(0.0)
  2746. if self.app.defaults["tools_transform_skew_x"]:
  2747. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  2748. else:
  2749. self.skewx_entry.set_value(0.0)
  2750. if self.app.defaults["tools_transform_skew_y"]:
  2751. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  2752. else:
  2753. self.skewy_entry.set_value(0.0)
  2754. if self.app.defaults["tools_transform_scale_x"]:
  2755. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  2756. else:
  2757. self.scalex_entry.set_value(1.0)
  2758. if self.app.defaults["tools_transform_scale_y"]:
  2759. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  2760. else:
  2761. self.scaley_entry.set_value(1.0)
  2762. if self.app.defaults["tools_transform_scale_link"]:
  2763. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  2764. else:
  2765. self.scale_link_cb.set_value(True)
  2766. if self.app.defaults["tools_transform_scale_reference"]:
  2767. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  2768. else:
  2769. self.scale_zero_ref_cb.set_value(True)
  2770. if self.app.defaults["tools_transform_offset_x"]:
  2771. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  2772. else:
  2773. self.offx_entry.set_value(0.0)
  2774. if self.app.defaults["tools_transform_offset_y"]:
  2775. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  2776. else:
  2777. self.offy_entry.set_value(0.0)
  2778. if self.app.defaults["tools_transform_mirror_reference"]:
  2779. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  2780. else:
  2781. self.flip_ref_cb.set_value(False)
  2782. if self.app.defaults["tools_transform_mirror_point"]:
  2783. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  2784. else:
  2785. self.flip_ref_entry.set_value((0, 0))
  2786. def template(self):
  2787. if not self.fcdraw.selected:
  2788. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  2789. return
  2790. self.draw_app.select_tool("select")
  2791. self.app.ui.notebook.setTabText(2, "Tools")
  2792. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  2793. self.app.ui.splitter.setSizes([0, 1])
  2794. def on_rotate(self, sig=None, val=None):
  2795. if val:
  2796. value = val
  2797. else:
  2798. try:
  2799. value = float(self.rotate_entry.get_value())
  2800. except ValueError:
  2801. # try to convert comma to decimal point. if it's still not working error message and return
  2802. try:
  2803. value = float(self.rotate_entry.get_value().replace(',', '.'))
  2804. except ValueError:
  2805. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  2806. "use a number."))
  2807. return
  2808. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  2809. 'params': [value]})
  2810. # self.on_rotate_action(value)
  2811. return
  2812. def on_flipx(self):
  2813. # self.on_flip("Y")
  2814. axis = 'Y'
  2815. self.app.worker_task.emit({'fcn': self.on_flip,
  2816. 'params': [axis]})
  2817. return
  2818. def on_flipy(self):
  2819. # self.on_flip("X")
  2820. axis = 'X'
  2821. self.app.worker_task.emit({'fcn': self.on_flip,
  2822. 'params': [axis]})
  2823. return
  2824. def on_flip_add_coords(self):
  2825. val = self.app.clipboard.text()
  2826. self.flip_ref_entry.set_value(val)
  2827. def on_skewx(self, sig=None, val=None):
  2828. if val:
  2829. value = val
  2830. else:
  2831. try:
  2832. value = float(self.skewx_entry.get_value())
  2833. except ValueError:
  2834. # try to convert comma to decimal point. if it's still not working error message and return
  2835. try:
  2836. value = float(self.skewx_entry.get_value().replace(',', '.'))
  2837. except ValueError:
  2838. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  2839. "use a number."))
  2840. return
  2841. # self.on_skew("X", value)
  2842. axis = 'X'
  2843. self.app.worker_task.emit({'fcn': self.on_skew,
  2844. 'params': [axis, value]})
  2845. return
  2846. def on_skewy(self, sig=None, val=None):
  2847. if val:
  2848. value = val
  2849. else:
  2850. try:
  2851. value = float(self.skewy_entry.get_value())
  2852. except ValueError:
  2853. # try to convert comma to decimal point. if it's still not working error message and return
  2854. try:
  2855. value = float(self.skewy_entry.get_value().replace(',', '.'))
  2856. except ValueError:
  2857. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  2858. "use a number."))
  2859. return
  2860. # self.on_skew("Y", value)
  2861. axis = 'Y'
  2862. self.app.worker_task.emit({'fcn': self.on_skew,
  2863. 'params': [axis, value]})
  2864. return
  2865. def on_scalex(self, sig=None, val=None):
  2866. if val:
  2867. xvalue = val
  2868. else:
  2869. try:
  2870. xvalue = float(self.scalex_entry.get_value())
  2871. except ValueError:
  2872. # try to convert comma to decimal point. if it's still not working error message and return
  2873. try:
  2874. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  2875. except ValueError:
  2876. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  2877. "use a number."))
  2878. return
  2879. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  2880. if xvalue == 0:
  2881. xvalue = 1
  2882. if self.scale_link_cb.get_value():
  2883. yvalue = xvalue
  2884. else:
  2885. yvalue = 1
  2886. axis = 'X'
  2887. point = (0, 0)
  2888. if self.scale_zero_ref_cb.get_value():
  2889. self.app.worker_task.emit({'fcn': self.on_scale,
  2890. 'params': [axis, xvalue, yvalue, point]})
  2891. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  2892. else:
  2893. # self.on_scale("X", xvalue, yvalue)
  2894. self.app.worker_task.emit({'fcn': self.on_scale,
  2895. 'params': [axis, xvalue, yvalue]})
  2896. return
  2897. def on_scaley(self, sig=None, val=None):
  2898. xvalue = 1
  2899. if val:
  2900. yvalue = val
  2901. else:
  2902. try:
  2903. yvalue = float(self.scaley_entry.get_value())
  2904. except ValueError:
  2905. # try to convert comma to decimal point. if it's still not working error message and return
  2906. try:
  2907. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  2908. except ValueError:
  2909. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  2910. "use a number."))
  2911. return
  2912. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  2913. if yvalue == 0:
  2914. yvalue = 1
  2915. axis = 'Y'
  2916. point = (0, 0)
  2917. if self.scale_zero_ref_cb.get_value():
  2918. self.app.worker_task.emit({'fcn': self.on_scale,
  2919. 'params': [axis, xvalue, yvalue, point]})
  2920. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  2921. else:
  2922. # self.on_scale("Y", xvalue, yvalue)
  2923. self.app.worker_task.emit({'fcn': self.on_scale,
  2924. 'params': [axis, xvalue, yvalue]})
  2925. return
  2926. def on_offx(self, sig=None, val=None):
  2927. if val:
  2928. value = val
  2929. else:
  2930. try:
  2931. value = float(self.offx_entry.get_value())
  2932. except ValueError:
  2933. # try to convert comma to decimal point. if it's still not working error message and return
  2934. try:
  2935. value = float(self.offx_entry.get_value().replace(',', '.'))
  2936. except ValueError:
  2937. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  2938. "use a number."))
  2939. return
  2940. # self.on_offset("X", value)
  2941. axis = 'X'
  2942. self.app.worker_task.emit({'fcn': self.on_offset,
  2943. 'params': [axis, value]})
  2944. return
  2945. def on_offy(self, sig=None, val=None):
  2946. if val:
  2947. value = val
  2948. else:
  2949. try:
  2950. value = float(self.offy_entry.get_value())
  2951. except ValueError:
  2952. # try to convert comma to decimal point. if it's still not working error message and return
  2953. try:
  2954. value = float(self.offy_entry.get_value().replace(',', '.'))
  2955. except ValueError:
  2956. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  2957. "use a number."))
  2958. return
  2959. # self.on_offset("Y", value)
  2960. axis = 'Y'
  2961. self.app.worker_task.emit({'fcn': self.on_offset,
  2962. 'params': [axis, value]})
  2963. return
  2964. def on_rotate_action(self, num):
  2965. shape_list = self.draw_app.selected
  2966. xminlist = []
  2967. yminlist = []
  2968. xmaxlist = []
  2969. ymaxlist = []
  2970. if not shape_list:
  2971. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  2972. return
  2973. else:
  2974. with self.app.proc_container.new(_("Appying Rotate")):
  2975. try:
  2976. # first get a bounding box to fit all
  2977. for sha in shape_list:
  2978. xmin, ymin, xmax, ymax = sha.bounds()
  2979. xminlist.append(xmin)
  2980. yminlist.append(ymin)
  2981. xmaxlist.append(xmax)
  2982. ymaxlist.append(ymax)
  2983. # get the minimum x,y and maximum x,y for all objects selected
  2984. xminimal = min(xminlist)
  2985. yminimal = min(yminlist)
  2986. xmaximal = max(xmaxlist)
  2987. ymaximal = max(ymaxlist)
  2988. self.app.progress.emit(20)
  2989. for sel_sha in shape_list:
  2990. px = 0.5 * (xminimal + xmaximal)
  2991. py = 0.5 * (yminimal + ymaximal)
  2992. sel_sha.rotate(-num, point=(px, py))
  2993. self.draw_app.plot_all()
  2994. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  2995. # self.draw_app.transform_complete.emit()
  2996. self.app.inform.emit(_("[success] Done. Rotate completed."))
  2997. self.app.progress.emit(100)
  2998. except Exception as e:
  2999. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3000. return
  3001. def on_flip(self, axis):
  3002. shape_list = self.draw_app.selected
  3003. xminlist = []
  3004. yminlist = []
  3005. xmaxlist = []
  3006. ymaxlist = []
  3007. if not shape_list:
  3008. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  3009. return
  3010. else:
  3011. with self.app.proc_container.new(_("Applying Flip")):
  3012. try:
  3013. # get mirroring coords from the point entry
  3014. if self.flip_ref_cb.isChecked():
  3015. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  3016. # get mirroing coords from the center of an all-enclosing bounding box
  3017. else:
  3018. # first get a bounding box to fit all
  3019. for sha in shape_list:
  3020. xmin, ymin, xmax, ymax = sha.bounds()
  3021. xminlist.append(xmin)
  3022. yminlist.append(ymin)
  3023. xmaxlist.append(xmax)
  3024. ymaxlist.append(ymax)
  3025. # get the minimum x,y and maximum x,y for all objects selected
  3026. xminimal = min(xminlist)
  3027. yminimal = min(yminlist)
  3028. xmaximal = max(xmaxlist)
  3029. ymaximal = max(ymaxlist)
  3030. px = 0.5 * (xminimal + xmaximal)
  3031. py = 0.5 * (yminimal + ymaximal)
  3032. self.app.progress.emit(20)
  3033. # execute mirroring
  3034. for sha in shape_list:
  3035. if axis is 'X':
  3036. sha.mirror('X', (px, py))
  3037. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  3038. elif axis is 'Y':
  3039. sha.mirror('Y', (px, py))
  3040. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  3041. self.draw_app.plot_all()
  3042. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3043. #
  3044. # self.draw_app.transform_complete.emit()
  3045. self.app.progress.emit(100)
  3046. except Exception as e:
  3047. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3048. return
  3049. def on_skew(self, axis, num):
  3050. shape_list = self.draw_app.selected
  3051. xminlist = []
  3052. yminlist = []
  3053. if not shape_list:
  3054. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  3055. return
  3056. else:
  3057. with self.app.proc_container.new(_("Applying Skew")):
  3058. try:
  3059. # first get a bounding box to fit all
  3060. for sha in shape_list:
  3061. xmin, ymin, xmax, ymax = sha.bounds()
  3062. xminlist.append(xmin)
  3063. yminlist.append(ymin)
  3064. # get the minimum x,y and maximum x,y for all objects selected
  3065. xminimal = min(xminlist)
  3066. yminimal = min(yminlist)
  3067. self.app.progress.emit(20)
  3068. for sha in shape_list:
  3069. if axis is 'X':
  3070. sha.skew(num, 0, point=(xminimal, yminimal))
  3071. elif axis is 'Y':
  3072. sha.skew(0, num, point=(xminimal, yminimal))
  3073. self.draw_app.plot_all()
  3074. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3075. #
  3076. # self.draw_app.transform_complete.emit()
  3077. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  3078. self.app.progress.emit(100)
  3079. except Exception as e:
  3080. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  3081. return
  3082. def on_scale(self, axis, xfactor, yfactor, point=None):
  3083. shape_list = self.draw_app.selected
  3084. xminlist = []
  3085. yminlist = []
  3086. xmaxlist = []
  3087. ymaxlist = []
  3088. if not shape_list:
  3089. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  3090. return
  3091. else:
  3092. with self.app.proc_container.new(_("Applying Scale")):
  3093. try:
  3094. # first get a bounding box to fit all
  3095. for sha in shape_list:
  3096. xmin, ymin, xmax, ymax = sha.bounds()
  3097. xminlist.append(xmin)
  3098. yminlist.append(ymin)
  3099. xmaxlist.append(xmax)
  3100. ymaxlist.append(ymax)
  3101. # get the minimum x,y and maximum x,y for all objects selected
  3102. xminimal = min(xminlist)
  3103. yminimal = min(yminlist)
  3104. xmaximal = max(xmaxlist)
  3105. ymaximal = max(ymaxlist)
  3106. self.app.progress.emit(20)
  3107. if point is None:
  3108. px = 0.5 * (xminimal + xmaximal)
  3109. py = 0.5 * (yminimal + ymaximal)
  3110. else:
  3111. px = 0
  3112. py = 0
  3113. for sha in shape_list:
  3114. sha.scale(xfactor, yfactor, point=(px, py))
  3115. self.draw_app.plot_all()
  3116. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3117. #
  3118. # self.draw_app.transform_complete.emit()
  3119. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  3120. self.app.progress.emit(100)
  3121. except Exception as e:
  3122. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  3123. return
  3124. def on_offset(self, axis, num):
  3125. shape_list = self.draw_app.selected
  3126. xminlist = []
  3127. yminlist = []
  3128. if not shape_list:
  3129. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  3130. return
  3131. else:
  3132. with self.app.proc_container.new(_("Applying Offset")):
  3133. try:
  3134. # first get a bounding box to fit all
  3135. for sha in shape_list:
  3136. xmin, ymin, xmax, ymax = sha.bounds()
  3137. xminlist.append(xmin)
  3138. yminlist.append(ymin)
  3139. # get the minimum x,y and maximum x,y for all objects selected
  3140. xminimal = min(xminlist)
  3141. yminimal = min(yminlist)
  3142. self.app.progress.emit(20)
  3143. for sha in shape_list:
  3144. if axis is 'X':
  3145. sha.offset((num, 0))
  3146. elif axis is 'Y':
  3147. sha.offset((0, num))
  3148. self.draw_app.plot_all()
  3149. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3150. #
  3151. # self.draw_app.transform_complete.emit()
  3152. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  3153. self.app.progress.emit(100)
  3154. except Exception as e:
  3155. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  3156. return
  3157. def on_rotate_key(self):
  3158. val_box = FCInputDialog(title=_("Rotate ..."),
  3159. text=_('Enter an Angle Value (degrees):'),
  3160. min=-359.9999, max=360.0000, decimals=4,
  3161. init_val=float(self.app.defaults['tools_transform_rotate']))
  3162. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  3163. val, ok = val_box.get_value()
  3164. if ok:
  3165. self.on_rotate(val=val)
  3166. self.app.inform.emit(
  3167. _("[success] Geometry shape rotate done...")
  3168. )
  3169. return
  3170. else:
  3171. self.app.inform.emit(
  3172. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  3173. )
  3174. def on_offx_key(self):
  3175. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3176. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  3177. text=(_('Enter a distance Value (%s):') % str(units)),
  3178. min=-9999.9999, max=10000.0000, decimals=4,
  3179. init_val=float(self.app.defaults['tools_transform_offset_x']))
  3180. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  3181. val, ok = val_box.get_value()
  3182. if ok:
  3183. self.on_offx(val=val)
  3184. self.app.inform.emit(
  3185. _("[success] Geometry shape offset on X axis done..."))
  3186. return
  3187. else:
  3188. self.app.inform.emit(
  3189. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  3190. def on_offy_key(self):
  3191. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3192. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  3193. text=(_('Enter a distance Value (%s):') % str(units)),
  3194. min=-9999.9999, max=10000.0000, decimals=4,
  3195. init_val=float(self.app.defaults['tools_transform_offset_y']))
  3196. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  3197. val, ok = val_box.get_value()
  3198. if ok:
  3199. self.on_offx(val=val)
  3200. self.app.inform.emit(
  3201. _("[success] Geometry shape offset on Y axis done..."))
  3202. return
  3203. else:
  3204. self.app.inform.emit(
  3205. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  3206. def on_skewx_key(self):
  3207. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  3208. text=_('Enter an Angle Value (degrees):'),
  3209. min=-359.9999, max=360.0000, decimals=4,
  3210. init_val=float(self.app.defaults['tools_transform_skew_x']))
  3211. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  3212. val, ok = val_box.get_value()
  3213. if ok:
  3214. self.on_skewx(val=val)
  3215. self.app.inform.emit(
  3216. _("[success] Geometry shape skew on X axis done..."))
  3217. return
  3218. else:
  3219. self.app.inform.emit(
  3220. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  3221. def on_skewy_key(self):
  3222. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  3223. text=_('Enter an Angle Value (degrees):'),
  3224. min=-359.9999, max=360.0000, decimals=4,
  3225. init_val=float(self.app.defaults['tools_transform_skew_y']))
  3226. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  3227. val, ok = val_box.get_value()
  3228. if ok:
  3229. self.on_skewx(val=val)
  3230. self.app.inform.emit(
  3231. _("[success] Geometry shape skew on Y axis done..."))
  3232. return
  3233. else:
  3234. self.app.inform.emit(
  3235. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))