FlatCAMExcEditor.py 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 8/17/2019 #
  6. # MIT Licence #
  7. # ##########################################################
  8. from PyQt5 import QtGui, QtCore, QtWidgets
  9. from PyQt5.QtCore import Qt, QSettings
  10. from shapely.geometry import LineString, LinearRing, MultiLineString
  11. from shapely.ops import cascaded_union
  12. import shapely.affinity as affinity
  13. from numpy import arctan2, Inf, array, sqrt, sign, dot
  14. from rtree import index as rtindex
  15. from camlib import *
  16. from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, LengthEntry, RadioSet, SpinBoxDelegate
  17. from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
  18. from copy import copy, deepcopy
  19. import gettext
  20. import FlatCAMTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. class FCDrillAdd(FCShapeTool):
  26. """
  27. Resulting type: MultiLineString
  28. """
  29. def __init__(self, draw_app):
  30. DrawTool.__init__(self, draw_app)
  31. self.name = 'drill_add'
  32. self.selected_dia = None
  33. try:
  34. self.draw_app.app.inform.emit(_("Click to place ..."))
  35. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  36. # as a visual marker, select again in tooltable the actual tool that we are using
  37. # remember that it was deselected when clicking on canvas
  38. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  39. self.draw_app.tools_table_exc.setCurrentItem(item)
  40. except KeyError:
  41. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  42. self.draw_app.select_tool("drill_select")
  43. return
  44. try:
  45. QtGui.QGuiApplication.restoreOverrideCursor()
  46. except Exception as e:
  47. pass
  48. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill.png'))
  49. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  50. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  51. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  52. self.draw_app.draw_utility_geometry(geo=geo)
  53. self.draw_app.app.inform.emit(_("Click to place ..."))
  54. # Switch notebook to Selected page
  55. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  56. def click(self, point):
  57. self.make()
  58. return "Done."
  59. def utility_geometry(self, data=None):
  60. self.points = data
  61. return DrawToolUtilityShape(self.util_shape(data))
  62. def util_shape(self, point):
  63. if point[0] is None and point[1] is None:
  64. point_x = self.draw_app.x
  65. point_y = self.draw_app.y
  66. else:
  67. point_x = point[0]
  68. point_y = point[1]
  69. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  70. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  71. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  72. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  73. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  74. def make(self):
  75. try:
  76. QtGui.QGuiApplication.restoreOverrideCursor()
  77. except Exception as e:
  78. pass
  79. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  80. # to the value, as a list of itself
  81. if self.selected_dia in self.draw_app.points_edit:
  82. self.draw_app.points_edit[self.selected_dia].append(self.points)
  83. else:
  84. self.draw_app.points_edit[self.selected_dia] = [self.points]
  85. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  86. self.geometry = DrawToolShape(self.util_shape(self.points))
  87. self.draw_app.in_action = False
  88. self.complete = True
  89. self.draw_app.app.inform.emit(_("[success] Done. Drill added."))
  90. class FCDrillArray(FCShapeTool):
  91. """
  92. Resulting type: MultiLineString
  93. """
  94. def __init__(self, draw_app):
  95. DrawTool.__init__(self, draw_app)
  96. self.name = 'drill_array'
  97. self.draw_app.array_frame.show()
  98. self.selected_dia = None
  99. self.drill_axis = 'X'
  100. self.drill_array = 'linear'
  101. self.drill_array_size = None
  102. self.drill_pitch = None
  103. self.drill_linear_angle = None
  104. self.drill_angle = None
  105. self.drill_direction = None
  106. self.drill_radius = None
  107. self.origin = None
  108. self.destination = None
  109. self.flag_for_circ_array = None
  110. self.last_dx = 0
  111. self.last_dy = 0
  112. self.pt = []
  113. try:
  114. self.draw_app.app.inform.emit(_("Click to place ..."))
  115. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  116. # as a visual marker, select again in tooltable the actual tool that we are using
  117. # remember that it was deselected when clicking on canvas
  118. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  119. self.draw_app.tools_table_exc.setCurrentItem(item)
  120. except KeyError:
  121. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  122. return
  123. try:
  124. QtGui.QGuiApplication.restoreOverrideCursor()
  125. except Exception as e:
  126. pass
  127. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill_array.png'))
  128. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  129. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  130. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  131. self.draw_app.draw_utility_geometry(geo=geo)
  132. self.draw_app.app.inform.emit(_("Click on target location ..."))
  133. # Switch notebook to Selected page
  134. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  135. def click(self, point):
  136. if self.drill_array == 'Linear':
  137. self.make()
  138. return
  139. else:
  140. if self.flag_for_circ_array is None:
  141. self.draw_app.in_action = True
  142. self.pt.append(point)
  143. self.flag_for_circ_array = True
  144. self.set_origin(point)
  145. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  146. else:
  147. self.destination = point
  148. self.make()
  149. self.flag_for_circ_array = None
  150. return
  151. def set_origin(self, origin):
  152. self.origin = origin
  153. def utility_geometry(self, data=None, static=None):
  154. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  155. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  156. self.drill_array = self.draw_app.array_type_combo.get_value()
  157. try:
  158. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  159. try:
  160. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  161. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  162. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  163. except TypeError:
  164. self.draw_app.app.inform.emit(
  165. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  166. return
  167. except Exception as e:
  168. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value. %s") % str(e))
  169. return
  170. if self.drill_array == 'Linear':
  171. if data[0] is None and data[1] is None:
  172. dx = self.draw_app.x
  173. dy = self.draw_app.y
  174. else:
  175. dx = data[0]
  176. dy = data[1]
  177. geo_list = []
  178. geo = None
  179. self.points = [dx, dy]
  180. for item in range(self.drill_array_size):
  181. if self.drill_axis == 'X':
  182. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  183. if self.drill_axis == 'Y':
  184. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  185. if self.drill_axis == 'A':
  186. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  187. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  188. geo = self.util_shape(
  189. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  190. )
  191. if static is None or static is False:
  192. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  193. else:
  194. geo_list.append(geo)
  195. # self.origin = data
  196. self.last_dx = dx
  197. self.last_dy = dy
  198. return DrawToolUtilityShape(geo_list)
  199. else:
  200. if data[0] is None and data[1] is None:
  201. cdx = self.draw_app.x
  202. cdy = self.draw_app.y
  203. else:
  204. cdx = data[0]
  205. cdy = data[1]
  206. if len(self.pt) > 0:
  207. temp_points = [x for x in self.pt]
  208. temp_points.append([cdx, cdy])
  209. return DrawToolUtilityShape(LineString(temp_points))
  210. def util_shape(self, point):
  211. if point[0] is None and point[1] is None:
  212. point_x = self.draw_app.x
  213. point_y = self.draw_app.y
  214. else:
  215. point_x = point[0]
  216. point_y = point[1]
  217. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  218. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  219. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  220. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  221. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  222. def make(self):
  223. self.geometry = []
  224. geo = None
  225. try:
  226. QtGui.QGuiApplication.restoreOverrideCursor()
  227. except Exception as e:
  228. pass
  229. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  230. # to the value, as a list of itself
  231. if self.selected_dia not in self.draw_app.points_edit:
  232. self.draw_app.points_edit[self.selected_dia] = []
  233. for i in range(self.drill_array_size):
  234. self.draw_app.points_edit[self.selected_dia].append(self.points)
  235. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  236. if self.drill_array == 'Linear':
  237. for item in range(self.drill_array_size):
  238. if self.drill_axis == 'X':
  239. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  240. if self.drill_axis == 'Y':
  241. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  242. if self.drill_axis == 'A':
  243. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  244. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  245. geo = self.util_shape(
  246. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  247. )
  248. self.geometry.append(DrawToolShape(geo))
  249. else:
  250. if (self.drill_angle * self.drill_array_size) > 360:
  251. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many drills for the selected spacing angle."))
  252. return
  253. radius = distance(self.destination, self.origin)
  254. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  255. for i in range(self.drill_array_size):
  256. angle_radians = math.radians(self.drill_angle * i)
  257. if self.drill_direction == 'CW':
  258. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  259. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  260. else:
  261. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  262. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  263. geo = self.util_shape((x, y))
  264. self.geometry.append(DrawToolShape(geo))
  265. self.complete = True
  266. self.draw_app.app.inform.emit(_("[success] Done. Drill Array added."))
  267. self.draw_app.in_action = False
  268. self.draw_app.array_frame.hide()
  269. return
  270. class FCSlot(FCShapeTool):
  271. """
  272. Resulting type: Polygon
  273. """
  274. def __init__(self, draw_app):
  275. DrawTool.__init__(self, draw_app)
  276. self.name = 'slot_add'
  277. self.draw_app = draw_app
  278. self.draw_app.slot_frame.show()
  279. self.selected_dia = None
  280. try:
  281. self.draw_app.app.inform.emit(_("Click to place ..."))
  282. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  283. # as a visual marker, select again in tooltable the actual tool that we are using
  284. # remember that it was deselected when clicking on canvas
  285. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  286. self.draw_app.tools_table_exc.setCurrentItem(item)
  287. except KeyError:
  288. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a slot first select a tool"))
  289. self.draw_app.select_tool("drill_select")
  290. return
  291. try:
  292. QtGui.QGuiApplication.restoreOverrideCursor()
  293. except Exception as e:
  294. pass
  295. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_slot.png'))
  296. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  297. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  298. self.half_height = 0.0
  299. self.half_width = 0.0
  300. self.radius = float(self.selected_dia / 2.0)
  301. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  302. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  303. self.draw_app.draw_utility_geometry(geo=geo)
  304. self.draw_app.app.inform.emit(_("Click on target location ..."))
  305. # Switch notebook to Selected page
  306. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  307. def click(self, point):
  308. self.make()
  309. return "Done."
  310. def utility_geometry(self, data=None):
  311. self.points = data
  312. geo_data = self.util_shape(data)
  313. if geo_data:
  314. return DrawToolUtilityShape(geo_data)
  315. else:
  316. return None
  317. def util_shape(self, point):
  318. if point is None:
  319. return
  320. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  321. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  322. self.radius = float(self.selected_dia / 2.0)
  323. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  324. try:
  325. slot_length = float(self.draw_app.slot_length_entry.get_value())
  326. except ValueError:
  327. # try to convert comma to decimal point. if it's still not working error message and return
  328. try:
  329. slot_length = float(self.draw_app.slot_length_entry.get_value().replace(',', '.'))
  330. self.draw_app.slot_length_entry.set_value(slot_length)
  331. except ValueError:
  332. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  333. "Add it and retry."))
  334. return
  335. try:
  336. slot_angle = float(self.draw_app.slot_angle_spinner.get_value())
  337. except ValueError:
  338. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  339. "Add it and retry."))
  340. return
  341. if self.draw_app.slot_axis_radio.get_value() == 'X':
  342. self.half_width = slot_length / 2.0
  343. self.half_height = self.radius
  344. else:
  345. self.half_width = self.radius
  346. self.half_height = slot_length / 2.0
  347. if point[0] is None and point[1] is None:
  348. point_x = self.draw_app.x
  349. point_y = self.draw_app.y
  350. else:
  351. point_x = point[0]
  352. point_y = point[1]
  353. geo = []
  354. if self.half_height > self.half_width:
  355. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  356. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  357. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  358. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  359. down_center = [point_x, point_y - self.half_height + self.half_width]
  360. d_start_angle = math.pi
  361. d_stop_angle = 0.0
  362. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  363. up_center = [point_x, point_y + self.half_height - self.half_width]
  364. u_start_angle = 0.0
  365. u_stop_angle = math.pi
  366. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  367. geo.append(p1)
  368. for pt in down_arc:
  369. geo.append(pt)
  370. geo.append(p2)
  371. geo.append(p3)
  372. for pt in up_arc:
  373. geo.append(pt)
  374. geo.append(p4)
  375. if self.draw_app.slot_axis_radio.get_value() == 'A':
  376. return affinity.rotate(geom=Polygon(geo), angle=-slot_angle)
  377. else:
  378. return Polygon(geo)
  379. else:
  380. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  381. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  382. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  383. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  384. left_center = [point_x - self.half_width + self.half_height, point_y]
  385. d_start_angle = math.pi / 2
  386. d_stop_angle = 1.5 * math.pi
  387. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  388. right_center = [point_x + self.half_width - self.half_height, point_y]
  389. u_start_angle = 1.5 * math.pi
  390. u_stop_angle = math.pi / 2
  391. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  392. geo.append(p1)
  393. geo.append(p2)
  394. for pt in right_arc:
  395. geo.append(pt)
  396. geo.append(p3)
  397. geo.append(p4)
  398. for pt in left_arc:
  399. geo.append(pt)
  400. return Polygon(geo)
  401. def make(self):
  402. try:
  403. QtGui.QGuiApplication.restoreOverrideCursor()
  404. except Exception as e:
  405. pass
  406. try:
  407. self.geometry = DrawToolShape(self.util_shape(self.points))
  408. except Exception as e:
  409. log.debug("FCSlot.make() --> %s" % str(e))
  410. # add the point to drills/slots if the diameter is a key in the dict, if not, create it add the drill location
  411. # to the value, as a list of itself
  412. if self.selected_dia in self.draw_app.slot_points_edit:
  413. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  414. else:
  415. self.draw_app.slot_points_edit[self.selected_dia] = [self.points]
  416. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  417. self.draw_app.in_action = False
  418. self.complete = True
  419. self.draw_app.app.inform.emit(_("[success] Done. Adding Slot completed."))
  420. self.draw_app.slot_frame.hide()
  421. class FCSlotArray(FCShapeTool):
  422. """
  423. Resulting type: MultiPolygon
  424. """
  425. def __init__(self, draw_app):
  426. DrawTool.__init__(self, draw_app)
  427. self.name = 'slot_array'
  428. self.draw_app = draw_app
  429. self.draw_app.slot_frame.show()
  430. self.draw_app.slot_array_frame.show()
  431. self.selected_dia = None
  432. try:
  433. self.draw_app.app.inform.emit(_("Click to place ..."))
  434. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  435. # as a visual marker, select again in tooltable the actual tool that we are using
  436. # remember that it was deselected when clicking on canvas
  437. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  438. self.draw_app.tools_table_exc.setCurrentItem(item)
  439. except KeyError:
  440. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Slot Array first select a tool in Tool Table"))
  441. return
  442. try:
  443. QtGui.QGuiApplication.restoreOverrideCursor()
  444. except Exception as e:
  445. pass
  446. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_array.png'))
  447. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  448. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  449. self.half_width = 0.0
  450. self.half_height = 0.0
  451. self.radius = float(self.selected_dia / 2.0)
  452. self.slot_axis = 'X'
  453. self.slot_array = 'linear'
  454. self.slot_array_size = None
  455. self.slot_pitch = None
  456. self.slot_linear_angle = None
  457. self.slot_angle = None
  458. self.slot_direction = None
  459. self.slot_radius = None
  460. self.origin = None
  461. self.destination = None
  462. self.flag_for_circ_array = None
  463. self.last_dx = 0
  464. self.last_dy = 0
  465. self.pt = []
  466. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  467. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  468. self.draw_app.draw_utility_geometry(geo=geo)
  469. self.draw_app.app.inform.emit(_("Click on target location ..."))
  470. # Switch notebook to Selected page
  471. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  472. def click(self, point):
  473. if self.slot_array == 'Linear':
  474. self.make()
  475. return
  476. else:
  477. if self.flag_for_circ_array is None:
  478. self.draw_app.in_action = True
  479. self.pt.append(point)
  480. self.flag_for_circ_array = True
  481. self.set_origin(point)
  482. self.draw_app.app.inform.emit(_("Click on the Slot Circular Array Start position"))
  483. else:
  484. self.destination = point
  485. self.make()
  486. self.flag_for_circ_array = None
  487. return
  488. def set_origin(self, origin):
  489. self.origin = origin
  490. def utility_geometry(self, data=None, static=None):
  491. self.slot_axis = self.draw_app.slot_array_axis_radio.get_value()
  492. self.slot_direction = self.draw_app.slot_array_direction_radio.get_value()
  493. self.slot_array = self.draw_app.slot_array_type_combo.get_value()
  494. try:
  495. self.slot_array_size = int(self.draw_app.slot_array_size_entry.get_value())
  496. try:
  497. self.slot_pitch = float(self.draw_app.slot_array_pitch_entry.get_value())
  498. self.slot_linear_angle = float(self.draw_app.slot_array_linear_angle_spinner.get_value())
  499. self.slot_angle = float(self.draw_app.slot_array_angle_entry.get_value())
  500. except TypeError:
  501. self.draw_app.app.inform.emit(
  502. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  503. return
  504. except Exception as e:
  505. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  506. return
  507. if self.slot_array == 'Linear':
  508. if data[0] is None and data[1] is None:
  509. dx = self.draw_app.x
  510. dy = self.draw_app.y
  511. else:
  512. dx = data[0]
  513. dy = data[1]
  514. geo_el_list = []
  515. geo_el = []
  516. self.points = [dx, dy]
  517. for item in range(self.slot_array_size):
  518. if self.slot_axis == 'X':
  519. geo_el = self.util_shape(((dx + (self.slot_pitch * item)), dy))
  520. if self.slot_axis == 'Y':
  521. geo_el = self.util_shape((dx, (dy + (self.slot_pitch * item))))
  522. if self.slot_axis == 'A':
  523. x_adj = self.slot_pitch * math.cos(math.radians(self.slot_linear_angle))
  524. y_adj = self.slot_pitch * math.sin(math.radians(self.slot_linear_angle))
  525. geo_el = self.util_shape(
  526. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  527. )
  528. if static is None or static is False:
  529. geo_el = affinity.translate(geo_el, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy))
  530. geo_el_list.append(geo_el)
  531. self.last_dx = dx
  532. self.last_dy = dy
  533. return DrawToolUtilityShape(geo_el_list)
  534. else:
  535. if data[0] is None and data[1] is None:
  536. cdx = self.draw_app.x
  537. cdy = self.draw_app.y
  538. else:
  539. cdx = data[0]
  540. cdy = data[1]
  541. if len(self.pt) > 0:
  542. temp_points = [x for x in self.pt]
  543. temp_points.append([cdx, cdy])
  544. return DrawToolUtilityShape(LineString(temp_points))
  545. def util_shape(self, point):
  546. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  547. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  548. self.radius = float(self.selected_dia / 2.0)
  549. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  550. try:
  551. slot_length = float(self.draw_app.slot_length_entry.get_value())
  552. except ValueError:
  553. # try to convert comma to decimal point. if it's still not working error message and return
  554. try:
  555. slot_length = float(self.draw_app.slot_length_entry.get_value().replace(',', '.'))
  556. self.draw_app.slot_length_entry.set_value(slot_length)
  557. except ValueError:
  558. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  559. "Add it and retry."))
  560. return
  561. try:
  562. slot_angle = float(self.draw_app.slot_angle_spinner.get_value())
  563. except ValueError:
  564. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  565. "Add it and retry."))
  566. return
  567. if self.draw_app.slot_axis_radio.get_value() == 'X':
  568. self.half_width = slot_length / 2.0
  569. self.half_height = self.radius
  570. else:
  571. self.half_width = self.radius
  572. self.half_height = slot_length / 2.0
  573. if point[0] is None and point[1] is None:
  574. point_x = self.draw_app.x
  575. point_y = self.draw_app.y
  576. else:
  577. point_x = point[0]
  578. point_y = point[1]
  579. geo = []
  580. if self.half_height > self.half_width:
  581. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  582. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  583. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  584. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  585. down_center = [point_x, point_y - self.half_height + self.half_width]
  586. d_start_angle = math.pi
  587. d_stop_angle = 0.0
  588. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  589. up_center = [point_x, point_y + self.half_height - self.half_width]
  590. u_start_angle = 0.0
  591. u_stop_angle = math.pi
  592. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  593. geo.append(p1)
  594. for pt in down_arc:
  595. geo.append(pt)
  596. geo.append(p2)
  597. geo.append(p3)
  598. for pt in up_arc:
  599. geo.append(pt)
  600. geo.append(p4)
  601. else:
  602. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  603. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  604. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  605. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  606. left_center = [point_x - self.half_width + self.half_height, point_y]
  607. d_start_angle = math.pi / 2
  608. d_stop_angle = 1.5 * math.pi
  609. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  610. right_center = [point_x + self.half_width - self.half_height, point_y]
  611. u_start_angle = 1.5 * math.pi
  612. u_stop_angle = math.pi / 2
  613. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  614. geo.append(p1)
  615. geo.append(p2)
  616. for pt in right_arc:
  617. geo.append(pt)
  618. geo.append(p3)
  619. geo.append(p4)
  620. for pt in left_arc:
  621. geo.append(pt)
  622. # this function return one slot in the slot array and the following will rotate that one slot around it's
  623. # center if the radio value is "A".
  624. if self.draw_app.slot_axis_radio.get_value() == 'A':
  625. return affinity.rotate(Polygon(geo), -slot_angle)
  626. else:
  627. return Polygon(geo)
  628. def make(self):
  629. self.geometry = []
  630. geo = None
  631. try:
  632. QtGui.QGuiApplication.restoreOverrideCursor()
  633. except Exception as e:
  634. pass
  635. # add the point to slots if the diameter is a key in the dict, if not, create it add the drill location
  636. # to the value, as a list of itself
  637. if self.selected_dia not in self.draw_app.slot_points_edit:
  638. self.draw_app.slot_points_edit[self.selected_dia] = []
  639. for i in range(self.slot_array_size):
  640. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  641. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  642. if self.slot_array == 'Linear':
  643. for item in range(self.slot_array_size):
  644. if self.slot_axis == 'X':
  645. geo = self.util_shape(((self.points[0] + (self.slot_pitch * item)), self.points[1]))
  646. if self.slot_axis == 'Y':
  647. geo = self.util_shape((self.points[0], (self.points[1] + (self.slot_pitch * item))))
  648. if self.slot_axis == 'A':
  649. x_adj = self.slot_pitch * math.cos(math.radians(self.slot_linear_angle))
  650. y_adj = self.slot_pitch * math.sin(math.radians(self.slot_linear_angle))
  651. geo = self.util_shape(
  652. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  653. )
  654. self.geometry.append(DrawToolShape(geo))
  655. else:
  656. if (self.slot_angle * self.slot_array_size) > 360:
  657. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many Slots for the selected spacing angle."))
  658. return
  659. radius = distance(self.destination, self.origin)
  660. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  661. for i in range(self.slot_array_size):
  662. angle_radians = math.radians(self.slot_angle * i)
  663. if self.slot_direction == 'CW':
  664. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  665. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  666. else:
  667. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  668. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  669. geo = self.util_shape((x, y))
  670. if self.slot_direction == 'CW':
  671. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  672. else:
  673. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  674. self.geometry.append(DrawToolShape(geo))
  675. self.complete = True
  676. self.draw_app.app.inform.emit(_("[success] Done. Slot Array added."))
  677. self.draw_app.in_action = False
  678. self.draw_app.slot_frame.hide()
  679. self.draw_app.slot_array_frame.hide()
  680. return
  681. def clean_up(self):
  682. self.draw_app.selected = []
  683. self.draw_app.apertures_table.clearSelection()
  684. self.draw_app.plot_all()
  685. class FCDrillResize(FCShapeTool):
  686. def __init__(self, draw_app):
  687. DrawTool.__init__(self, draw_app)
  688. self.name = 'drill_resize'
  689. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  690. self.resize_dia = None
  691. self.draw_app.resize_frame.show()
  692. self.points = None
  693. # made this a set so there are no duplicates
  694. self.selected_dia_set = set()
  695. self.current_storage = None
  696. self.geometry = []
  697. self.destination_storage = None
  698. self.draw_app.resize_btn.clicked.connect(self.make)
  699. self.draw_app.resdrill_entry.editingFinished.connect(self.make)
  700. # Switch notebook to Selected page
  701. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  702. def make(self):
  703. self.draw_app.is_modified = True
  704. try:
  705. self.draw_app.tools_table_exc.itemChanged.disconnect()
  706. except TypeError:
  707. pass
  708. try:
  709. new_dia = self.draw_app.resdrill_entry.get_value()
  710. except:
  711. self.draw_app.app.inform.emit(
  712. _("[ERROR_NOTCL] Resize drill(s) failed. Please enter a diameter for resize.")
  713. )
  714. return
  715. if new_dia not in self.draw_app.olddia_newdia:
  716. self.destination_storage = FlatCAMGeoEditor.make_storage()
  717. self.draw_app.storage_dict[new_dia] = self.destination_storage
  718. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  719. # each time a tool diameter is edited or added
  720. self.draw_app.olddia_newdia[new_dia] = new_dia
  721. else:
  722. self.destination_storage = self.draw_app.storage_dict[new_dia]
  723. for index in self.draw_app.tools_table_exc.selectedIndexes():
  724. row = index.row()
  725. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  726. # therefore below we convert to float
  727. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  728. self.selected_dia_set.add(float(dia_on_row))
  729. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  730. # we add a new entry in the tool2tooldia dict
  731. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  732. sel_shapes_to_be_deleted = []
  733. if self.selected_dia_set:
  734. for sel_dia in self.selected_dia_set:
  735. self.current_storage = self.draw_app.storage_dict[sel_dia]
  736. for select_shape in self.draw_app.get_selected():
  737. if select_shape in self.current_storage.get_objects():
  738. # add new geometry according to the new size
  739. if isinstance(select_shape.geo, MultiLineString):
  740. factor = new_dia / sel_dia
  741. self.geometry.append(DrawToolShape(affinity.scale(select_shape.geo,
  742. xfact=factor,
  743. yfact=factor,
  744. origin='center')))
  745. elif isinstance(select_shape.geo, Polygon):
  746. # I don't have any info regarding the angle of the slot geometry, nor how thick it is or
  747. # how long it is given the angle. So I will have to make an approximation because
  748. # we need to conserve the slot length, we only resize the diameter for the tool
  749. # Therefore scaling won't work and buffering will not work either.
  750. # First we get the Linestring that is one that the original slot is built around with the
  751. # tool having the diameter sel_dia
  752. poly = select_shape.geo
  753. xmin, ymin, xmax, ymax = poly.bounds
  754. # a line that is certain to be bigger than our slot because it's the diagonal
  755. # of it's bounding box
  756. poly_diagonal = LineString([(xmin, ymin), (xmax, ymax)])
  757. poly_centroid = poly.centroid
  758. # center of the slot geometry
  759. poly_center = (poly_centroid.x, poly_centroid.y)
  760. # make a list of intersections with the rotated line
  761. list_of_cuttings = []
  762. for angle in range(0, 359, 1):
  763. rot_poly_diagonal = affinity.rotate(poly_diagonal, angle=angle, origin=poly_center)
  764. cut_line = rot_poly_diagonal.intersection(poly)
  765. cut_line_len = cut_line.length
  766. list_of_cuttings.append(
  767. (cut_line_len, cut_line)
  768. )
  769. # find the cut_line with the maximum length which is the LineString for which the start
  770. # and stop point are the start and stop point of the slot as in the Gerber file
  771. cut_line_with_max_length = max(list_of_cuttings, key=lambda i: i[0])[1]
  772. # find the coordinates of this line
  773. cut_line_with_max_length_coords = list(cut_line_with_max_length.coords)
  774. # extract the first and last point of the line and build some buffered polygon circles
  775. # around them
  776. start_pt = Point(cut_line_with_max_length_coords[0])
  777. stop_pt = Point(cut_line_with_max_length_coords[1])
  778. start_cut_geo = start_pt.buffer(new_dia / 2)
  779. stop_cut_geo = stop_pt.buffer(new_dia / 2)
  780. # and we cut the above circle polygons from our line and get in this way a line around
  781. # which we can build the new slot by buffering with the new tool diameter
  782. new_line = cut_line_with_max_length.difference(start_cut_geo)
  783. new_line = new_line.difference(stop_cut_geo)
  784. # create the geometry for the resized slot by buffering with half of the
  785. # new diameter value, new_dia
  786. new_poly = new_line.buffer(new_dia / 2)
  787. self.geometry.append(DrawToolShape(new_poly))
  788. else:
  789. # unexpected geometry so we cancel
  790. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Cancelled."))
  791. return
  792. # remove the geometry with the old size
  793. self.current_storage.remove(select_shape)
  794. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  795. # self.points_edit it's only useful first time when we load the data into the storage
  796. # but is still used as reference when building tool_table in self.build_ui()
  797. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  798. # deleting self.points_edit elements (doesn't matter who but just the number)
  799. # solved the display issue.
  800. if isinstance(select_shape.geo, MultiLineString):
  801. try:
  802. del self.draw_app.points_edit[sel_dia][0]
  803. except KeyError:
  804. # if the exception happen here then we are not dealing with drills but with slots
  805. # This should not happen as the drills have MultiLineString geometry and slots have
  806. # Polygon geometry
  807. pass
  808. if isinstance(select_shape.geo, Polygon):
  809. try:
  810. del self.draw_app.slot_points_edit[sel_dia][0]
  811. except KeyError:
  812. # if the exception happen here then we are not dealing with slots but with drills
  813. # This should not happen as the drills have MultiLineString geometry and slots have
  814. # Polygon geometry
  815. pass
  816. sel_shapes_to_be_deleted.append(select_shape)
  817. # a hack to make the tool_table display more drills/slots per diameter when shape(drill/slot)
  818. # is added.
  819. # self.points_edit it's only useful first time when we load the data into the storage
  820. # but is still used as reference when building tool_table in self.build_ui()
  821. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  822. # deleting self.points_edit elements (doesn't matter who but just the number)
  823. # solved the display issue.
  824. # for drills
  825. if isinstance(select_shape.geo, MultiLineString):
  826. if new_dia not in self.draw_app.points_edit:
  827. self.draw_app.points_edit[new_dia] = [(0, 0)]
  828. else:
  829. self.draw_app.points_edit[new_dia].append((0, 0))
  830. # for slots
  831. if isinstance(select_shape.geo, Polygon):
  832. if new_dia not in self.draw_app.slot_points_edit:
  833. self.draw_app.slot_points_edit[new_dia] = [(0, 0)]
  834. else:
  835. self.draw_app.slot_points_edit[new_dia].append((0, 0))
  836. for dia_key in list(self.draw_app.storage_dict.keys()):
  837. # if following the resize of the drills there will be no more drills for some of the tools then
  838. # delete those tools
  839. try:
  840. if not self.draw_app.points_edit[dia_key]:
  841. self.draw_app.on_tool_delete(dia_key)
  842. except KeyError:
  843. # if the exception happen here then we are not dealing with drills but with slots
  844. # so we try for them
  845. try:
  846. if not self.draw_app.slot_points_edit[dia_key]:
  847. self.draw_app.on_tool_delete(dia_key)
  848. except KeyError:
  849. # if the exception happen here then we are not dealing with slots neither
  850. # therefore something else is not OK so we return
  851. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Cancelled."))
  852. return
  853. # this simple hack is used so we can delete form self.draw_app.selected but
  854. # after we no longer iterate through it
  855. for shp in sel_shapes_to_be_deleted:
  856. self.draw_app.selected.remove(shp)
  857. # add the new geometry to storage
  858. self.draw_app.on_exc_shape_complete(self.destination_storage)
  859. self.draw_app.build_ui()
  860. self.draw_app.replot()
  861. # empty the self.geometry
  862. self.geometry = []
  863. # we reactivate the signals after the after the tool editing
  864. self.draw_app.tools_table_exc.itemChanged.connect(self.draw_app.on_tool_edit)
  865. self.draw_app.app.inform.emit(_("[success] Done. Drill/Slot Resize completed."))
  866. else:
  867. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No drills/slots selected for resize ..."))
  868. # init this set() for another use perhaps
  869. self.selected_dia_set = set()
  870. self.draw_app.resize_frame.hide()
  871. self.complete = True
  872. # MS: always return to the Select Tool
  873. self.draw_app.select_tool("drill_select")
  874. class FCDrillMove(FCShapeTool):
  875. def __init__(self, draw_app):
  876. DrawTool.__init__(self, draw_app)
  877. self.name = 'drill_move'
  878. # self.shape_buffer = self.draw_app.shape_buffer
  879. self.origin = None
  880. self.destination = None
  881. self.sel_limit = self.draw_app.app.defaults["excellon_editor_sel_limit"]
  882. self.selection_shape = self.selection_bbox()
  883. self.selected_dia_list = []
  884. if self.draw_app.launched_from_shortcuts is True:
  885. self.draw_app.launched_from_shortcuts = False
  886. self.draw_app.app.inform.emit(_("Click on target location ..."))
  887. else:
  888. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  889. self.current_storage = None
  890. self.geometry = []
  891. for index in self.draw_app.tools_table_exc.selectedIndexes():
  892. row = index.row()
  893. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  894. # therefore below we convert to float
  895. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  896. self.selected_dia_list.append(float(dia_on_row))
  897. # Switch notebook to Selected page
  898. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  899. def set_origin(self, origin):
  900. self.origin = origin
  901. def click(self, point):
  902. if len(self.draw_app.get_selected()) == 0:
  903. return "Nothing to move."
  904. if self.origin is None:
  905. self.set_origin(point)
  906. self.draw_app.app.inform.emit(_("Click on target location ..."))
  907. return
  908. else:
  909. self.destination = point
  910. self.make()
  911. # MS: always return to the Select Tool
  912. self.draw_app.select_tool("drill_select")
  913. return
  914. def make(self):
  915. # Create new geometry
  916. dx = self.destination[0] - self.origin[0]
  917. dy = self.destination[1] - self.origin[1]
  918. sel_shapes_to_be_deleted = []
  919. for sel_dia in self.selected_dia_list:
  920. self.current_storage = self.draw_app.storage_dict[sel_dia]
  921. for select_shape in self.draw_app.get_selected():
  922. if select_shape in self.current_storage.get_objects():
  923. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  924. self.current_storage.remove(select_shape)
  925. sel_shapes_to_be_deleted.append(select_shape)
  926. self.draw_app.on_exc_shape_complete(self.current_storage)
  927. self.geometry = []
  928. for shp in sel_shapes_to_be_deleted:
  929. self.draw_app.selected.remove(shp)
  930. sel_shapes_to_be_deleted = []
  931. self.draw_app.build_ui()
  932. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) Move completed."))
  933. def selection_bbox(self):
  934. geo_list = []
  935. for select_shape in self.draw_app.get_selected():
  936. geometric_data = select_shape.geo
  937. try:
  938. for g in geometric_data:
  939. geo_list.append(g)
  940. except TypeError:
  941. geo_list.append(geometric_data)
  942. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  943. pt1 = (xmin, ymin)
  944. pt2 = (xmax, ymin)
  945. pt3 = (xmax, ymax)
  946. pt4 = (xmin, ymax)
  947. return Polygon([pt1, pt2, pt3, pt4])
  948. def utility_geometry(self, data=None):
  949. """
  950. Temporary geometry on screen while using this tool.
  951. :param data:
  952. :return:
  953. """
  954. geo_list = []
  955. if self.origin is None:
  956. return None
  957. if len(self.draw_app.get_selected()) == 0:
  958. return None
  959. dx = data[0] - self.origin[0]
  960. dy = data[1] - self.origin[1]
  961. if len(self.draw_app.get_selected()) <= self.sel_limit:
  962. try:
  963. for geom in self.draw_app.get_selected():
  964. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  965. except AttributeError:
  966. self.draw_app.select_tool('drill_select')
  967. self.draw_app.selected = []
  968. return
  969. return DrawToolUtilityShape(geo_list)
  970. else:
  971. try:
  972. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  973. except ValueError:
  974. ss_el = None
  975. return DrawToolUtilityShape(ss_el)
  976. class FCDrillCopy(FCDrillMove):
  977. def __init__(self, draw_app):
  978. FCDrillMove.__init__(self, draw_app)
  979. self.name = 'drill_copy'
  980. def make(self):
  981. # Create new geometry
  982. dx = self.destination[0] - self.origin[0]
  983. dy = self.destination[1] - self.origin[1]
  984. sel_shapes_to_be_deleted = []
  985. for sel_dia in self.selected_dia_list:
  986. self.current_storage = self.draw_app.storage_dict[sel_dia]
  987. for select_shape in self.draw_app.get_selected():
  988. if select_shape in self.current_storage.get_objects():
  989. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  990. # Add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  991. # This may fail if we copy slots.
  992. try:
  993. self.draw_app.points_edit[sel_dia].append((0, 0))
  994. except KeyError:
  995. pass
  996. # add some fake slots into the self.draw_app.slots_points_edit
  997. # to update the slot count in tool table
  998. # This may fail if we copy drills.
  999. try:
  1000. self.draw_app.slot_points_edit[sel_dia].append((0, 0))
  1001. except KeyError:
  1002. pass
  1003. sel_shapes_to_be_deleted.append(select_shape)
  1004. self.draw_app.on_exc_shape_complete(self.current_storage)
  1005. self.geometry = []
  1006. for shp in sel_shapes_to_be_deleted:
  1007. self.draw_app.selected.remove(shp)
  1008. sel_shapes_to_be_deleted = []
  1009. self.draw_app.build_ui()
  1010. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) copied."))
  1011. class FCDrillSelect(DrawTool):
  1012. def __init__(self, exc_editor_app):
  1013. DrawTool.__init__(self, exc_editor_app)
  1014. self.name = 'drill_select'
  1015. try:
  1016. QtGui.QGuiApplication.restoreOverrideCursor()
  1017. except Exception as e:
  1018. pass
  1019. self.exc_editor_app = exc_editor_app
  1020. self.storage = self.exc_editor_app.storage_dict
  1021. # self.selected = self.exc_editor_app.selected
  1022. # here we store all shapes that were selected so we can search for the nearest to our click location
  1023. self.sel_storage = FlatCAMExcEditor.make_storage()
  1024. self.exc_editor_app.resize_frame.hide()
  1025. self.exc_editor_app.array_frame.hide()
  1026. self.exc_editor_app.slot_frame.hide()
  1027. self.exc_editor_app.slot_array_frame.hide()
  1028. def click(self, point):
  1029. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1030. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1031. if key_modifier == Qt.ControlModifier:
  1032. pass
  1033. else:
  1034. self.exc_editor_app.selected = []
  1035. else:
  1036. if key_modifier == Qt.ShiftModifier:
  1037. pass
  1038. else:
  1039. self.exc_editor_app.selected = []
  1040. def click_release(self, pos):
  1041. self.exc_editor_app.tools_table_exc.clearSelection()
  1042. xmin, ymin, xmax, ymax = 0, 0, 0, 0
  1043. try:
  1044. for storage in self.exc_editor_app.storage_dict:
  1045. for sh in self.exc_editor_app.storage_dict[storage].get_objects():
  1046. self.sel_storage.insert(sh)
  1047. _, closest_shape = self.sel_storage.nearest(pos)
  1048. # constrain selection to happen only within a certain bounding box; it works only for MultiLineStrings
  1049. if isinstance(closest_shape.geo, MultiLineString):
  1050. x_coord, y_coord = closest_shape.geo[0].xy
  1051. delta = (x_coord[1] - x_coord[0])
  1052. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  1053. xmin = x_coord[0] - (0.7 * delta)
  1054. xmax = x_coord[0] + (1.7 * delta)
  1055. ymin = y_coord[0] - (0.7 * delta)
  1056. ymax = y_coord[0] + (1.7 * delta)
  1057. elif isinstance(closest_shape.geo, Polygon):
  1058. xmin, ymin, xmax, ymax = closest_shape.geo.bounds
  1059. dx = xmax - xmin
  1060. dy = ymax - ymin
  1061. delta = dx if dx > dy else dy
  1062. xmin -= 0.7 * delta
  1063. xmax += 0.7 * delta
  1064. ymin -= 0.7 * delta
  1065. ymax += 0.7 * delta
  1066. except StopIteration:
  1067. return ""
  1068. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  1069. self.exc_editor_app.selected = []
  1070. else:
  1071. modifiers = QtWidgets.QApplication.keyboardModifiers()
  1072. mod_key = 'Control'
  1073. if modifiers == QtCore.Qt.ShiftModifier:
  1074. mod_key = 'Shift'
  1075. elif modifiers == QtCore.Qt.ControlModifier:
  1076. mod_key = 'Control'
  1077. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  1078. if closest_shape in self.exc_editor_app.selected:
  1079. self.exc_editor_app.selected.remove(closest_shape)
  1080. else:
  1081. self.exc_editor_app.selected.append(closest_shape)
  1082. else:
  1083. self.draw_app.selected = []
  1084. self.draw_app.selected.append(closest_shape)
  1085. # select the diameter of the selected shape in the tool table
  1086. try:
  1087. self.draw_app.tools_table_exc.cellPressed.disconnect()
  1088. except (TypeError, AttributeError):
  1089. pass
  1090. sel_tools = set()
  1091. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1092. for shape_s in self.exc_editor_app.selected:
  1093. for storage in self.exc_editor_app.storage_dict:
  1094. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  1095. sel_tools.add(storage)
  1096. for storage in sel_tools:
  1097. for k, v in self.draw_app.tool2tooldia.items():
  1098. if v == storage:
  1099. self.exc_editor_app.tools_table_exc.selectRow(int(k) - 1)
  1100. self.draw_app.last_tool_selected = int(k)
  1101. break
  1102. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1103. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  1104. # delete whatever is in selection storage, there is no longer need for those shapes
  1105. self.sel_storage = FlatCAMExcEditor.make_storage()
  1106. return ""
  1107. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1108. # for storage in self.exc_editor_app.storage_dict:
  1109. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1110. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1111. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1112. # over_shape_list.append(obj_shape)
  1113. #
  1114. # try:
  1115. # # if there is no shape under our click then deselect all shapes
  1116. # if not over_shape_list:
  1117. # self.exc_editor_app.selected = []
  1118. # FlatCAMExcEditor.draw_shape_idx = -1
  1119. # self.exc_editor_app.tools_table_exc.clearSelection()
  1120. # else:
  1121. # # if there are shapes under our click then advance through the list of them, one at the time in a
  1122. # # circular way
  1123. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  1124. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  1125. #
  1126. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  1127. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  1128. # if obj_to_add in self.exc_editor_app.selected:
  1129. # self.exc_editor_app.selected.remove(obj_to_add)
  1130. # else:
  1131. # self.exc_editor_app.selected.append(obj_to_add)
  1132. # else:
  1133. # self.exc_editor_app.selected = []
  1134. # self.exc_editor_app.selected.append(obj_to_add)
  1135. # else:
  1136. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1137. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  1138. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  1139. # if obj_to_add in self.exc_editor_app.selected:
  1140. # self.exc_editor_app.selected.remove(obj_to_add)
  1141. # else:
  1142. # self.exc_editor_app.selected.append(obj_to_add)
  1143. # else:
  1144. # self.exc_editor_app.selected = []
  1145. # self.exc_editor_app.selected.append(obj_to_add)
  1146. #
  1147. # for storage in self.exc_editor_app.storage_dict:
  1148. # for shape in self.exc_editor_app.selected:
  1149. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1150. # for key in self.exc_editor_app.tool2tooldia:
  1151. # if self.exc_editor_app.tool2tooldia[key] == storage:
  1152. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1153. # item.setSelected(True)
  1154. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1155. #
  1156. # except Exception as e:
  1157. # log.error("[ERROR] Something went bad. %s" % str(e))
  1158. # raise
  1159. class FlatCAMExcEditor(QtCore.QObject):
  1160. draw_shape_idx = -1
  1161. def __init__(self, app):
  1162. assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1163. super(FlatCAMExcEditor, self).__init__()
  1164. self.app = app
  1165. self.canvas = self.app.plotcanvas
  1166. # ## Current application units in Upper Case
  1167. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1168. self.exc_edit_widget = QtWidgets.QWidget()
  1169. # ## Box for custom widgets
  1170. # This gets populated in offspring implementations.
  1171. layout = QtWidgets.QVBoxLayout()
  1172. self.exc_edit_widget.setLayout(layout)
  1173. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1174. # this way I can hide/show the frame
  1175. self.drills_frame = QtWidgets.QFrame()
  1176. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  1177. layout.addWidget(self.drills_frame)
  1178. self.tools_box = QtWidgets.QVBoxLayout()
  1179. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1180. self.drills_frame.setLayout(self.tools_box)
  1181. # ## Page Title box (spacing between children)
  1182. self.title_box = QtWidgets.QHBoxLayout()
  1183. self.tools_box.addLayout(self.title_box)
  1184. # ## Page Title icon
  1185. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1186. self.icon = QtWidgets.QLabel()
  1187. self.icon.setPixmap(pixmap)
  1188. self.title_box.addWidget(self.icon, stretch=0)
  1189. # ## Title label
  1190. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  1191. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1192. self.title_box.addWidget(self.title_label, stretch=1)
  1193. # ## Object name
  1194. self.name_box = QtWidgets.QHBoxLayout()
  1195. self.tools_box.addLayout(self.name_box)
  1196. name_label = QtWidgets.QLabel(_("Name:"))
  1197. self.name_box.addWidget(name_label)
  1198. self.name_entry = FCEntry()
  1199. self.name_box.addWidget(self.name_entry)
  1200. # ### Tools Drills ## ##
  1201. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  1202. self.tools_table_label.setToolTip(
  1203. _("Tools in this Excellon object\n"
  1204. "when are used for drilling.")
  1205. )
  1206. self.tools_box.addWidget(self.tools_table_label)
  1207. self.tools_table_exc = FCTable()
  1208. # delegate = SpinBoxDelegate(units=self.units)
  1209. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  1210. self.tools_box.addWidget(self.tools_table_exc)
  1211. self.tools_table_exc.setColumnCount(4)
  1212. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1213. self.tools_table_exc.setSortingEnabled(False)
  1214. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1215. self.empty_label = QtWidgets.QLabel('')
  1216. self.tools_box.addWidget(self.empty_label)
  1217. # ### Add a new Tool ## ##
  1218. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  1219. self.addtool_label.setToolTip(
  1220. _("Add/Delete a tool to the tool list\n"
  1221. "for this Excellon object.")
  1222. )
  1223. self.tools_box.addWidget(self.addtool_label)
  1224. grid1 = QtWidgets.QGridLayout()
  1225. self.tools_box.addLayout(grid1)
  1226. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  1227. addtool_entry_lbl.setToolTip(
  1228. _("Diameter for the new tool")
  1229. )
  1230. hlay = QtWidgets.QHBoxLayout()
  1231. self.addtool_entry = FCEntry()
  1232. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1233. hlay.addWidget(self.addtool_entry)
  1234. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  1235. self.addtool_btn.setToolTip(
  1236. _("Add a new tool to the tool list\n"
  1237. "with the diameter specified above.")
  1238. )
  1239. self.addtool_btn.setFixedWidth(80)
  1240. hlay.addWidget(self.addtool_btn)
  1241. grid1.addWidget(addtool_entry_lbl, 0, 0)
  1242. grid1.addLayout(hlay, 0, 1)
  1243. grid2 = QtWidgets.QGridLayout()
  1244. self.tools_box.addLayout(grid2)
  1245. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  1246. self.deltool_btn.setToolTip(
  1247. _("Delete a tool in the tool list\n"
  1248. "by selecting a row in the tool table.")
  1249. )
  1250. grid2.addWidget(self.deltool_btn, 0, 1)
  1251. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1252. # this way I can hide/show the frame
  1253. self.resize_frame = QtWidgets.QFrame()
  1254. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  1255. self.tools_box.addWidget(self.resize_frame)
  1256. self.resize_box = QtWidgets.QVBoxLayout()
  1257. self.resize_box.setContentsMargins(0, 0, 0, 0)
  1258. self.resize_frame.setLayout(self.resize_box)
  1259. # ### Resize a drill ## ##
  1260. self.emptyresize_label = QtWidgets.QLabel('')
  1261. self.resize_box.addWidget(self.emptyresize_label)
  1262. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  1263. self.drillresize_label.setToolTip(
  1264. _("Resize a drill or a selection of drills.")
  1265. )
  1266. self.resize_box.addWidget(self.drillresize_label)
  1267. grid3 = QtWidgets.QGridLayout()
  1268. self.resize_box.addLayout(grid3)
  1269. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  1270. res_entry_lbl.setToolTip(
  1271. _("Diameter to resize to.")
  1272. )
  1273. grid3.addWidget(res_entry_lbl, 0, 0)
  1274. hlay2 = QtWidgets.QHBoxLayout()
  1275. self.resdrill_entry = LengthEntry()
  1276. hlay2.addWidget(self.resdrill_entry)
  1277. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  1278. self.resize_btn.setToolTip(
  1279. _("Resize drill(s)")
  1280. )
  1281. self.resize_btn.setFixedWidth(80)
  1282. hlay2.addWidget(self.resize_btn)
  1283. grid3.addLayout(hlay2, 0, 1)
  1284. self.resize_frame.hide()
  1285. # ####################################
  1286. # ### Add DRILL Array ################
  1287. # ####################################
  1288. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1289. # all the add drill array widgets
  1290. # this way I can hide/show the frame
  1291. self.array_frame = QtWidgets.QFrame()
  1292. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1293. self.tools_box.addWidget(self.array_frame)
  1294. self.array_box = QtWidgets.QVBoxLayout()
  1295. self.array_box.setContentsMargins(0, 0, 0, 0)
  1296. self.array_frame.setLayout(self.array_box)
  1297. self.emptyarray_label = QtWidgets.QLabel('')
  1298. self.array_box.addWidget(self.emptyarray_label)
  1299. self.drill_array_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  1300. self.drill_array_label.setToolTip(
  1301. _("Add an array of drills (linear or circular array)")
  1302. )
  1303. self.array_box.addWidget(self.drill_array_label)
  1304. self.array_type_combo = FCComboBox()
  1305. self.array_type_combo.setToolTip(
  1306. _("Select the type of drills array to create.\n"
  1307. "It can be Linear X(Y) or Circular")
  1308. )
  1309. self.array_type_combo.addItem(_("Linear"))
  1310. self.array_type_combo.addItem(_("Circular"))
  1311. self.array_box.addWidget(self.array_type_combo)
  1312. self.array_form = QtWidgets.QFormLayout()
  1313. self.array_box.addLayout(self.array_form)
  1314. # Set the number of drill holes in the drill array
  1315. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  1316. self.drill_array_size_label.setToolTip(_("Specify how many drills to be in the array."))
  1317. self.drill_array_size_label.setMinimumWidth(100)
  1318. self.drill_array_size_entry = LengthEntry()
  1319. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  1320. self.array_linear_frame = QtWidgets.QFrame()
  1321. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1322. self.array_box.addWidget(self.array_linear_frame)
  1323. self.linear_box = QtWidgets.QVBoxLayout()
  1324. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1325. self.array_linear_frame.setLayout(self.linear_box)
  1326. self.linear_form = QtWidgets.QFormLayout()
  1327. self.linear_box.addLayout(self.linear_form)
  1328. # Linear Drill Array direction
  1329. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  1330. self.drill_axis_label.setToolTip(
  1331. _("Direction on which the linear array is oriented:\n"
  1332. "- 'X' - horizontal axis \n"
  1333. "- 'Y' - vertical axis or \n"
  1334. "- 'Angle' - a custom angle for the array inclination")
  1335. )
  1336. self.drill_axis_label.setMinimumWidth(100)
  1337. self.drill_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1338. {'label': _('Y'), 'value': 'Y'},
  1339. {'label': _('Angle'), 'value': 'A'}])
  1340. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  1341. # Linear Drill Array pitch distance
  1342. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1343. self.drill_pitch_label.setToolTip(
  1344. _("Pitch = Distance between elements of the array.")
  1345. )
  1346. self.drill_pitch_label.setMinimumWidth(100)
  1347. self.drill_pitch_entry = LengthEntry()
  1348. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  1349. # Linear Drill Array angle
  1350. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1351. self.linear_angle_label.setToolTip(
  1352. _("Angle at which the linear array is placed.\n"
  1353. "The precision is of max 2 decimals.\n"
  1354. "Min value is: -359.99 degrees.\n"
  1355. "Max value is: 360.00 degrees.")
  1356. )
  1357. self.linear_angle_label.setMinimumWidth(100)
  1358. self.linear_angle_spinner = FCDoubleSpinner()
  1359. self.linear_angle_spinner.set_precision(2)
  1360. self.linear_angle_spinner.setSingleStep(1.0)
  1361. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1362. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1363. self.array_circular_frame = QtWidgets.QFrame()
  1364. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1365. self.array_box.addWidget(self.array_circular_frame)
  1366. self.circular_box = QtWidgets.QVBoxLayout()
  1367. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1368. self.array_circular_frame.setLayout(self.circular_box)
  1369. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  1370. self.drill_direction_label.setToolTip(_("Direction for circular array."
  1371. "Can be CW = clockwise or CCW = counter clockwise."))
  1372. self.drill_direction_label.setMinimumWidth(100)
  1373. self.circular_form = QtWidgets.QFormLayout()
  1374. self.circular_box.addLayout(self.circular_form)
  1375. self.drill_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1376. {'label': _('CCW'), 'value': 'CCW'}])
  1377. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  1378. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  1379. self.drill_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1380. self.drill_angle_label.setMinimumWidth(100)
  1381. self.drill_angle_entry = LengthEntry()
  1382. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  1383. self.array_circular_frame.hide()
  1384. self.linear_angle_spinner.hide()
  1385. self.linear_angle_label.hide()
  1386. self.array_frame.hide()
  1387. # ######################################################
  1388. # ##### ADDING SLOTS ###################################
  1389. # ######################################################
  1390. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1391. # all the add slot widgets
  1392. # this way I can hide/show the frame
  1393. self.slot_frame = QtWidgets.QFrame()
  1394. self.slot_frame.setContentsMargins(0, 0, 0, 0)
  1395. self.tools_box.addWidget(self.slot_frame)
  1396. self.slot_box = QtWidgets.QVBoxLayout()
  1397. self.slot_box.setContentsMargins(0, 0, 0, 0)
  1398. self.slot_frame.setLayout(self.slot_box)
  1399. self.emptyarray_label = QtWidgets.QLabel('')
  1400. self.slot_box.addWidget(self.emptyarray_label)
  1401. self.slot_label = QtWidgets.QLabel('<b>%s</b>' % _("Slot Parameters"))
  1402. self.slot_label.setToolTip(
  1403. _("Parameters for adding a slot (hole with oval shape)\n"
  1404. "either single or as an part of an array.")
  1405. )
  1406. self.slot_box.addWidget(self.slot_label)
  1407. self.slot_form = QtWidgets.QFormLayout()
  1408. self.slot_box.addLayout(self.slot_form)
  1409. # Slot length
  1410. self.slot_length_label = QtWidgets.QLabel(_('Length:'))
  1411. self.slot_length_label.setToolTip(
  1412. _("Length = The length of the slot.")
  1413. )
  1414. self.slot_length_label.setMinimumWidth(100)
  1415. self.slot_length_entry = LengthEntry()
  1416. self.slot_form.addRow(self.slot_length_label, self.slot_length_entry)
  1417. # Slot direction
  1418. self.slot_axis_label = QtWidgets.QLabel(_('Direction:'))
  1419. self.slot_axis_label.setToolTip(
  1420. _("Direction on which the slot is oriented:\n"
  1421. "- 'X' - horizontal axis \n"
  1422. "- 'Y' - vertical axis or \n"
  1423. "- 'Angle' - a custom angle for the slot inclination")
  1424. )
  1425. self.slot_axis_label.setMinimumWidth(100)
  1426. self.slot_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1427. {'label': _('Y'), 'value': 'Y'},
  1428. {'label': _('Angle'), 'value': 'A'}])
  1429. self.slot_form.addRow(self.slot_axis_label, self.slot_axis_radio)
  1430. # Slot custom angle
  1431. self.slot_angle_label = QtWidgets.QLabel(_('Angle:'))
  1432. self.slot_angle_label.setToolTip(
  1433. _("Angle at which the slot is placed.\n"
  1434. "The precision is of max 2 decimals.\n"
  1435. "Min value is: -359.99 degrees.\n"
  1436. "Max value is: 360.00 degrees.")
  1437. )
  1438. self.slot_angle_label.setMinimumWidth(100)
  1439. self.slot_angle_spinner = FCDoubleSpinner()
  1440. self.slot_angle_spinner.set_precision(2)
  1441. self.slot_angle_spinner.setWrapping(True)
  1442. self.slot_angle_spinner.setRange(-359.99, 360.00)
  1443. self.slot_angle_spinner.setSingleStep(1.0)
  1444. self.slot_form.addRow(self.slot_angle_label, self.slot_angle_spinner)
  1445. self.slot_frame.hide()
  1446. # ######################################################
  1447. # ##### ADDING SLOT ARRAY #############################
  1448. # ######################################################
  1449. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1450. # all the add slot widgets
  1451. # this way I can hide/show the frame
  1452. self.slot_array_frame = QtWidgets.QFrame()
  1453. self.slot_array_frame.setContentsMargins(0, 0, 0, 0)
  1454. self.tools_box.addWidget(self.slot_array_frame)
  1455. self.slot_array_box = QtWidgets.QVBoxLayout()
  1456. self.slot_array_box.setContentsMargins(0, 0, 0, 0)
  1457. self.slot_array_frame.setLayout(self.slot_array_box)
  1458. self.emptyarray_label = QtWidgets.QLabel('')
  1459. self.slot_array_box.addWidget(self.emptyarray_label)
  1460. self.slot_array_label = QtWidgets.QLabel('<b>%s</b>' % _("Slot Array Parameters"))
  1461. self.slot_array_label.setToolTip(
  1462. _("Parameters for the array of slots (linear or circular array)")
  1463. )
  1464. self.slot_array_box.addWidget(self.slot_array_label)
  1465. self.l_form = QtWidgets.QFormLayout()
  1466. self.slot_array_box.addLayout(self.l_form)
  1467. self.slot_array_type_combo = FCComboBox()
  1468. self.slot_array_type_combo.setToolTip(
  1469. _("Select the type of slot array to create.\n"
  1470. "It can be Linear X(Y) or Circular")
  1471. )
  1472. self.slot_array_type_combo.addItem(_("Linear"))
  1473. self.slot_array_type_combo.addItem(_("Circular"))
  1474. self.slot_array_box.addWidget(self.slot_array_type_combo)
  1475. self.slot_array_form = QtWidgets.QFormLayout()
  1476. self.slot_array_box.addLayout(self.slot_array_form)
  1477. # Set the number of slot holes in the slot array
  1478. self.slot_array_size_label = QtWidgets.QLabel(_('Nr of slots:'))
  1479. self.slot_array_size_label.setToolTip(_("Specify how many slots to be in the array."))
  1480. self.slot_array_size_label.setMinimumWidth(100)
  1481. self.slot_array_size_entry = LengthEntry()
  1482. self.slot_array_form.addRow(self.slot_array_size_label, self.slot_array_size_entry)
  1483. self.slot_array_linear_frame = QtWidgets.QFrame()
  1484. self.slot_array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1485. self.slot_array_box.addWidget(self.slot_array_linear_frame)
  1486. self.slot_array_linear_box = QtWidgets.QVBoxLayout()
  1487. self.slot_array_linear_box.setContentsMargins(0, 0, 0, 0)
  1488. self.slot_array_linear_frame.setLayout(self.slot_array_linear_box)
  1489. self.slot_array_linear_form = QtWidgets.QFormLayout()
  1490. self.slot_array_linear_box.addLayout(self.slot_array_linear_form)
  1491. # Linear Slot Array direction
  1492. self.slot_array_axis_label = QtWidgets.QLabel(_('Direction:'))
  1493. self.slot_array_axis_label.setToolTip(
  1494. _("Direction on which the linear array is oriented:\n"
  1495. "- 'X' - horizontal axis \n"
  1496. "- 'Y' - vertical axis or \n"
  1497. "- 'Angle' - a custom angle for the array inclination")
  1498. )
  1499. self.slot_array_axis_label.setMinimumWidth(100)
  1500. self.slot_array_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1501. {'label': _('Y'), 'value': 'Y'},
  1502. {'label': _('Angle'), 'value': 'A'}])
  1503. self.slot_array_linear_form.addRow(self.slot_array_axis_label, self.slot_array_axis_radio)
  1504. # Linear Slot Array pitch distance
  1505. self.slot_array_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1506. self.slot_array_pitch_label.setToolTip(
  1507. _("Pitch = Distance between elements of the array.")
  1508. )
  1509. self.slot_array_pitch_label.setMinimumWidth(100)
  1510. self.slot_array_pitch_entry = LengthEntry()
  1511. self.slot_array_linear_form.addRow(self.slot_array_pitch_label, self.slot_array_pitch_entry)
  1512. # Linear Slot Array angle
  1513. self.slot_array_linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1514. self.slot_array_linear_angle_label.setToolTip(
  1515. _("Angle at which the linear array is placed.\n"
  1516. "The precision is of max 2 decimals.\n"
  1517. "Min value is: -359.99 degrees.\n"
  1518. "Max value is: 360.00 degrees.")
  1519. )
  1520. self.slot_array_linear_angle_label.setMinimumWidth(100)
  1521. self.slot_array_linear_angle_spinner = FCDoubleSpinner()
  1522. self.slot_array_linear_angle_spinner.set_precision(2)
  1523. self.slot_array_linear_angle_spinner.setSingleStep(1.0)
  1524. self.slot_array_linear_angle_spinner.setRange(-359.99, 360.00)
  1525. self.slot_array_linear_form.addRow(self.slot_array_linear_angle_label, self.slot_array_linear_angle_spinner)
  1526. self.slot_array_circular_frame = QtWidgets.QFrame()
  1527. self.slot_array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1528. self.slot_array_box.addWidget(self.slot_array_circular_frame)
  1529. self.slot_array_circular_box = QtWidgets.QVBoxLayout()
  1530. self.slot_array_circular_box.setContentsMargins(0, 0, 0, 0)
  1531. self.slot_array_circular_frame.setLayout(self.slot_array_circular_box)
  1532. self.slot_array_direction_label = QtWidgets.QLabel(_('Direction:'))
  1533. self.slot_array_direction_label.setToolTip(_("Direction for circular array."
  1534. "Can be CW = clockwise or CCW = counter clockwise."))
  1535. self.slot_array_direction_label.setMinimumWidth(100)
  1536. self.slot_array_circular_form = QtWidgets.QFormLayout()
  1537. self.slot_array_circular_box.addLayout(self.slot_array_circular_form)
  1538. self.slot_array_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1539. {'label': _('CCW'), 'value': 'CCW'}])
  1540. self.slot_array_circular_form.addRow(self.slot_array_direction_label, self.slot_array_direction_radio)
  1541. self.slot_array_angle_label = QtWidgets.QLabel(_('Angle:'))
  1542. self.slot_array_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1543. self.slot_array_angle_label.setMinimumWidth(100)
  1544. self.slot_array_angle_entry = LengthEntry()
  1545. self.slot_array_circular_form.addRow(self.slot_array_angle_label, self.slot_array_angle_entry)
  1546. self.slot_array_linear_angle_spinner.hide()
  1547. self.slot_array_linear_angle_label.hide()
  1548. self.slot_array_frame.hide()
  1549. self.tools_box.addStretch()
  1550. # ## Toolbar events and properties
  1551. self.tools_exc = {
  1552. "drill_select": {"button": self.app.ui.select_drill_btn,
  1553. "constructor": FCDrillSelect},
  1554. "drill_add": {"button": self.app.ui.add_drill_btn,
  1555. "constructor": FCDrillAdd},
  1556. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  1557. "constructor": FCDrillArray},
  1558. "slot_add": {"button": self.app.ui.add_slot_btn,
  1559. "constructor": FCSlot},
  1560. "slot_array": {"button": self.app.ui.add_slot_array_btn,
  1561. "constructor": FCSlotArray},
  1562. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  1563. "constructor": FCDrillResize},
  1564. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  1565. "constructor": FCDrillCopy},
  1566. "drill_move": {"button": self.app.ui.move_drill_btn,
  1567. "constructor": FCDrillMove},
  1568. }
  1569. # ## Data
  1570. self.active_tool = None
  1571. self.in_action = False
  1572. self.storage_dict = {}
  1573. self.current_storage = []
  1574. # build the data from the Excellon point into a dictionary
  1575. # {tool_dia: [geometry_in_points]}
  1576. self.points_edit = {}
  1577. self.slot_points_edit = {}
  1578. self.sorted_diameters = []
  1579. self.new_drills = []
  1580. self.new_tools = {}
  1581. self.new_slots = []
  1582. self.new_tool_offset = {}
  1583. # dictionary to store the tool_row and diameters in Tool_table
  1584. # it will be updated everytime self.build_ui() is called
  1585. self.olddia_newdia = {}
  1586. self.tool2tooldia = {}
  1587. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1588. # is cleared but as a side effect also the selected tool is cleared
  1589. self.last_tool_selected = None
  1590. self.utility = []
  1591. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1592. self.launched_from_shortcuts = False
  1593. # this var will store the state of the toolbar before starting the editor
  1594. self.toolbar_old_state = False
  1595. if self.units == 'MM':
  1596. self.tolerance = float(self.app.defaults["global_tolerance"])
  1597. else:
  1598. self.tolerance = float(self.app.defaults["global_tolerance"]) / 20
  1599. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  1600. self.name_entry.returnPressed.connect(self.on_name_activate)
  1601. self.addtool_btn.clicked.connect(self.on_tool_add)
  1602. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  1603. self.deltool_btn.clicked.connect(self.on_tool_delete)
  1604. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1605. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1606. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1607. self.slot_array_type_combo.currentIndexChanged.connect(self.on_slot_array_type_combo)
  1608. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1609. self.slot_axis_radio.activated_custom.connect(self.on_slot_angle_radio)
  1610. self.slot_array_axis_radio.activated_custom.connect(self.on_slot_array_linear_angle_radio)
  1611. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  1612. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  1613. self.app.ui.exc_add_array_slot_menuitem.triggered.connect(self.exc_add_slot_array)
  1614. self.app.ui.exc_add_slot_menuitem.triggered.connect(self.exc_add_slot)
  1615. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  1616. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  1617. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  1618. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  1619. self.exc_obj = None
  1620. # VisPy Visuals
  1621. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1622. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1623. self.app.pool_recreated.connect(self.pool_recreated)
  1624. # Remove from scene
  1625. self.shapes.enabled = False
  1626. self.tool_shape.enabled = False
  1627. # ## List of selected shapes.
  1628. self.selected = []
  1629. self.move_timer = QtCore.QTimer()
  1630. self.move_timer.setSingleShot(True)
  1631. self.key = None # Currently pressed key
  1632. self.modifiers = None
  1633. self.x = None # Current mouse cursor pos
  1634. self.y = None
  1635. # Current snapped mouse pos
  1636. self.snap_x = None
  1637. self.snap_y = None
  1638. self.pos = None
  1639. self.complete = False
  1640. def make_callback(thetool):
  1641. def f():
  1642. self.on_tool_select(thetool)
  1643. return f
  1644. for tool in self.tools_exc:
  1645. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1646. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1647. self.options = {
  1648. "global_gridx": 0.1,
  1649. "global_gridy": 0.1,
  1650. "snap_max": 0.05,
  1651. "grid_snap": True,
  1652. "corner_snap": False,
  1653. "grid_gap_link": True
  1654. }
  1655. self.app.options_read_form()
  1656. for option in self.options:
  1657. if option in self.app.options:
  1658. self.options[option] = self.app.options[option]
  1659. self.rtree_exc_index = rtindex.Index()
  1660. # flag to show if the object was modified
  1661. self.is_modified = False
  1662. self.edited_obj_name = ""
  1663. # variable to store the total amount of drills per job
  1664. self.tot_drill_cnt = 0
  1665. self.tool_row = 0
  1666. # variable to store the total amount of slots per job
  1667. self.tot_slot_cnt = 0
  1668. self.tool_row_slots = 0
  1669. self.tool_row = 0
  1670. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1671. self.editor_active = False
  1672. def entry2option(option, entry):
  1673. self.options[option] = float(entry.text())
  1674. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1675. self.editor_active = False
  1676. log.debug("Initialization of the FlatCAM Excellon Editor is finished ...")
  1677. def pool_recreated(self, pool):
  1678. self.shapes.pool = pool
  1679. self.tool_shape.pool = pool
  1680. @staticmethod
  1681. def make_storage():
  1682. # ## Shape storage.
  1683. storage = FlatCAMRTreeStorage()
  1684. storage.get_points = DrawToolShape.get_pts
  1685. return storage
  1686. def set_ui(self):
  1687. # updated units
  1688. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1689. self.olddia_newdia.clear()
  1690. self.tool2tooldia.clear()
  1691. # build the self.points_edit dict {dimaters: [point_list]}
  1692. for drill in self.exc_obj.drills:
  1693. if drill['tool'] in self.exc_obj.tools:
  1694. if self.units == 'IN':
  1695. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1696. else:
  1697. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1698. try:
  1699. self.points_edit[tool_dia].append(drill['point'])
  1700. except KeyError:
  1701. self.points_edit[tool_dia] = [drill['point']]
  1702. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1703. for slot in self.exc_obj.slots:
  1704. if slot['tool'] in self.exc_obj.tools:
  1705. if self.units == 'IN':
  1706. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1707. else:
  1708. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1709. try:
  1710. self.slot_points_edit[tool_dia].append({
  1711. "start": slot["start"],
  1712. "stop": slot["stop"]
  1713. })
  1714. except KeyError:
  1715. self.slot_points_edit[tool_dia] = [{
  1716. "start": slot["start"],
  1717. "stop": slot["stop"]
  1718. }]
  1719. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1720. for key in self.points_edit:
  1721. self.olddia_newdia[key] = key
  1722. for key in self.slot_points_edit:
  1723. if key not in self.olddia_newdia:
  1724. self.olddia_newdia[key] = key
  1725. sort_temp = []
  1726. for diam in self.olddia_newdia:
  1727. sort_temp.append(float(diam))
  1728. self.sorted_diameters = sorted(sort_temp)
  1729. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1730. if self.exc_obj.diameterless is False:
  1731. for i in range(len(self.sorted_diameters)):
  1732. tt_dia = self.sorted_diameters[i]
  1733. self.tool2tooldia[i + 1] = tt_dia
  1734. else:
  1735. # the Excellon object has diameters that are bogus information, added by the application because the
  1736. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1737. # but use the real order found in the exc_obj.tools
  1738. for k, v in self.exc_obj.tools.items():
  1739. if self.units == 'IN':
  1740. tool_dia = float('%.4f' % v['C'])
  1741. else:
  1742. tool_dia = float('%.2f' % v['C'])
  1743. self.tool2tooldia[int(k)] = tool_dia
  1744. # Init GUI
  1745. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1746. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1747. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1748. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1749. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1750. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1751. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1752. self.slot_length_entry.set_value(float(self.app.defaults['excellon_editor_slot_length']))
  1753. self.slot_axis_radio.set_value(self.app.defaults['excellon_editor_slot_direction'])
  1754. self.slot_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_angle']))
  1755. self.slot_array_size_entry.set_value(int(self.app.defaults['excellon_editor_slot_array_size']))
  1756. self.slot_array_axis_radio.set_value(self.app.defaults['excellon_editor_slot_lin_dir'])
  1757. self.slot_array_pitch_entry.set_value(float(self.app.defaults['excellon_editor_slot_lin_pitch']))
  1758. self.slot_array_linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_lin_angle']))
  1759. self.slot_array_direction_radio.set_value(self.app.defaults['excellon_editor_slot_circ_dir'])
  1760. self.slot_array_angle_entry.set_value(float(self.app.defaults['excellon_editor_slot_circ_angle']))
  1761. self.slot_array_circular_frame.hide()
  1762. self.slot_array_linear_frame.show()
  1763. def build_ui(self, first_run=None):
  1764. try:
  1765. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1766. self.tools_table_exc.itemChanged.disconnect()
  1767. except (TypeError, AttributeError):
  1768. pass
  1769. try:
  1770. self.tools_table_exc.cellPressed.disconnect()
  1771. except (TypeError, AttributeError):
  1772. pass
  1773. # updated units
  1774. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1775. # make a new name for the new Excellon object (the one with edited content)
  1776. self.edited_obj_name = self.exc_obj.options['name']
  1777. self.name_entry.set_value(self.edited_obj_name)
  1778. sort_temp = []
  1779. for diam in self.olddia_newdia:
  1780. sort_temp.append(float(diam))
  1781. self.sorted_diameters = sorted(sort_temp)
  1782. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1783. n = len(self.sorted_diameters)
  1784. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1785. self.tools_table_exc.setRowCount(n + 2)
  1786. self.tot_drill_cnt = 0
  1787. self.tot_slot_cnt = 0
  1788. self.tool_row = 0
  1789. # this variable will serve as the real tool_number
  1790. tool_id = 0
  1791. for tool_no in self.sorted_diameters:
  1792. tool_id += 1
  1793. drill_cnt = 0 # variable to store the nr of drills per tool
  1794. slot_cnt = 0 # variable to store the nr of slots per tool
  1795. # Find no of drills for the current tool
  1796. for tool_dia in self.points_edit:
  1797. if float(tool_dia) == tool_no:
  1798. drill_cnt = len(self.points_edit[tool_dia])
  1799. self.tot_drill_cnt += drill_cnt
  1800. try:
  1801. # Find no of slots for the current tool
  1802. for slot in self.slots:
  1803. if slot['tool'] == tool_no:
  1804. slot_cnt += 1
  1805. self.tot_slot_cnt += slot_cnt
  1806. except AttributeError:
  1807. # log.debug("No slots in the Excellon file")
  1808. # Find no of slots for the current tool
  1809. for tool_dia in self.slot_points_edit:
  1810. if float(tool_dia) == tool_no:
  1811. slot_cnt = len(self.slot_points_edit[tool_dia])
  1812. self.tot_slot_cnt += slot_cnt
  1813. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1814. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1815. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1816. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1817. # There are no drill bits in MM with more than 3 decimals diameter
  1818. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1819. if self.units == 'MM':
  1820. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1821. else:
  1822. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1823. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1824. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1825. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1826. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1827. if slot_cnt > 0:
  1828. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1829. else:
  1830. slot_count = QtWidgets.QTableWidgetItem('')
  1831. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1832. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1833. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1834. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1835. if first_run is True:
  1836. # set now the last tool selected
  1837. self.last_tool_selected = int(tool_id)
  1838. self.tool_row += 1
  1839. # make the diameter column editable
  1840. for row in range(self.tool_row):
  1841. self.tools_table_exc.item(row, 1).setFlags(
  1842. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1843. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1844. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1845. # add a last row with the Total number of drills
  1846. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1847. # it will have to have the foreground color (font color) white
  1848. empty = QtWidgets.QTableWidgetItem('9998')
  1849. empty.setForeground(QtGui.QColor(255, 255, 255))
  1850. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1851. empty_b = QtWidgets.QTableWidgetItem('')
  1852. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1853. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1854. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1855. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1856. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1857. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1858. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1859. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1860. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1861. font = QtGui.QFont()
  1862. font.setBold(True)
  1863. font.setWeight(75)
  1864. for k in [1, 2]:
  1865. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1866. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1867. self.tool_row += 1
  1868. # add a last row with the Total number of slots
  1869. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1870. # it will have to have the foreground color (font color) white
  1871. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1872. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1873. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1874. empty_3 = QtWidgets.QTableWidgetItem('')
  1875. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1876. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1877. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1878. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1879. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1880. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1881. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1882. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1883. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1884. for kl in [1, 2, 3]:
  1885. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1886. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1887. # all the tools are selected by default
  1888. self.tools_table_exc.selectColumn(0)
  1889. #
  1890. self.tools_table_exc.resizeColumnsToContents()
  1891. self.tools_table_exc.resizeRowsToContents()
  1892. vertical_header = self.tools_table_exc.verticalHeader()
  1893. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1894. vertical_header.hide()
  1895. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1896. horizontal_header = self.tools_table_exc.horizontalHeader()
  1897. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1898. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1899. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1900. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1901. # horizontal_header.setStretchLastSection(True)
  1902. # self.tools_table_exc.setSortingEnabled(True)
  1903. # sort by tool diameter
  1904. self.tools_table_exc.sortItems(1)
  1905. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1906. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1907. # use them
  1908. self.tool2tooldia.clear()
  1909. for row in range(self.tools_table_exc.rowCount() - 2):
  1910. tool = int(self.tools_table_exc.item(row, 0).text())
  1911. diameter = float(self.tools_table_exc.item(row, 1).text())
  1912. self.tool2tooldia[tool] = diameter
  1913. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1914. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1915. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1916. self.tools_table_exc.clearSelection()
  1917. # Remove anything else in the GUI Selected Tab
  1918. self.app.ui.selected_scroll_area.takeWidget()
  1919. # Put ourself in the GUI Selected Tab
  1920. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1921. # Switch notebook to Selected page
  1922. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1923. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1924. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1925. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1926. def on_tool_add(self, tooldia=None):
  1927. self.is_modified = True
  1928. if tooldia:
  1929. tool_dia = tooldia
  1930. else:
  1931. try:
  1932. tool_dia = float(self.addtool_entry.get_value())
  1933. except ValueError:
  1934. # try to convert comma to decimal point. if it's still not working error message and return
  1935. try:
  1936. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1937. except ValueError:
  1938. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1939. "use a number.")
  1940. )
  1941. return
  1942. if tool_dia not in self.olddia_newdia:
  1943. storage_elem = FlatCAMGeoEditor.make_storage()
  1944. self.storage_dict[tool_dia] = storage_elem
  1945. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1946. # each time a tool diameter is edited or added
  1947. self.olddia_newdia[tool_dia] = tool_dia
  1948. else:
  1949. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1950. "Save and reedit Excellon if you need to add this tool. ")
  1951. )
  1952. return
  1953. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1954. # we add a new entry in the tool2tooldia dict
  1955. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1956. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia),
  1957. units=str(self.units)))
  1958. self.build_ui()
  1959. # make a quick sort through the tool2tooldia dict so we find which row to select
  1960. row_to_be_selected = None
  1961. for key in sorted(self.tool2tooldia):
  1962. if self.tool2tooldia[key] == tool_dia:
  1963. row_to_be_selected = int(key) - 1
  1964. self.last_tool_selected = int(key)
  1965. break
  1966. self.tools_table_exc.selectRow(row_to_be_selected)
  1967. def on_tool_delete(self, dia=None):
  1968. self.is_modified = True
  1969. deleted_tool_dia_list = []
  1970. try:
  1971. if dia is None or dia is False:
  1972. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1973. for index in self.tools_table_exc.selectionModel().selectedRows():
  1974. row = index.row()
  1975. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1976. else:
  1977. if isinstance(dia, list):
  1978. for dd in dia:
  1979. deleted_tool_dia_list.append(float('%.4f' % dd))
  1980. else:
  1981. deleted_tool_dia_list.append(float('%.4f' % dia))
  1982. except Exception as e:
  1983. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1984. return
  1985. for deleted_tool_dia in deleted_tool_dia_list:
  1986. # delete de tool offset
  1987. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1988. # delete the storage used for that tool
  1989. storage_elem = FlatCAMGeoEditor.make_storage()
  1990. self.storage_dict[deleted_tool_dia] = storage_elem
  1991. self.storage_dict.pop(deleted_tool_dia, None)
  1992. # I've added this flag_del variable because dictionary don't like
  1993. # having keys deleted while iterating through them
  1994. flag_del = []
  1995. # self.points_edit.pop(deleted_tool_dia, None)
  1996. for deleted_tool in self.tool2tooldia:
  1997. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1998. flag_del.append(deleted_tool)
  1999. if flag_del:
  2000. for tool_to_be_deleted in flag_del:
  2001. # delete the tool
  2002. self.tool2tooldia.pop(tool_to_be_deleted, None)
  2003. # delete also the drills from points_edit dict just in case we add the tool again,
  2004. # we don't want to show the number of drills from before was deleter
  2005. self.points_edit[deleted_tool_dia] = []
  2006. self.olddia_newdia.pop(deleted_tool_dia, None)
  2007. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(
  2008. del_dia=str(deleted_tool_dia),
  2009. units=str(self.units)))
  2010. self.replot()
  2011. # self.app.inform.emit("Could not delete selected tool")
  2012. self.build_ui()
  2013. def on_tool_edit(self, item_changed):
  2014. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2015. try:
  2016. self.tools_table_exc.itemChanged.disconnect()
  2017. except TypeError:
  2018. pass
  2019. try:
  2020. self.tools_table_exc.cellPressed.disconnect()
  2021. except TypeError:
  2022. pass
  2023. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  2024. self.is_modified = True
  2025. new_dia = None
  2026. if self.tools_table_exc.currentItem() is not None:
  2027. try:
  2028. new_dia = float(self.tools_table_exc.currentItem().text())
  2029. except ValueError as e:
  2030. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  2031. self.tools_table_exc.setCurrentItem(None)
  2032. return
  2033. row_of_item_changed = self.tools_table_exc.currentRow()
  2034. # rows start with 0, tools start with 1 so we adjust the value by 1
  2035. key_in_tool2tooldia = row_of_item_changed + 1
  2036. old_dia = self.tool2tooldia[key_in_tool2tooldia]
  2037. # SOURCE storage
  2038. source_storage = self.storage_dict[old_dia]
  2039. # DESTINATION storage
  2040. # tool diameter is not used so we create a new tool with the desired diameter
  2041. if new_dia not in self.olddia_newdia:
  2042. destination_storage = FlatCAMGeoEditor.make_storage()
  2043. self.storage_dict[new_dia] = destination_storage
  2044. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2045. # each time a tool diameter is edited or added
  2046. self.olddia_newdia[new_dia] = new_dia
  2047. else:
  2048. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  2049. destination_storage = self.storage_dict[new_dia]
  2050. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2051. # we add a new entry in the tool2tooldia dict
  2052. self.tool2tooldia[len(self.olddia_newdia)] = new_dia
  2053. # CHANGE the elements geometry according to the new diameter
  2054. factor = new_dia / old_dia
  2055. new_geo = Polygon()
  2056. for shape_exc in source_storage.get_objects():
  2057. geo_list = []
  2058. if isinstance(shape_exc.geo, MultiLineString):
  2059. for subgeo in shape_exc.geo:
  2060. geo_list.append(affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center'))
  2061. new_geo = MultiLineString(geo_list)
  2062. elif isinstance(shape_exc.geo, Polygon):
  2063. # I don't have any info regarding the angle of the slot geometry, nor how thick it is or
  2064. # how long it is given the angle. So I will have to make an approximation because
  2065. # we need to conserve the slot length, we only resize the diameter for the tool
  2066. # Therefore scaling won't work and buffering will not work either.
  2067. # First we get the Linestring that is one that the original slot is built around with the
  2068. # tool having the diameter sel_dia
  2069. poly = shape_exc.geo
  2070. xmin, ymin, xmax, ymax = poly.bounds
  2071. # a line that is certain to be bigger than our slot because it's the diagonal
  2072. # of it's bounding box
  2073. poly_diagonal = LineString([(xmin, ymin), (xmax, ymax)])
  2074. poly_centroid = poly.centroid
  2075. # center of the slot geometry
  2076. poly_center = (poly_centroid.x, poly_centroid.y)
  2077. # make a list of intersections with the rotated line
  2078. list_of_cuttings = []
  2079. for angle in range(0, 359, 1):
  2080. rot_poly_diagonal = affinity.rotate(poly_diagonal, angle=angle, origin=poly_center)
  2081. cut_line = rot_poly_diagonal.intersection(poly)
  2082. cut_line_len = cut_line.length
  2083. list_of_cuttings.append(
  2084. (cut_line_len, cut_line)
  2085. )
  2086. # find the cut_line with the maximum length which is the LineString for which the start
  2087. # and stop point are the start and stop point of the slot as in the Gerber file
  2088. cut_line_with_max_length = max(list_of_cuttings, key=lambda i: i[0])[1]
  2089. # find the coordinates of this line
  2090. cut_line_with_max_length_coords = list(cut_line_with_max_length.coords)
  2091. # extract the first and last point of the line and build some buffered polygon circles
  2092. # around them
  2093. start_pt = Point(cut_line_with_max_length_coords[0])
  2094. stop_pt = Point(cut_line_with_max_length_coords[1])
  2095. start_cut_geo = start_pt.buffer(new_dia / 2)
  2096. stop_cut_geo = stop_pt.buffer(new_dia / 2)
  2097. # and we cut the above circle polygons from our line and get in this way a line around
  2098. # which we can build the new slot by buffering with the new tool diameter
  2099. new_line = cut_line_with_max_length.difference(start_cut_geo)
  2100. new_line = new_line.difference(stop_cut_geo)
  2101. # create the geometry for the resized slot by buffering with half of the
  2102. # new diameter value: new_dia
  2103. new_geo = new_line.buffer(new_dia / 2)
  2104. try:
  2105. self.points_edit.pop(old_dia, None)
  2106. except KeyError:
  2107. pass
  2108. try:
  2109. self.slot_points_edit.pop(old_dia, None)
  2110. except KeyError:
  2111. pass
  2112. # add bogus drill/slots points (for total count of drills/slots)
  2113. # for drills
  2114. if isinstance(shape_exc.geo, MultiLineString):
  2115. if new_dia not in self.points_edit:
  2116. self.points_edit[new_dia] = [(0, 0)]
  2117. else:
  2118. self.points_edit[new_dia].append((0, 0))
  2119. # for slots
  2120. if isinstance(shape_exc.geo, Polygon):
  2121. if new_dia not in self.slot_points_edit:
  2122. self.slot_points_edit[new_dia] = [(0, 0)]
  2123. else:
  2124. self.slot_points_edit[new_dia].append((0, 0))
  2125. self.add_exc_shape(shape=DrawToolShape(new_geo), storage=destination_storage)
  2126. # update the UI and the CANVAS
  2127. self.build_ui()
  2128. self.replot()
  2129. # delete the old tool
  2130. self.on_tool_delete(dia=old_dia)
  2131. # we reactivate the signals after the after the tool editing
  2132. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2133. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2134. self.app.inform.emit(_("[success] Done. Tool edit completed."))
  2135. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  2136. def on_name_activate(self):
  2137. self.edited_obj_name = self.name_entry.get_value()
  2138. def activate(self):
  2139. # adjust the status of the menu entries related to the editor
  2140. self.app.ui.menueditedit.setDisabled(True)
  2141. self.app.ui.menueditok.setDisabled(False)
  2142. # adjust the visibility of some of the canvas context menu
  2143. self.app.ui.popmenu_edit.setVisible(False)
  2144. self.app.ui.popmenu_save.setVisible(True)
  2145. self.connect_canvas_event_handlers()
  2146. # initialize working objects
  2147. self.storage_dict = {}
  2148. self.current_storage = []
  2149. self.points_edit = {}
  2150. self.sorted_diameters = []
  2151. self.new_drills = []
  2152. self.new_tools = {}
  2153. self.new_slots = []
  2154. self.new_tool_offset = {}
  2155. self.olddia_newdia = {}
  2156. self.shapes.enabled = True
  2157. self.tool_shape.enabled = True
  2158. # self.app.app_cursor.enabled = True
  2159. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2160. self.app.ui.corner_snap_btn.setEnabled(True)
  2161. self.app.ui.snap_magnet.setVisible(True)
  2162. self.app.ui.corner_snap_btn.setVisible(True)
  2163. self.app.ui.exc_editor_menu.setDisabled(False)
  2164. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  2165. self.app.ui.update_obj_btn.setEnabled(True)
  2166. self.app.ui.e_editor_cmenu.setEnabled(True)
  2167. self.app.ui.exc_edit_toolbar.setDisabled(False)
  2168. self.app.ui.exc_edit_toolbar.setVisible(True)
  2169. # self.app.ui.snap_toolbar.setDisabled(False)
  2170. # start with GRID toolbar activated
  2171. if self.app.ui.grid_snap_btn.isChecked() is False:
  2172. self.app.ui.grid_snap_btn.trigger()
  2173. self.app.ui.popmenu_disable.setVisible(False)
  2174. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2175. self.app.ui.popmenu_properties.setVisible(False)
  2176. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  2177. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2178. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2179. # Tell the App that the editor is active
  2180. self.editor_active = True
  2181. # show the UI
  2182. self.drills_frame.show()
  2183. def deactivate(self):
  2184. try:
  2185. QtGui.QGuiApplication.restoreOverrideCursor()
  2186. except Exception as e:
  2187. pass
  2188. # adjust the status of the menu entries related to the editor
  2189. self.app.ui.menueditedit.setDisabled(False)
  2190. self.app.ui.menueditok.setDisabled(True)
  2191. # adjust the visibility of some of the canvas context menu
  2192. self.app.ui.popmenu_edit.setVisible(True)
  2193. self.app.ui.popmenu_save.setVisible(False)
  2194. self.disconnect_canvas_event_handlers()
  2195. self.clear()
  2196. self.app.ui.exc_edit_toolbar.setDisabled(True)
  2197. settings = QSettings("Open Source", "FlatCAM")
  2198. if settings.contains("layout"):
  2199. layout = settings.value('layout', type=str)
  2200. if layout == 'standard':
  2201. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2202. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2203. self.app.ui.corner_snap_btn.setEnabled(False)
  2204. self.app.ui.snap_magnet.setVisible(False)
  2205. self.app.ui.corner_snap_btn.setVisible(False)
  2206. elif layout == 'compact':
  2207. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2208. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2209. self.app.ui.corner_snap_btn.setEnabled(False)
  2210. self.app.ui.snap_magnet.setVisible(True)
  2211. self.app.ui.corner_snap_btn.setVisible(True)
  2212. else:
  2213. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2214. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2215. self.app.ui.corner_snap_btn.setEnabled(False)
  2216. self.app.ui.snap_magnet.setVisible(False)
  2217. self.app.ui.corner_snap_btn.setVisible(False)
  2218. # set the Editor Toolbar visibility to what was before entering in the Editor
  2219. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2220. else self.app.ui.exc_edit_toolbar.setVisible(True)
  2221. # Disable visuals
  2222. self.shapes.enabled = False
  2223. self.tool_shape.enabled = False
  2224. # self.app.app_cursor.enabled = False
  2225. # Tell the app that the editor is no longer active
  2226. self.editor_active = False
  2227. self.app.ui.exc_editor_menu.setDisabled(True)
  2228. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  2229. self.app.ui.update_obj_btn.setEnabled(False)
  2230. self.app.ui.popmenu_disable.setVisible(True)
  2231. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2232. self.app.ui.popmenu_properties.setVisible(True)
  2233. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2234. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2235. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2236. # Show original geometry
  2237. if self.exc_obj:
  2238. self.exc_obj.visible = True
  2239. # hide the UI
  2240. self.drills_frame.hide()
  2241. def connect_canvas_event_handlers(self):
  2242. # ## Canvas events
  2243. # first connect to new, then disconnect the old handlers
  2244. # don't ask why but if there is nothing connected I've seen issues
  2245. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2246. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2247. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  2248. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2249. # but those from FlatCAMGeoEditor
  2250. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2251. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2252. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2253. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2254. self.app.collection.view.clicked.disconnect()
  2255. self.app.ui.popmenu_copy.triggered.disconnect()
  2256. self.app.ui.popmenu_delete.triggered.disconnect()
  2257. self.app.ui.popmenu_move.triggered.disconnect()
  2258. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  2259. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2260. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  2261. # Excellon Editor
  2262. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  2263. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  2264. def disconnect_canvas_event_handlers(self):
  2265. # we restore the key and mouse control to FlatCAMApp method
  2266. # first connect to new, then disconnect the old handlers
  2267. # don't ask why but if there is nothing connected I've seen issues
  2268. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2269. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2270. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2271. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2272. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2273. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2274. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2275. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  2276. try:
  2277. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  2278. except (TypeError, AttributeError):
  2279. pass
  2280. try:
  2281. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2282. except (TypeError, AttributeError):
  2283. pass
  2284. try:
  2285. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  2286. except (TypeError, AttributeError):
  2287. pass
  2288. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2289. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2290. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2291. # Excellon Editor
  2292. try:
  2293. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2294. except (TypeError, AttributeError):
  2295. pass
  2296. try:
  2297. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2298. except (TypeError, AttributeError):
  2299. pass
  2300. def clear(self):
  2301. self.active_tool = None
  2302. # self.shape_buffer = []
  2303. self.selected = []
  2304. self.points_edit = {}
  2305. self.new_tools = {}
  2306. self.new_drills = []
  2307. # self.storage_dict = {}
  2308. self.shapes.clear(update=True)
  2309. self.tool_shape.clear(update=True)
  2310. # self.storage = FlatCAMExcEditor.make_storage()
  2311. self.replot()
  2312. def edit_fcexcellon(self, exc_obj):
  2313. """
  2314. Imports the geometry from the given FlatCAM Excellon object
  2315. into the editor.
  2316. :param exc_obj: FlatCAMExcellon object
  2317. :return: None
  2318. """
  2319. assert isinstance(exc_obj, Excellon), \
  2320. "Expected an Excellon Object, got %s" % type(exc_obj)
  2321. self.deactivate()
  2322. self.activate()
  2323. # Hide original geometry
  2324. self.exc_obj = exc_obj
  2325. exc_obj.visible = False
  2326. self.points_edit = {}
  2327. self.slot_points_edit = {}
  2328. # Set selection tolerance
  2329. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2330. self.select_tool("drill_select")
  2331. self.set_ui()
  2332. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2333. self.build_ui(first_run=True)
  2334. # we activate this after the initial build as we don't need to see the tool been populated
  2335. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2336. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2337. # and then add it to the storage elements (each storage elements is a member of a list
  2338. for tool_dia in self.points_edit:
  2339. storage_elem = FlatCAMGeoEditor.make_storage()
  2340. for point in self.points_edit[tool_dia]:
  2341. # make a '+' sign, the line length is the tool diameter
  2342. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2343. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2344. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2345. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2346. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2347. if shape_geo is not None:
  2348. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2349. self.storage_dict[tool_dia] = storage_elem
  2350. # slots
  2351. for tool_dia in self.slot_points_edit:
  2352. buf_value = float(tool_dia) / 2
  2353. for elem_dict in self.slot_points_edit[tool_dia]:
  2354. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2355. shape_geo = line_geo.buffer(buf_value)
  2356. if tool_dia not in self.storage_dict:
  2357. storage_elem = FlatCAMGeoEditor.make_storage()
  2358. self.storage_dict[tool_dia] = storage_elem
  2359. if shape_geo is not None:
  2360. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2361. self.replot()
  2362. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2363. if not self.tool2tooldia:
  2364. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2365. def update_fcexcellon(self, exc_obj):
  2366. """
  2367. Create a new Excellon object that contain the edited content of the source Excellon object
  2368. :param exc_obj: FlatCAMExcellon
  2369. :return: None
  2370. """
  2371. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2372. # the values of this dict are coordinates of the holes (drills)
  2373. edited_points = {}
  2374. """
  2375. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2376. - the dict element of the list has the structure
  2377. ================ ====================================
  2378. Key Value
  2379. ================ ====================================
  2380. start (Shapely.Point) Start point of the slot
  2381. stop (Shapely.Point) Stop point of the slot
  2382. ================ ====================================
  2383. """
  2384. edited_slot_points = {}
  2385. for storage_tooldia in self.storage_dict:
  2386. for x in self.storage_dict[storage_tooldia].get_objects():
  2387. if isinstance(x.geo, MultiLineString):
  2388. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2389. # each MultiLineString is made out of Linestrings
  2390. # select first Linestring object in the current MultiLineString
  2391. first_linestring = x.geo[0]
  2392. # get it's coordinates
  2393. first_linestring_coords = first_linestring.coords
  2394. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2395. y_coord = first_linestring_coords[0][1]
  2396. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2397. # edited_points dictionary
  2398. point = (x_coord, y_coord)
  2399. if storage_tooldia not in edited_points:
  2400. edited_points[storage_tooldia] = [point]
  2401. else:
  2402. edited_points[storage_tooldia].append(point)
  2403. elif isinstance(x.geo, Polygon):
  2404. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2405. # edited_points dictionary
  2406. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2407. # diameter
  2408. radius = float(storage_tooldia) / 2
  2409. radius = radius - 0.0000001
  2410. poly = x.geo
  2411. poly = poly.buffer(-radius)
  2412. xmin, ymin, xmax, ymax = poly.bounds
  2413. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2414. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2415. if line_one < line_two:
  2416. point_elem = {
  2417. "start": (xmin, ymax),
  2418. "stop": (xmax, ymin)
  2419. }
  2420. else:
  2421. point_elem = {
  2422. "start": (xmin, ymin),
  2423. "stop": (xmax, ymax)
  2424. }
  2425. if storage_tooldia not in edited_slot_points:
  2426. edited_slot_points[storage_tooldia] = [point_elem]
  2427. else:
  2428. edited_slot_points[storage_tooldia].append(point_elem)
  2429. # recreate the drills and tools to be added to the new Excellon edited object
  2430. # first, we look in the tool table if one of the tool diameters was changed then
  2431. # append that a tuple formed by (old_dia, edited_dia) to a list
  2432. changed_key = set()
  2433. for initial_dia in self.olddia_newdia:
  2434. edited_dia = self.olddia_newdia[initial_dia]
  2435. if edited_dia != initial_dia:
  2436. # for drills
  2437. for old_dia in edited_points:
  2438. if old_dia == initial_dia:
  2439. changed_key.add((old_dia, edited_dia))
  2440. # for slots
  2441. for old_dia in edited_slot_points:
  2442. if old_dia == initial_dia:
  2443. changed_key.add((old_dia, edited_dia))
  2444. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2445. # (and we have to add it)
  2446. # because in case we have drill points it will have to be already added in edited_points
  2447. # if initial_dia not in edited_points.keys():
  2448. # edited_points[initial_dia] = []
  2449. for el in changed_key:
  2450. edited_points[el[1]] = edited_points.pop(el[0])
  2451. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2452. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2453. # ordered_edited_points is a ordered list of tuples;
  2454. # element[0] of the tuple is the diameter and
  2455. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2456. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2457. current_tool = 0
  2458. for tool_dia in ordered_edited_points:
  2459. current_tool += 1
  2460. # create the self.tools for the new Excellon object (the one with edited content)
  2461. name = str(current_tool)
  2462. spec = {"C": float(tool_dia[0])}
  2463. self.new_tools[name] = spec
  2464. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2465. self.new_tools[name]['solid_geometry'] = []
  2466. # create the self.drills for the new Excellon object (the one with edited content)
  2467. for point in tool_dia[1]:
  2468. self.new_drills.append(
  2469. {
  2470. 'point': Point(point),
  2471. 'tool': str(current_tool)
  2472. }
  2473. )
  2474. # repopulate the 'solid_geometry' for each tool
  2475. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2476. self.new_tools[name]['solid_geometry'].append(poly)
  2477. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2478. for tool_dia in ordered_edited_slot_points:
  2479. tool_exist_flag = False
  2480. for tool in self.new_tools:
  2481. if tool_dia[0] == self.new_tools[tool]["C"]:
  2482. current_tool = tool
  2483. tool_exist_flag = True
  2484. break
  2485. if tool_exist_flag is False:
  2486. current_tool += 1
  2487. # create the self.tools for the new Excellon object (the one with edited content)
  2488. name = str(current_tool)
  2489. spec = {"C": float(tool_dia[0])}
  2490. self.new_tools[name] = spec
  2491. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2492. self.new_tools[name]['solid_geometry'] = []
  2493. # create the self.slots for the new Excellon object (the one with edited content)
  2494. for coord_dict in tool_dia[1]:
  2495. self.new_slots.append(
  2496. {
  2497. 'start': Point(coord_dict['start']),
  2498. 'stop': Point(coord_dict['stop']),
  2499. 'tool': str(current_tool)
  2500. }
  2501. )
  2502. # repopulate the 'solid_geometry' for each tool
  2503. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2504. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2505. )
  2506. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2507. if self.is_modified is True:
  2508. if "_edit" in self.edited_obj_name:
  2509. try:
  2510. idd = int(self.edited_obj_name[-1]) + 1
  2511. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2512. except ValueError:
  2513. self.edited_obj_name += "_1"
  2514. else:
  2515. self.edited_obj_name += "_edit"
  2516. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2517. 'params': [self.edited_obj_name]})
  2518. self.new_tool_offset = self.exc_obj.tool_offset
  2519. # reset the tool table
  2520. self.tools_table_exc.clear()
  2521. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2522. self.last_tool_selected = None
  2523. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2524. self.app.collection.set_active(self.exc_obj.options['name'])
  2525. self.app.collection.delete_active()
  2526. # restore GUI to the Selected TAB
  2527. # Remove anything else in the GUI
  2528. self.app.ui.tool_scroll_area.takeWidget()
  2529. # Switch notebook to Selected page
  2530. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2531. def update_options(self, obj):
  2532. try:
  2533. if not obj.options:
  2534. obj.options = {}
  2535. obj.options['xmin'] = 0
  2536. obj.options['ymin'] = 0
  2537. obj.options['xmax'] = 0
  2538. obj.options['ymax'] = 0
  2539. return True
  2540. else:
  2541. return False
  2542. except AttributeError:
  2543. obj.options = {}
  2544. return True
  2545. def new_edited_excellon(self, outname):
  2546. """
  2547. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2548. :param outname: Name of the resulting object. None causes the
  2549. name to be that of the file.
  2550. :type outname: str
  2551. :return: None
  2552. """
  2553. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2554. self.exc_obj.options['name'])
  2555. # How the object should be initialized
  2556. def obj_init(excellon_obj, app_obj):
  2557. # self.progress.emit(20)
  2558. excellon_obj.drills = self.new_drills
  2559. excellon_obj.tools = self.new_tools
  2560. excellon_obj.slots = self.new_slots
  2561. excellon_obj.tool_offset = self.new_tool_offset
  2562. excellon_obj.options['name'] = outname
  2563. try:
  2564. excellon_obj.create_geometry()
  2565. except KeyError:
  2566. self.app.inform.emit(
  2567. _("[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  2568. )
  2569. except:
  2570. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2571. msg += traceback.format_exc()
  2572. app_obj.inform.emit(msg)
  2573. raise
  2574. # raise
  2575. with self.app.proc_container.new(_("Creating Excellon.")):
  2576. try:
  2577. self.app.new_object("excellon", outname, obj_init)
  2578. except Exception as e:
  2579. log.error("Error on object creation: %s" % str(e))
  2580. self.app.progress.emit(100)
  2581. return
  2582. self.app.inform.emit(_("[success] Excellon editing finished."))
  2583. # self.progress.emit(100)
  2584. def on_tool_select(self, tool):
  2585. """
  2586. Behavior of the toolbar. Tool initialization.
  2587. :rtype : None
  2588. """
  2589. current_tool = tool
  2590. self.app.log.debug("on_tool_select('%s')" % tool)
  2591. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2592. # self.draw_app.select_tool('drill_select')
  2593. self.complete = True
  2594. current_tool = 'drill_select'
  2595. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  2596. # This is to make the group behave as radio group
  2597. if current_tool in self.tools_exc:
  2598. if self.tools_exc[current_tool]["button"].isChecked():
  2599. self.app.log.debug("%s is checked." % current_tool)
  2600. for t in self.tools_exc:
  2601. if t != current_tool:
  2602. self.tools_exc[t]["button"].setChecked(False)
  2603. # this is where the Editor toolbar classes (button's) are instantiated
  2604. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2605. # self.app.inform.emit(self.active_tool.start_msg)
  2606. else:
  2607. self.app.log.debug("%s is NOT checked." % current_tool)
  2608. for t in self.tools_exc:
  2609. self.tools_exc[t]["button"].setChecked(False)
  2610. self.select_tool('drill_select')
  2611. self.active_tool = FCDrillSelect(self)
  2612. def on_row_selected(self, row, col):
  2613. if col == 0:
  2614. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2615. if self.app.defaults["global_mselect_key"] == 'Control':
  2616. modifier_to_use = Qt.ControlModifier
  2617. else:
  2618. modifier_to_use = Qt.ShiftModifier
  2619. if key_modifier == modifier_to_use:
  2620. pass
  2621. else:
  2622. self.selected = []
  2623. try:
  2624. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2625. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2626. for obj in self.storage_dict[selected_dia].get_objects():
  2627. self.selected.append(obj)
  2628. except Exception as e:
  2629. self.app.log.debug(str(e))
  2630. self.replot()
  2631. def toolbar_tool_toggle(self, key):
  2632. self.options[key] = self.sender().isChecked()
  2633. if self.options[key] is True:
  2634. return 1
  2635. else:
  2636. return 0
  2637. def on_canvas_click(self, event):
  2638. """
  2639. event.x and .y have canvas coordinates
  2640. event.xdata and .ydata have plot coordinates
  2641. :param event: Event object dispatched by VisPy
  2642. :return: None
  2643. """
  2644. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2645. if self.app.grid_status() == True:
  2646. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2647. self.app.app_cursor.enabled = True
  2648. # Update cursor
  2649. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2650. size=20)
  2651. else:
  2652. self.pos = (self.pos[0], self.pos[1])
  2653. self.app.app_cursor.enabled = False
  2654. if event.button is 1:
  2655. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2656. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2657. # Selection with left mouse button
  2658. if self.active_tool is not None and event.button is 1:
  2659. # Dispatch event to active_tool
  2660. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2661. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2662. # If it is a shape generating tool
  2663. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2664. if self.current_storage is not None:
  2665. self.on_exc_shape_complete(self.current_storage)
  2666. self.build_ui()
  2667. # MS: always return to the Select Tool if modifier key is not pressed
  2668. # else return to the current tool
  2669. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2670. if self.app.defaults["global_mselect_key"] == 'Control':
  2671. modifier_to_use = Qt.ControlModifier
  2672. else:
  2673. modifier_to_use = Qt.ShiftModifier
  2674. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2675. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2676. if key_modifier == modifier_to_use:
  2677. self.select_tool(self.active_tool.name)
  2678. else:
  2679. # return to Select tool but not for FCDrillAdd or FCSlot
  2680. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2681. self.select_tool(self.active_tool.name)
  2682. else:
  2683. self.select_tool("drill_select")
  2684. return
  2685. if isinstance(self.active_tool, FCDrillSelect):
  2686. # self.app.log.debug("Replotting after click.")
  2687. self.replot()
  2688. else:
  2689. self.app.log.debug("No active tool to respond to click!")
  2690. def on_exc_shape_complete(self, storage):
  2691. self.app.log.debug("on_shape_complete()")
  2692. # Add shape
  2693. if type(storage) is list:
  2694. for item_storage in storage:
  2695. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2696. else:
  2697. self.add_exc_shape(self.active_tool.geometry, storage)
  2698. # Remove any utility shapes
  2699. self.delete_utility_geometry()
  2700. self.tool_shape.clear(update=True)
  2701. # Replot and reset tool.
  2702. self.replot()
  2703. # self.active_tool = type(self.active_tool)(self)
  2704. def add_exc_shape(self, shape, storage):
  2705. """
  2706. Adds a shape to a specified shape storage.
  2707. :param shape: Shape to be added.
  2708. :type shape: DrawToolShape
  2709. :param storage: object where to store the shapes
  2710. :return: None
  2711. """
  2712. # List of DrawToolShape?
  2713. if isinstance(shape, list):
  2714. for subshape in shape:
  2715. self.add_exc_shape(subshape, storage)
  2716. return
  2717. assert isinstance(shape, DrawToolShape), \
  2718. "Expected a DrawToolShape, got %s" % str(type(shape))
  2719. assert shape.geo is not None, \
  2720. "Shape object has empty geometry (None)"
  2721. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2722. "Shape objects has empty geometry ([])"
  2723. if isinstance(shape, DrawToolUtilityShape):
  2724. self.utility.append(shape)
  2725. else:
  2726. storage.insert(shape) # TODO: Check performance
  2727. def add_shape(self, shape):
  2728. """
  2729. Adds a shape to the shape storage.
  2730. :param shape: Shape to be added.
  2731. :type shape: DrawToolShape
  2732. :return: None
  2733. """
  2734. # List of DrawToolShape?
  2735. if isinstance(shape, list):
  2736. for subshape in shape:
  2737. self.add_shape(subshape)
  2738. return
  2739. assert isinstance(shape, DrawToolShape), \
  2740. "Expected a DrawToolShape, got %s" % type(shape)
  2741. assert shape.geo is not None, \
  2742. "Shape object has empty geometry (None)"
  2743. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2744. "Shape objects has empty geometry ([])"
  2745. if isinstance(shape, DrawToolUtilityShape):
  2746. self.utility.append(shape)
  2747. else:
  2748. self.storage.insert(shape) # TODO: Check performance
  2749. def on_exc_click_release(self, event):
  2750. """
  2751. Handler of the "mouse_release" event.
  2752. It will pop-up the context menu on right mouse click unless there was a panning move (decided in the
  2753. "mouse_move" event handler) and only if the current tool is the Select tool.
  2754. It will 'close' a Editor tool if it is the case.
  2755. :param event: Event object dispatched by VisPy SceneCavas
  2756. :return: None
  2757. """
  2758. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2759. if self.app.grid_status() == True:
  2760. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2761. else:
  2762. pos = (pos_canvas[0], pos_canvas[1])
  2763. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2764. # canvas menu
  2765. try:
  2766. if event.button == 2: # right click
  2767. if self.app.ui.popMenu.mouse_is_panning is False:
  2768. try:
  2769. QtGui.QGuiApplication.restoreOverrideCursor()
  2770. except Exception as e:
  2771. pass
  2772. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2773. self.active_tool.complete = True
  2774. self.in_action = False
  2775. self.delete_utility_geometry()
  2776. self.app.inform.emit(_("[success] Done."))
  2777. self.select_tool('drill_select')
  2778. else:
  2779. if isinstance(self.active_tool, FCDrillAdd):
  2780. self.active_tool.complete = True
  2781. self.in_action = False
  2782. self.delete_utility_geometry()
  2783. self.app.inform.emit(_("[success] Done."))
  2784. self.select_tool('drill_select')
  2785. self.app.cursor = QtGui.QCursor()
  2786. self.app.populate_cmenu_grids()
  2787. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2788. except Exception as e:
  2789. log.warning("Error: %s" % str(e))
  2790. raise
  2791. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2792. # selection and then select a type of selection ("enclosing" or "touching")
  2793. try:
  2794. if event.button == 1: # left click
  2795. if self.app.selection_type is not None:
  2796. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2797. self.app.selection_type = None
  2798. elif isinstance(self.active_tool, FCDrillSelect):
  2799. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2800. # if there are selected objects then plot them
  2801. if self.selected:
  2802. self.replot()
  2803. except Exception as e:
  2804. log.warning("Error: %s" % str(e))
  2805. raise
  2806. def draw_selection_area_handler(self, start, end, sel_type):
  2807. """
  2808. This function is called whenever we have a left mouse click release and only we have a left mouse click drag,
  2809. be it from left to right or from right to left. The direction of the drag is decided in the "mouse_move"
  2810. event handler.
  2811. Pressing a modifier key (eg. Ctrl, Shift or Alt) will change the behavior of the selection.
  2812. Depending on which tool belongs the selected shapes, the corresponding rows in the Tools Table are selected or
  2813. deselected.
  2814. :param start: mouse position when the selection LMB click was done
  2815. :param end: mouse position when the left mouse button is released
  2816. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2817. :return:
  2818. """
  2819. start_pos = (start[0], start[1])
  2820. end_pos = (end[0], end[1])
  2821. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2822. modifiers = None
  2823. # delete the selection shape that was just drawn, we no longer need it
  2824. self.app.delete_selection_shape()
  2825. # detect if a modifier key was pressed while the left mouse button was released
  2826. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2827. if self.modifiers == QtCore.Qt.ShiftModifier:
  2828. modifiers = 'Shift'
  2829. elif self.modifiers == QtCore.Qt.ControlModifier:
  2830. modifiers = 'Control'
  2831. if modifiers == self.app.defaults["global_mselect_key"]:
  2832. for storage in self.storage_dict:
  2833. for obj in self.storage_dict[storage].get_objects():
  2834. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2835. (sel_type is False and poly_selection.intersects(obj.geo)):
  2836. if obj in self.selected:
  2837. # remove the shape object from the selected shapes storage
  2838. self.selected.remove(obj)
  2839. else:
  2840. # add the shape object to the selected shapes storage
  2841. self.selected.append(obj)
  2842. else:
  2843. # clear the selection shapes storage
  2844. self.selected = []
  2845. # then add to the selection shapes storage the shapes that are included (touched) by the selection rectangle
  2846. for storage in self.storage_dict:
  2847. for obj in self.storage_dict[storage].get_objects():
  2848. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2849. (sel_type is False and poly_selection.intersects(obj.geo)):
  2850. self.selected.append(obj)
  2851. try:
  2852. self.tools_table_exc.cellPressed.disconnect()
  2853. except Exception as e:
  2854. pass
  2855. # first deselect all rows (tools) in the Tools Table
  2856. self.tools_table_exc.clearSelection()
  2857. # and select the rows (tools) in the tool table according to the diameter(s) of the selected shape(s)
  2858. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2859. for storage in self.storage_dict:
  2860. for shape_s in self.selected:
  2861. if shape_s in self.storage_dict[storage].get_objects():
  2862. for key_tool_nr in self.tool2tooldia:
  2863. if self.tool2tooldia[key_tool_nr] == storage:
  2864. row_to_sel = key_tool_nr - 1
  2865. # item = self.tools_table_exc.item(row_to_sel, 1)
  2866. # self.tools_table_exc.setCurrentItem(item)
  2867. # item.setSelected(True)
  2868. # if the row to be selected is not already in the selected rows then select it
  2869. # otherwise don't do it as it seems that we have a toggle effect
  2870. if row_to_sel not in set(index.row() for index in self.tools_table_exc.selectedIndexes()):
  2871. self.tools_table_exc.selectRow(row_to_sel)
  2872. self.last_tool_selected = int(key_tool_nr)
  2873. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2874. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2875. self.replot()
  2876. def on_canvas_move(self, event):
  2877. """
  2878. Called on 'mouse_move' event.
  2879. It updates the mouse cursor if the grid snapping is ON.
  2880. It decide if we have a mouse drag and if it is done with the right mouse click. Then it passes this info to a
  2881. class object which is used in the "mouse_release" handler to decide if to pop-up the context menu or not.
  2882. It draws utility_geometry for the Editor tools.
  2883. Update the position labels from status bar.
  2884. Decide if we have a right to left or a left to right mouse drag with left mouse button and call a function
  2885. that will draw a selection shape on canvas.
  2886. event.pos have canvas screen coordinates
  2887. :param event: Event object dispatched by VisPy SceneCavas
  2888. :return: None
  2889. """
  2890. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2891. event.xdata, event.ydata = pos[0], pos[1]
  2892. self.x = event.xdata
  2893. self.y = event.ydata
  2894. self.app.ui.popMenu.mouse_is_panning = False
  2895. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2896. if event.button == 2 and event.is_dragging == 1:
  2897. self.app.ui.popMenu.mouse_is_panning = True
  2898. return
  2899. try:
  2900. x = float(event.xdata)
  2901. y = float(event.ydata)
  2902. except TypeError:
  2903. return
  2904. if self.active_tool is None:
  2905. return
  2906. # ## Snap coordinates
  2907. if self.app.grid_status() == True:
  2908. x, y = self.app.geo_editor.snap(x, y)
  2909. self.app.app_cursor.enabled = True
  2910. # Update cursor
  2911. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2912. else:
  2913. self.app.app_cursor.enabled = False
  2914. self.snap_x = x
  2915. self.snap_y = y
  2916. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2917. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2918. "<b>Y</b>: %.4f" % (x, y))
  2919. if self.pos is None:
  2920. self.pos = (0, 0)
  2921. dx = x - self.pos[0]
  2922. dy = y - self.pos[1]
  2923. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2924. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2925. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2926. # ## Utility geometry (animated)
  2927. geo = self.active_tool.utility_geometry(data=(x, y))
  2928. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2929. # Remove any previous utility shape
  2930. self.tool_shape.clear(update=True)
  2931. self.draw_utility_geometry(geo=geo)
  2932. # ## Selection area on canvas section # ##
  2933. if event.is_dragging == 1 and event.button == 1:
  2934. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2935. # can create strange issues. Also for FCSlot and FCSlotArray
  2936. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray) or \
  2937. isinstance(self.active_tool, FCSlot) or isinstance(self.active_tool, FCSlotArray):
  2938. self.app.selection_type = None
  2939. else:
  2940. dx = pos[0] - self.pos[0]
  2941. self.app.delete_selection_shape()
  2942. if dx < 0:
  2943. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2944. color=self.app.defaults["global_alt_sel_line"],
  2945. face_color=self.app.defaults['global_alt_sel_fill'])
  2946. self.app.selection_type = False
  2947. else:
  2948. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2949. self.app.selection_type = True
  2950. else:
  2951. self.app.selection_type = None
  2952. # Update cursor
  2953. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2954. def on_canvas_key_release(self, event):
  2955. self.key = None
  2956. def draw_utility_geometry(self, geo):
  2957. # Add the new utility shape
  2958. try:
  2959. # this case is for the Font Parse
  2960. for el in list(geo.geo):
  2961. if type(el) == MultiPolygon:
  2962. for poly in el:
  2963. self.tool_shape.add(
  2964. shape=poly,
  2965. color=(self.app.defaults["global_draw_color"] + '80'),
  2966. update=False,
  2967. layer=0,
  2968. tolerance=None
  2969. )
  2970. elif type(el) == MultiLineString:
  2971. for linestring in el:
  2972. self.tool_shape.add(
  2973. shape=linestring,
  2974. color=(self.app.defaults["global_draw_color"] + '80'),
  2975. update=False,
  2976. layer=0,
  2977. tolerance=None
  2978. )
  2979. else:
  2980. self.tool_shape.add(
  2981. shape=el,
  2982. color=(self.app.defaults["global_draw_color"] + '80'),
  2983. update=False,
  2984. layer=0,
  2985. tolerance=None
  2986. )
  2987. except TypeError:
  2988. self.tool_shape.add(
  2989. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2990. update=False, layer=0, tolerance=None)
  2991. self.tool_shape.redraw()
  2992. def replot(self):
  2993. self.plot_all()
  2994. def plot_all(self):
  2995. """
  2996. Plots all shapes in the editor.
  2997. :return: None
  2998. :rtype: None
  2999. """
  3000. # self.app.log.debug("plot_all()")
  3001. self.shapes.clear(update=True)
  3002. for storage in self.storage_dict:
  3003. for shape_plus in self.storage_dict[storage].get_objects():
  3004. if shape_plus.geo is None:
  3005. continue
  3006. if shape_plus in self.selected:
  3007. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  3008. linewidth=2)
  3009. continue
  3010. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  3011. # for shape in self.storage.get_objects():
  3012. # if shape.geo is None: # TODO: This shouldn't have happened
  3013. # continue
  3014. #
  3015. # if shape in self.selected:
  3016. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3017. # continue
  3018. #
  3019. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3020. for shape_form in self.utility:
  3021. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  3022. continue
  3023. self.shapes.redraw()
  3024. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3025. """
  3026. Plots a geometric object or list of objects without rendering. Plotted objects
  3027. are returned as a list. This allows for efficient/animated rendering.
  3028. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3029. :param color: Shape color
  3030. :param linewidth: Width of lines in # of pixels.
  3031. :return: List of plotted elements.
  3032. """
  3033. plot_elements = []
  3034. if geometry is None:
  3035. geometry = self.active_tool.geometry
  3036. try:
  3037. for geo in geometry:
  3038. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3039. # ## Non-iterable
  3040. except TypeError:
  3041. # ## DrawToolShape
  3042. if isinstance(geometry, DrawToolShape):
  3043. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3044. # ## Polygon: Descend into exterior and each interior.
  3045. if type(geometry) == Polygon:
  3046. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3047. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3048. if type(geometry) == LineString or type(geometry) == LinearRing:
  3049. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0, tolerance=self.tolerance))
  3050. if type(geometry) == Point:
  3051. pass
  3052. return plot_elements
  3053. def on_shape_complete(self):
  3054. self.app.log.debug("on_shape_complete()")
  3055. # Add shape
  3056. self.add_shape(self.active_tool.geometry)
  3057. # Remove any utility shapes
  3058. self.delete_utility_geometry()
  3059. self.tool_shape.clear(update=True)
  3060. # Replot and reset tool.
  3061. self.replot()
  3062. # self.active_tool = type(self.active_tool)(self)
  3063. def get_selected(self):
  3064. """
  3065. Returns list of shapes that are selected in the editor.
  3066. :return: List of shapes.
  3067. """
  3068. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3069. return self.selected
  3070. def delete_selected(self):
  3071. temp_ref = [s for s in self.selected]
  3072. for shape_sel in temp_ref:
  3073. self.delete_shape(shape_sel)
  3074. self.selected = []
  3075. self.build_ui()
  3076. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  3077. def delete_shape(self, del_shape):
  3078. self.is_modified = True
  3079. if del_shape in self.utility:
  3080. self.utility.remove(del_shape)
  3081. return
  3082. for storage in self.storage_dict:
  3083. # try:
  3084. # self.storage_dict[storage].remove(shape)
  3085. # except:
  3086. # pass
  3087. if del_shape in self.storage_dict[storage].get_objects():
  3088. if isinstance(del_shape.geo, MultiLineString):
  3089. self.storage_dict[storage].remove(del_shape)
  3090. # a hack to make the tool_table display less drills per diameter
  3091. # self.points_edit it's only useful first time when we load the data into the storage
  3092. # but is still used as referecen when building tool_table in self.build_ui()
  3093. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  3094. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  3095. del self.points_edit[storage][0]
  3096. else:
  3097. self.storage_dict[storage].remove(del_shape)
  3098. del self.slot_points_edit[storage][0]
  3099. if del_shape in self.selected:
  3100. self.selected.remove(del_shape) # TODO: Check performance
  3101. def delete_utility_geometry(self):
  3102. for_deletion = [util_shape for util_shape in self.utility]
  3103. for util_shape in for_deletion:
  3104. self.delete_shape(util_shape)
  3105. self.tool_shape.clear(update=True)
  3106. self.tool_shape.redraw()
  3107. def on_delete_btn(self):
  3108. self.delete_selected()
  3109. self.replot()
  3110. def select_tool(self, toolname):
  3111. """
  3112. Selects a drawing tool. Impacts the object and GUI.
  3113. :param toolname: Name of the tool.
  3114. :return: None
  3115. """
  3116. self.tools_exc[toolname]["button"].setChecked(True)
  3117. self.on_tool_select(toolname)
  3118. def set_selected(self, sel_shape):
  3119. # Remove and add to the end.
  3120. if sel_shape in self.selected:
  3121. self.selected.remove(sel_shape)
  3122. self.selected.append(sel_shape)
  3123. def set_unselected(self, unsel_shape):
  3124. if unsel_shape in self.selected:
  3125. self.selected.remove(unsel_shape)
  3126. def on_array_type_combo(self):
  3127. if self.array_type_combo.currentIndex() == 0:
  3128. self.array_circular_frame.hide()
  3129. self.array_linear_frame.show()
  3130. else:
  3131. self.delete_utility_geometry()
  3132. self.array_circular_frame.show()
  3133. self.array_linear_frame.hide()
  3134. self.app.inform.emit(_("Click on the circular array Center position"))
  3135. def on_slot_array_type_combo(self):
  3136. if self.slot_array_type_combo.currentIndex() == 0:
  3137. self.slot_array_circular_frame.hide()
  3138. self.slot_array_linear_frame.show()
  3139. else:
  3140. self.delete_utility_geometry()
  3141. self.slot_array_circular_frame.show()
  3142. self.slot_array_linear_frame.hide()
  3143. self.app.inform.emit(_("Click on the circular array Center position"))
  3144. def on_linear_angle_radio(self):
  3145. val = self.drill_axis_radio.get_value()
  3146. if val == 'A':
  3147. self.linear_angle_spinner.show()
  3148. self.linear_angle_label.show()
  3149. else:
  3150. self.linear_angle_spinner.hide()
  3151. self.linear_angle_label.hide()
  3152. def on_slot_array_linear_angle_radio(self):
  3153. val = self.slot_array_axis_radio.get_value()
  3154. if val == 'A':
  3155. self.slot_array_linear_angle_spinner.show()
  3156. self.slot_array_linear_angle_label.show()
  3157. else:
  3158. self.slot_array_linear_angle_spinner.hide()
  3159. self.slot_array_linear_angle_label.hide()
  3160. def on_slot_angle_radio(self):
  3161. val = self.slot_axis_radio.get_value()
  3162. if val == 'A':
  3163. self.slot_angle_spinner.show()
  3164. self.slot_angle_label.show()
  3165. else:
  3166. self.slot_angle_spinner.hide()
  3167. self.slot_angle_label.hide()
  3168. def exc_add_drill(self):
  3169. self.select_tool('drill_add')
  3170. return
  3171. def exc_add_drill_array(self):
  3172. self.select_tool('drill_array')
  3173. return
  3174. def exc_add_slot(self):
  3175. self.select_tool('slot_add')
  3176. return
  3177. def exc_add_slot_array(self):
  3178. self.select_tool('slot_array')
  3179. return
  3180. def exc_resize_drills(self):
  3181. self.select_tool('drill_resize')
  3182. return
  3183. def exc_copy_drills(self):
  3184. self.select_tool('drill_copy')
  3185. return
  3186. def exc_move_drills(self):
  3187. self.select_tool('drill_move')
  3188. return
  3189. def get_shapely_list_bounds(geometry_list):
  3190. xmin = Inf
  3191. ymin = Inf
  3192. xmax = -Inf
  3193. ymax = -Inf
  3194. for gs in geometry_list:
  3195. try:
  3196. gxmin, gymin, gxmax, gymax = gs.bounds
  3197. xmin = min([xmin, gxmin])
  3198. ymin = min([ymin, gymin])
  3199. xmax = max([xmax, gxmax])
  3200. ymax = max([ymax, gymax])
  3201. except Exception as e:
  3202. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3203. return [xmin, ymin, xmax, ymax]
  3204. # EOF