FlatCAMGrbEditor.py 152 KB

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