FlatCAMGrbEditor.py 156 KB

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