FlatCAMGrbEditor.py 166 KB

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