FlatCAMExcEditor.py 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945
  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 the selected tools
  1023. self.sel_tools = set()
  1024. # here we store all shapes that were selected so we can search for the nearest to our click location
  1025. self.sel_storage = FlatCAMExcEditor.make_storage()
  1026. self.exc_editor_app.resize_frame.hide()
  1027. self.exc_editor_app.array_frame.hide()
  1028. self.exc_editor_app.slot_frame.hide()
  1029. self.exc_editor_app.slot_array_frame.hide()
  1030. def click(self, point):
  1031. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1032. if key_modifier == QtCore.Qt.ShiftModifier:
  1033. mod_key = 'Shift'
  1034. elif key_modifier == QtCore.Qt.ControlModifier:
  1035. mod_key = 'Control'
  1036. else:
  1037. mod_key = None
  1038. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  1039. pass
  1040. else:
  1041. self.exc_editor_app.selected = []
  1042. def click_release(self, pos):
  1043. self.exc_editor_app.tools_table_exc.clearSelection()
  1044. xmin, ymin, xmax, ymax = 0, 0, 0, 0
  1045. try:
  1046. for storage in self.exc_editor_app.storage_dict:
  1047. for sh in self.exc_editor_app.storage_dict[storage].get_objects():
  1048. self.sel_storage.insert(sh)
  1049. _, closest_shape = self.sel_storage.nearest(pos)
  1050. # constrain selection to happen only within a certain bounding box; it works only for MultiLineStrings
  1051. if isinstance(closest_shape.geo, MultiLineString):
  1052. x_coord, y_coord = closest_shape.geo[0].xy
  1053. delta = (x_coord[1] - x_coord[0])
  1054. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  1055. xmin = x_coord[0] - (0.7 * delta)
  1056. xmax = x_coord[0] + (1.7 * delta)
  1057. ymin = y_coord[0] - (0.7 * delta)
  1058. ymax = y_coord[0] + (1.7 * delta)
  1059. elif isinstance(closest_shape.geo, Polygon):
  1060. xmin, ymin, xmax, ymax = closest_shape.geo.bounds
  1061. dx = xmax - xmin
  1062. dy = ymax - ymin
  1063. delta = dx if dx > dy else dy
  1064. xmin -= 0.7 * delta
  1065. xmax += 0.7 * delta
  1066. ymin -= 0.7 * delta
  1067. ymax += 0.7 * delta
  1068. except StopIteration:
  1069. return ""
  1070. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  1071. self.exc_editor_app.selected = []
  1072. else:
  1073. modifiers = QtWidgets.QApplication.keyboardModifiers()
  1074. if modifiers == QtCore.Qt.ShiftModifier:
  1075. mod_key = 'Shift'
  1076. elif modifiers == QtCore.Qt.ControlModifier:
  1077. mod_key = 'Control'
  1078. else:
  1079. mod_key = None
  1080. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  1081. if closest_shape in self.exc_editor_app.selected:
  1082. self.exc_editor_app.selected.remove(closest_shape)
  1083. else:
  1084. self.exc_editor_app.selected.append(closest_shape)
  1085. else:
  1086. self.draw_app.selected = []
  1087. self.draw_app.selected.append(closest_shape)
  1088. # select the diameter of the selected shape in the tool table
  1089. try:
  1090. self.draw_app.tools_table_exc.cellPressed.disconnect()
  1091. except (TypeError, AttributeError):
  1092. pass
  1093. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1094. for shape_s in self.exc_editor_app.selected:
  1095. for storage in self.exc_editor_app.storage_dict:
  1096. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  1097. self.sel_tools.add(storage)
  1098. for storage in self.sel_tools:
  1099. for k, v in self.draw_app.tool2tooldia.items():
  1100. if v == storage:
  1101. self.exc_editor_app.tools_table_exc.selectRow(int(k) - 1)
  1102. self.draw_app.last_tool_selected = int(k)
  1103. break
  1104. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1105. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  1106. # delete whatever is in selection storage, there is no longer need for those shapes
  1107. self.sel_storage = FlatCAMExcEditor.make_storage()
  1108. return ""
  1109. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1110. # for storage in self.exc_editor_app.storage_dict:
  1111. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1112. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1113. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1114. # over_shape_list.append(obj_shape)
  1115. #
  1116. # try:
  1117. # # if there is no shape under our click then deselect all shapes
  1118. # if not over_shape_list:
  1119. # self.exc_editor_app.selected = []
  1120. # FlatCAMExcEditor.draw_shape_idx = -1
  1121. # self.exc_editor_app.tools_table_exc.clearSelection()
  1122. # else:
  1123. # # if there are shapes under our click then advance through the list of them, one at the time in a
  1124. # # circular way
  1125. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  1126. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  1127. #
  1128. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  1129. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  1130. # if obj_to_add in self.exc_editor_app.selected:
  1131. # self.exc_editor_app.selected.remove(obj_to_add)
  1132. # else:
  1133. # self.exc_editor_app.selected.append(obj_to_add)
  1134. # else:
  1135. # self.exc_editor_app.selected = []
  1136. # self.exc_editor_app.selected.append(obj_to_add)
  1137. # else:
  1138. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1139. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  1140. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  1141. # if obj_to_add in self.exc_editor_app.selected:
  1142. # self.exc_editor_app.selected.remove(obj_to_add)
  1143. # else:
  1144. # self.exc_editor_app.selected.append(obj_to_add)
  1145. # else:
  1146. # self.exc_editor_app.selected = []
  1147. # self.exc_editor_app.selected.append(obj_to_add)
  1148. #
  1149. # for storage in self.exc_editor_app.storage_dict:
  1150. # for shape in self.exc_editor_app.selected:
  1151. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1152. # for key in self.exc_editor_app.tool2tooldia:
  1153. # if self.exc_editor_app.tool2tooldia[key] == storage:
  1154. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1155. # item.setSelected(True)
  1156. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1157. #
  1158. # except Exception as e:
  1159. # log.error("[ERROR] Something went bad. %s" % str(e))
  1160. # raise
  1161. class FlatCAMExcEditor(QtCore.QObject):
  1162. draw_shape_idx = -1
  1163. def __init__(self, app):
  1164. assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1165. super(FlatCAMExcEditor, self).__init__()
  1166. self.app = app
  1167. self.canvas = self.app.plotcanvas
  1168. # ## Current application units in Upper Case
  1169. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1170. self.exc_edit_widget = QtWidgets.QWidget()
  1171. # ## Box for custom widgets
  1172. # This gets populated in offspring implementations.
  1173. layout = QtWidgets.QVBoxLayout()
  1174. self.exc_edit_widget.setLayout(layout)
  1175. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1176. # this way I can hide/show the frame
  1177. self.drills_frame = QtWidgets.QFrame()
  1178. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  1179. layout.addWidget(self.drills_frame)
  1180. self.tools_box = QtWidgets.QVBoxLayout()
  1181. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1182. self.drills_frame.setLayout(self.tools_box)
  1183. # ## Page Title box (spacing between children)
  1184. self.title_box = QtWidgets.QHBoxLayout()
  1185. self.tools_box.addLayout(self.title_box)
  1186. # ## Page Title icon
  1187. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1188. self.icon = QtWidgets.QLabel()
  1189. self.icon.setPixmap(pixmap)
  1190. self.title_box.addWidget(self.icon, stretch=0)
  1191. # ## Title label
  1192. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  1193. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1194. self.title_box.addWidget(self.title_label, stretch=1)
  1195. # ## Object name
  1196. self.name_box = QtWidgets.QHBoxLayout()
  1197. self.tools_box.addLayout(self.name_box)
  1198. name_label = QtWidgets.QLabel(_("Name:"))
  1199. self.name_box.addWidget(name_label)
  1200. self.name_entry = FCEntry()
  1201. self.name_box.addWidget(self.name_entry)
  1202. # ### Tools Drills ## ##
  1203. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  1204. self.tools_table_label.setToolTip(
  1205. _("Tools in this Excellon object\n"
  1206. "when are used for drilling.")
  1207. )
  1208. self.tools_box.addWidget(self.tools_table_label)
  1209. self.tools_table_exc = FCTable()
  1210. # delegate = SpinBoxDelegate(units=self.units)
  1211. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  1212. self.tools_box.addWidget(self.tools_table_exc)
  1213. self.tools_table_exc.setColumnCount(4)
  1214. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1215. self.tools_table_exc.setSortingEnabled(False)
  1216. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1217. self.empty_label = QtWidgets.QLabel('')
  1218. self.tools_box.addWidget(self.empty_label)
  1219. # ### Add a new Tool ## ##
  1220. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  1221. self.addtool_label.setToolTip(
  1222. _("Add/Delete a tool to the tool list\n"
  1223. "for this Excellon object.")
  1224. )
  1225. self.tools_box.addWidget(self.addtool_label)
  1226. grid1 = QtWidgets.QGridLayout()
  1227. self.tools_box.addLayout(grid1)
  1228. addtool_entry_lbl = QtWidgets.QLabel('%s:' % _('Tool Dia'))
  1229. addtool_entry_lbl.setToolTip(
  1230. _("Diameter for the new tool")
  1231. )
  1232. hlay = QtWidgets.QHBoxLayout()
  1233. self.addtool_entry = FCEntry()
  1234. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1235. hlay.addWidget(self.addtool_entry)
  1236. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  1237. self.addtool_btn.setToolTip(
  1238. _("Add a new tool to the tool list\n"
  1239. "with the diameter specified above.")
  1240. )
  1241. self.addtool_btn.setFixedWidth(80)
  1242. hlay.addWidget(self.addtool_btn)
  1243. grid1.addWidget(addtool_entry_lbl, 0, 0)
  1244. grid1.addLayout(hlay, 0, 1)
  1245. grid2 = QtWidgets.QGridLayout()
  1246. self.tools_box.addLayout(grid2)
  1247. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  1248. self.deltool_btn.setToolTip(
  1249. _("Delete a tool in the tool list\n"
  1250. "by selecting a row in the tool table.")
  1251. )
  1252. grid2.addWidget(self.deltool_btn, 0, 1)
  1253. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1254. # this way I can hide/show the frame
  1255. self.resize_frame = QtWidgets.QFrame()
  1256. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  1257. self.tools_box.addWidget(self.resize_frame)
  1258. self.resize_box = QtWidgets.QVBoxLayout()
  1259. self.resize_box.setContentsMargins(0, 0, 0, 0)
  1260. self.resize_frame.setLayout(self.resize_box)
  1261. # ### Resize a drill ## ##
  1262. self.emptyresize_label = QtWidgets.QLabel('')
  1263. self.resize_box.addWidget(self.emptyresize_label)
  1264. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  1265. self.drillresize_label.setToolTip(
  1266. _("Resize a drill or a selection of drills.")
  1267. )
  1268. self.resize_box.addWidget(self.drillresize_label)
  1269. grid3 = QtWidgets.QGridLayout()
  1270. self.resize_box.addLayout(grid3)
  1271. res_entry_lbl = QtWidgets.QLabel('%s:' % _('Resize Dia'))
  1272. res_entry_lbl.setToolTip(
  1273. _("Diameter to resize to.")
  1274. )
  1275. grid3.addWidget(res_entry_lbl, 0, 0)
  1276. hlay2 = QtWidgets.QHBoxLayout()
  1277. self.resdrill_entry = LengthEntry()
  1278. hlay2.addWidget(self.resdrill_entry)
  1279. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  1280. self.resize_btn.setToolTip(
  1281. _("Resize drill(s)")
  1282. )
  1283. self.resize_btn.setFixedWidth(80)
  1284. hlay2.addWidget(self.resize_btn)
  1285. grid3.addLayout(hlay2, 0, 1)
  1286. self.resize_frame.hide()
  1287. # ####################################
  1288. # ### Add DRILL Array ################
  1289. # ####################################
  1290. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1291. # all the add drill array widgets
  1292. # this way I can hide/show the frame
  1293. self.array_frame = QtWidgets.QFrame()
  1294. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1295. self.tools_box.addWidget(self.array_frame)
  1296. self.array_box = QtWidgets.QVBoxLayout()
  1297. self.array_box.setContentsMargins(0, 0, 0, 0)
  1298. self.array_frame.setLayout(self.array_box)
  1299. self.emptyarray_label = QtWidgets.QLabel('')
  1300. self.array_box.addWidget(self.emptyarray_label)
  1301. self.drill_array_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  1302. self.drill_array_label.setToolTip(
  1303. _("Add an array of drills (linear or circular array)")
  1304. )
  1305. self.array_box.addWidget(self.drill_array_label)
  1306. self.array_type_combo = FCComboBox()
  1307. self.array_type_combo.setToolTip(
  1308. _("Select the type of drills array to create.\n"
  1309. "It can be Linear X(Y) or Circular")
  1310. )
  1311. self.array_type_combo.addItem(_("Linear"))
  1312. self.array_type_combo.addItem(_("Circular"))
  1313. self.array_box.addWidget(self.array_type_combo)
  1314. self.array_form = QtWidgets.QFormLayout()
  1315. self.array_box.addLayout(self.array_form)
  1316. # Set the number of drill holes in the drill array
  1317. self.drill_array_size_label = QtWidgets.QLabel('%s:' % _('Nr of drills'))
  1318. self.drill_array_size_label.setToolTip(_("Specify how many drills to be in the array."))
  1319. self.drill_array_size_label.setMinimumWidth(100)
  1320. self.drill_array_size_entry = LengthEntry()
  1321. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  1322. self.array_linear_frame = QtWidgets.QFrame()
  1323. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1324. self.array_box.addWidget(self.array_linear_frame)
  1325. self.linear_box = QtWidgets.QVBoxLayout()
  1326. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1327. self.array_linear_frame.setLayout(self.linear_box)
  1328. self.linear_form = QtWidgets.QFormLayout()
  1329. self.linear_box.addLayout(self.linear_form)
  1330. # Linear Drill Array direction
  1331. self.drill_axis_label = QtWidgets.QLabel('%s:'% _('Direction'))
  1332. self.drill_axis_label.setToolTip(
  1333. _("Direction on which the linear array is oriented:\n"
  1334. "- 'X' - horizontal axis \n"
  1335. "- 'Y' - vertical axis or \n"
  1336. "- 'Angle' - a custom angle for the array inclination")
  1337. )
  1338. self.drill_axis_label.setMinimumWidth(100)
  1339. self.drill_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1340. {'label': _('Y'), 'value': 'Y'},
  1341. {'label': _('Angle'), 'value': 'A'}])
  1342. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  1343. # Linear Drill Array pitch distance
  1344. self.drill_pitch_label = QtWidgets.QLabel('%s:' % _('Pitch'))
  1345. self.drill_pitch_label.setToolTip(
  1346. _("Pitch = Distance between elements of the array.")
  1347. )
  1348. self.drill_pitch_label.setMinimumWidth(100)
  1349. self.drill_pitch_entry = LengthEntry()
  1350. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  1351. # Linear Drill Array angle
  1352. self.linear_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  1353. self.linear_angle_label.setToolTip(
  1354. _("Angle at which the linear array is placed.\n"
  1355. "The precision is of max 2 decimals.\n"
  1356. "Min value is: -359.99 degrees.\n"
  1357. "Max value is: 360.00 degrees.")
  1358. )
  1359. self.linear_angle_label.setMinimumWidth(100)
  1360. self.linear_angle_spinner = FCDoubleSpinner()
  1361. self.linear_angle_spinner.set_precision(2)
  1362. self.linear_angle_spinner.setSingleStep(1.0)
  1363. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1364. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1365. self.array_circular_frame = QtWidgets.QFrame()
  1366. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1367. self.array_box.addWidget(self.array_circular_frame)
  1368. self.circular_box = QtWidgets.QVBoxLayout()
  1369. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1370. self.array_circular_frame.setLayout(self.circular_box)
  1371. self.drill_direction_label = QtWidgets.QLabel('%s:' % _('Direction'))
  1372. self.drill_direction_label.setToolTip(_("Direction for circular array."
  1373. "Can be CW = clockwise or CCW = counter clockwise."))
  1374. self.drill_direction_label.setMinimumWidth(100)
  1375. self.circular_form = QtWidgets.QFormLayout()
  1376. self.circular_box.addLayout(self.circular_form)
  1377. self.drill_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1378. {'label': _('CCW'), 'value': 'CCW'}])
  1379. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  1380. self.drill_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  1381. self.drill_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1382. self.drill_angle_label.setMinimumWidth(100)
  1383. self.drill_angle_entry = LengthEntry()
  1384. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  1385. self.array_circular_frame.hide()
  1386. self.linear_angle_spinner.hide()
  1387. self.linear_angle_label.hide()
  1388. self.array_frame.hide()
  1389. # ######################################################
  1390. # ##### ADDING SLOTS ###################################
  1391. # ######################################################
  1392. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1393. # all the add slot widgets
  1394. # this way I can hide/show the frame
  1395. self.slot_frame = QtWidgets.QFrame()
  1396. self.slot_frame.setContentsMargins(0, 0, 0, 0)
  1397. self.tools_box.addWidget(self.slot_frame)
  1398. self.slot_box = QtWidgets.QVBoxLayout()
  1399. self.slot_box.setContentsMargins(0, 0, 0, 0)
  1400. self.slot_frame.setLayout(self.slot_box)
  1401. self.emptyarray_label = QtWidgets.QLabel('')
  1402. self.slot_box.addWidget(self.emptyarray_label)
  1403. self.slot_label = QtWidgets.QLabel('<b>%s</b>' % _("Slot Parameters"))
  1404. self.slot_label.setToolTip(
  1405. _("Parameters for adding a slot (hole with oval shape)\n"
  1406. "either single or as an part of an array.")
  1407. )
  1408. self.slot_box.addWidget(self.slot_label)
  1409. self.slot_form = QtWidgets.QFormLayout()
  1410. self.slot_box.addLayout(self.slot_form)
  1411. # Slot length
  1412. self.slot_length_label = QtWidgets.QLabel('%s:' % _('Length'))
  1413. self.slot_length_label.setToolTip(
  1414. _("Length = The length of the slot.")
  1415. )
  1416. self.slot_length_label.setMinimumWidth(100)
  1417. self.slot_length_entry = LengthEntry()
  1418. self.slot_form.addRow(self.slot_length_label, self.slot_length_entry)
  1419. # Slot direction
  1420. self.slot_axis_label = QtWidgets.QLabel('%s:' % _('Direction'))
  1421. self.slot_axis_label.setToolTip(
  1422. _("Direction on which the slot is oriented:\n"
  1423. "- 'X' - horizontal axis \n"
  1424. "- 'Y' - vertical axis or \n"
  1425. "- 'Angle' - a custom angle for the slot inclination")
  1426. )
  1427. self.slot_axis_label.setMinimumWidth(100)
  1428. self.slot_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1429. {'label': _('Y'), 'value': 'Y'},
  1430. {'label': _('Angle'), 'value': 'A'}])
  1431. self.slot_form.addRow(self.slot_axis_label, self.slot_axis_radio)
  1432. # Slot custom angle
  1433. self.slot_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  1434. self.slot_angle_label.setToolTip(
  1435. _("Angle at which the slot is placed.\n"
  1436. "The precision is of max 2 decimals.\n"
  1437. "Min value is: -359.99 degrees.\n"
  1438. "Max value is: 360.00 degrees.")
  1439. )
  1440. self.slot_angle_label.setMinimumWidth(100)
  1441. self.slot_angle_spinner = FCDoubleSpinner()
  1442. self.slot_angle_spinner.set_precision(2)
  1443. self.slot_angle_spinner.setWrapping(True)
  1444. self.slot_angle_spinner.setRange(-359.99, 360.00)
  1445. self.slot_angle_spinner.setSingleStep(1.0)
  1446. self.slot_form.addRow(self.slot_angle_label, self.slot_angle_spinner)
  1447. self.slot_frame.hide()
  1448. # ######################################################
  1449. # ##### ADDING SLOT ARRAY #############################
  1450. # ######################################################
  1451. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1452. # all the add slot widgets
  1453. # this way I can hide/show the frame
  1454. self.slot_array_frame = QtWidgets.QFrame()
  1455. self.slot_array_frame.setContentsMargins(0, 0, 0, 0)
  1456. self.tools_box.addWidget(self.slot_array_frame)
  1457. self.slot_array_box = QtWidgets.QVBoxLayout()
  1458. self.slot_array_box.setContentsMargins(0, 0, 0, 0)
  1459. self.slot_array_frame.setLayout(self.slot_array_box)
  1460. self.emptyarray_label = QtWidgets.QLabel('')
  1461. self.slot_array_box.addWidget(self.emptyarray_label)
  1462. self.slot_array_label = QtWidgets.QLabel('<b>%s</b>' % _("Slot Array Parameters"))
  1463. self.slot_array_label.setToolTip(
  1464. _("Parameters for the array of slots (linear or circular array)")
  1465. )
  1466. self.slot_array_box.addWidget(self.slot_array_label)
  1467. self.l_form = QtWidgets.QFormLayout()
  1468. self.slot_array_box.addLayout(self.l_form)
  1469. self.slot_array_type_combo = FCComboBox()
  1470. self.slot_array_type_combo.setToolTip(
  1471. _("Select the type of slot array to create.\n"
  1472. "It can be Linear X(Y) or Circular")
  1473. )
  1474. self.slot_array_type_combo.addItem(_("Linear"))
  1475. self.slot_array_type_combo.addItem(_("Circular"))
  1476. self.slot_array_box.addWidget(self.slot_array_type_combo)
  1477. self.slot_array_form = QtWidgets.QFormLayout()
  1478. self.slot_array_box.addLayout(self.slot_array_form)
  1479. # Set the number of slot holes in the slot array
  1480. self.slot_array_size_label = QtWidgets.QLabel('%s:' % _('Nr of slots'))
  1481. self.slot_array_size_label.setToolTip(_("Specify how many slots to be in the array."))
  1482. self.slot_array_size_label.setMinimumWidth(100)
  1483. self.slot_array_size_entry = LengthEntry()
  1484. self.slot_array_form.addRow(self.slot_array_size_label, self.slot_array_size_entry)
  1485. self.slot_array_linear_frame = QtWidgets.QFrame()
  1486. self.slot_array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1487. self.slot_array_box.addWidget(self.slot_array_linear_frame)
  1488. self.slot_array_linear_box = QtWidgets.QVBoxLayout()
  1489. self.slot_array_linear_box.setContentsMargins(0, 0, 0, 0)
  1490. self.slot_array_linear_frame.setLayout(self.slot_array_linear_box)
  1491. self.slot_array_linear_form = QtWidgets.QFormLayout()
  1492. self.slot_array_linear_box.addLayout(self.slot_array_linear_form)
  1493. # Linear Slot Array direction
  1494. self.slot_array_axis_label = QtWidgets.QLabel('%s:' % _('Direction'))
  1495. self.slot_array_axis_label.setToolTip(
  1496. _("Direction on which the linear array is oriented:\n"
  1497. "- 'X' - horizontal axis \n"
  1498. "- 'Y' - vertical axis or \n"
  1499. "- 'Angle' - a custom angle for the array inclination")
  1500. )
  1501. self.slot_array_axis_label.setMinimumWidth(100)
  1502. self.slot_array_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1503. {'label': _('Y'), 'value': 'Y'},
  1504. {'label': _('Angle'), 'value': 'A'}])
  1505. self.slot_array_linear_form.addRow(self.slot_array_axis_label, self.slot_array_axis_radio)
  1506. # Linear Slot Array pitch distance
  1507. self.slot_array_pitch_label = QtWidgets.QLabel('%s:' % _('Pitch'))
  1508. self.slot_array_pitch_label.setToolTip(
  1509. _("Pitch = Distance between elements of the array.")
  1510. )
  1511. self.slot_array_pitch_label.setMinimumWidth(100)
  1512. self.slot_array_pitch_entry = LengthEntry()
  1513. self.slot_array_linear_form.addRow(self.slot_array_pitch_label, self.slot_array_pitch_entry)
  1514. # Linear Slot Array angle
  1515. self.slot_array_linear_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  1516. self.slot_array_linear_angle_label.setToolTip(
  1517. _("Angle at which the linear array is placed.\n"
  1518. "The precision is of max 2 decimals.\n"
  1519. "Min value is: -359.99 degrees.\n"
  1520. "Max value is: 360.00 degrees.")
  1521. )
  1522. self.slot_array_linear_angle_label.setMinimumWidth(100)
  1523. self.slot_array_linear_angle_spinner = FCDoubleSpinner()
  1524. self.slot_array_linear_angle_spinner.set_precision(2)
  1525. self.slot_array_linear_angle_spinner.setSingleStep(1.0)
  1526. self.slot_array_linear_angle_spinner.setRange(-359.99, 360.00)
  1527. self.slot_array_linear_form.addRow(self.slot_array_linear_angle_label, self.slot_array_linear_angle_spinner)
  1528. self.slot_array_circular_frame = QtWidgets.QFrame()
  1529. self.slot_array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1530. self.slot_array_box.addWidget(self.slot_array_circular_frame)
  1531. self.slot_array_circular_box = QtWidgets.QVBoxLayout()
  1532. self.slot_array_circular_box.setContentsMargins(0, 0, 0, 0)
  1533. self.slot_array_circular_frame.setLayout(self.slot_array_circular_box)
  1534. self.slot_array_direction_label = QtWidgets.QLabel('%s:' % _('Direction'))
  1535. self.slot_array_direction_label.setToolTip(_("Direction for circular array."
  1536. "Can be CW = clockwise or CCW = counter clockwise."))
  1537. self.slot_array_direction_label.setMinimumWidth(100)
  1538. self.slot_array_circular_form = QtWidgets.QFormLayout()
  1539. self.slot_array_circular_box.addLayout(self.slot_array_circular_form)
  1540. self.slot_array_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1541. {'label': _('CCW'), 'value': 'CCW'}])
  1542. self.slot_array_circular_form.addRow(self.slot_array_direction_label, self.slot_array_direction_radio)
  1543. self.slot_array_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  1544. self.slot_array_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1545. self.slot_array_angle_label.setMinimumWidth(100)
  1546. self.slot_array_angle_entry = LengthEntry()
  1547. self.slot_array_circular_form.addRow(self.slot_array_angle_label, self.slot_array_angle_entry)
  1548. self.slot_array_linear_angle_spinner.hide()
  1549. self.slot_array_linear_angle_label.hide()
  1550. self.slot_array_frame.hide()
  1551. self.tools_box.addStretch()
  1552. # ## Toolbar events and properties
  1553. self.tools_exc = {
  1554. "drill_select": {"button": self.app.ui.select_drill_btn,
  1555. "constructor": FCDrillSelect},
  1556. "drill_add": {"button": self.app.ui.add_drill_btn,
  1557. "constructor": FCDrillAdd},
  1558. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  1559. "constructor": FCDrillArray},
  1560. "slot_add": {"button": self.app.ui.add_slot_btn,
  1561. "constructor": FCSlot},
  1562. "slot_array": {"button": self.app.ui.add_slot_array_btn,
  1563. "constructor": FCSlotArray},
  1564. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  1565. "constructor": FCDrillResize},
  1566. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  1567. "constructor": FCDrillCopy},
  1568. "drill_move": {"button": self.app.ui.move_drill_btn,
  1569. "constructor": FCDrillMove},
  1570. }
  1571. # ## Data
  1572. self.active_tool = None
  1573. self.in_action = False
  1574. self.storage_dict = {}
  1575. self.current_storage = []
  1576. # build the data from the Excellon point into a dictionary
  1577. # {tool_dia: [geometry_in_points]}
  1578. self.points_edit = {}
  1579. self.slot_points_edit = {}
  1580. self.sorted_diameters = []
  1581. self.new_drills = []
  1582. self.new_tools = {}
  1583. self.new_slots = []
  1584. self.new_tool_offset = {}
  1585. # dictionary to store the tool_row and diameters in Tool_table
  1586. # it will be updated everytime self.build_ui() is called
  1587. self.olddia_newdia = {}
  1588. self.tool2tooldia = {}
  1589. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1590. # is cleared but as a side effect also the selected tool is cleared
  1591. self.last_tool_selected = None
  1592. self.utility = []
  1593. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1594. self.launched_from_shortcuts = False
  1595. # this var will store the state of the toolbar before starting the editor
  1596. self.toolbar_old_state = False
  1597. if self.units == 'MM':
  1598. self.tolerance = float(self.app.defaults["global_tolerance"])
  1599. else:
  1600. self.tolerance = float(self.app.defaults["global_tolerance"]) / 20
  1601. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  1602. self.name_entry.returnPressed.connect(self.on_name_activate)
  1603. self.addtool_btn.clicked.connect(self.on_tool_add)
  1604. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  1605. self.deltool_btn.clicked.connect(self.on_tool_delete)
  1606. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1607. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1608. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1609. self.slot_array_type_combo.currentIndexChanged.connect(self.on_slot_array_type_combo)
  1610. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1611. self.slot_axis_radio.activated_custom.connect(self.on_slot_angle_radio)
  1612. self.slot_array_axis_radio.activated_custom.connect(self.on_slot_array_linear_angle_radio)
  1613. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  1614. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  1615. self.app.ui.exc_add_array_slot_menuitem.triggered.connect(self.exc_add_slot_array)
  1616. self.app.ui.exc_add_slot_menuitem.triggered.connect(self.exc_add_slot)
  1617. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  1618. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  1619. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  1620. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  1621. self.exc_obj = None
  1622. # VisPy Visuals
  1623. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1624. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1625. self.app.pool_recreated.connect(self.pool_recreated)
  1626. # Remove from scene
  1627. self.shapes.enabled = False
  1628. self.tool_shape.enabled = False
  1629. # ## List of selected shapes.
  1630. self.selected = []
  1631. self.move_timer = QtCore.QTimer()
  1632. self.move_timer.setSingleShot(True)
  1633. self.key = None # Currently pressed key
  1634. self.modifiers = None
  1635. self.x = None # Current mouse cursor pos
  1636. self.y = None
  1637. # Current snapped mouse pos
  1638. self.snap_x = None
  1639. self.snap_y = None
  1640. self.pos = None
  1641. self.complete = False
  1642. def make_callback(thetool):
  1643. def f():
  1644. self.on_tool_select(thetool)
  1645. return f
  1646. for tool in self.tools_exc:
  1647. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1648. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1649. self.options = {
  1650. "global_gridx": 0.1,
  1651. "global_gridy": 0.1,
  1652. "snap_max": 0.05,
  1653. "grid_snap": True,
  1654. "corner_snap": False,
  1655. "grid_gap_link": True
  1656. }
  1657. self.app.options_read_form()
  1658. for option in self.options:
  1659. if option in self.app.options:
  1660. self.options[option] = self.app.options[option]
  1661. self.rtree_exc_index = rtindex.Index()
  1662. # flag to show if the object was modified
  1663. self.is_modified = False
  1664. self.edited_obj_name = ""
  1665. # variable to store the total amount of drills per job
  1666. self.tot_drill_cnt = 0
  1667. self.tool_row = 0
  1668. # variable to store the total amount of slots per job
  1669. self.tot_slot_cnt = 0
  1670. self.tool_row_slots = 0
  1671. self.tool_row = 0
  1672. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1673. self.editor_active = False
  1674. def entry2option(option, entry):
  1675. self.options[option] = float(entry.text())
  1676. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1677. self.editor_active = False
  1678. log.debug("Initialization of the FlatCAM Excellon Editor is finished ...")
  1679. def pool_recreated(self, pool):
  1680. self.shapes.pool = pool
  1681. self.tool_shape.pool = pool
  1682. @staticmethod
  1683. def make_storage():
  1684. # ## Shape storage.
  1685. storage = FlatCAMRTreeStorage()
  1686. storage.get_points = DrawToolShape.get_pts
  1687. return storage
  1688. def set_ui(self):
  1689. # updated units
  1690. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1691. self.olddia_newdia.clear()
  1692. self.tool2tooldia.clear()
  1693. # build the self.points_edit dict {dimaters: [point_list]}
  1694. for drill in self.exc_obj.drills:
  1695. if drill['tool'] in self.exc_obj.tools:
  1696. if self.units == 'IN':
  1697. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1698. else:
  1699. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1700. try:
  1701. self.points_edit[tool_dia].append(drill['point'])
  1702. except KeyError:
  1703. self.points_edit[tool_dia] = [drill['point']]
  1704. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1705. for slot in self.exc_obj.slots:
  1706. if slot['tool'] in self.exc_obj.tools:
  1707. if self.units == 'IN':
  1708. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1709. else:
  1710. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1711. try:
  1712. self.slot_points_edit[tool_dia].append({
  1713. "start": slot["start"],
  1714. "stop": slot["stop"]
  1715. })
  1716. except KeyError:
  1717. self.slot_points_edit[tool_dia] = [{
  1718. "start": slot["start"],
  1719. "stop": slot["stop"]
  1720. }]
  1721. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1722. for key in self.points_edit:
  1723. self.olddia_newdia[key] = key
  1724. for key in self.slot_points_edit:
  1725. if key not in self.olddia_newdia:
  1726. self.olddia_newdia[key] = key
  1727. sort_temp = []
  1728. for diam in self.olddia_newdia:
  1729. sort_temp.append(float(diam))
  1730. self.sorted_diameters = sorted(sort_temp)
  1731. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1732. if self.exc_obj.diameterless is False:
  1733. for i in range(len(self.sorted_diameters)):
  1734. tt_dia = self.sorted_diameters[i]
  1735. self.tool2tooldia[i + 1] = tt_dia
  1736. else:
  1737. # the Excellon object has diameters that are bogus information, added by the application because the
  1738. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1739. # but use the real order found in the exc_obj.tools
  1740. for k, v in self.exc_obj.tools.items():
  1741. if self.units == 'IN':
  1742. tool_dia = float('%.4f' % v['C'])
  1743. else:
  1744. tool_dia = float('%.2f' % v['C'])
  1745. self.tool2tooldia[int(k)] = tool_dia
  1746. # Init GUI
  1747. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1748. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1749. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1750. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1751. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1752. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1753. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1754. self.slot_length_entry.set_value(float(self.app.defaults['excellon_editor_slot_length']))
  1755. self.slot_axis_radio.set_value(self.app.defaults['excellon_editor_slot_direction'])
  1756. self.slot_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_angle']))
  1757. self.slot_array_size_entry.set_value(int(self.app.defaults['excellon_editor_slot_array_size']))
  1758. self.slot_array_axis_radio.set_value(self.app.defaults['excellon_editor_slot_lin_dir'])
  1759. self.slot_array_pitch_entry.set_value(float(self.app.defaults['excellon_editor_slot_lin_pitch']))
  1760. self.slot_array_linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_lin_angle']))
  1761. self.slot_array_direction_radio.set_value(self.app.defaults['excellon_editor_slot_circ_dir'])
  1762. self.slot_array_angle_entry.set_value(float(self.app.defaults['excellon_editor_slot_circ_angle']))
  1763. self.slot_array_circular_frame.hide()
  1764. self.slot_array_linear_frame.show()
  1765. def build_ui(self, first_run=None):
  1766. try:
  1767. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1768. self.tools_table_exc.itemChanged.disconnect()
  1769. except (TypeError, AttributeError):
  1770. pass
  1771. try:
  1772. self.tools_table_exc.cellPressed.disconnect()
  1773. except (TypeError, AttributeError):
  1774. pass
  1775. # updated units
  1776. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1777. # make a new name for the new Excellon object (the one with edited content)
  1778. self.edited_obj_name = self.exc_obj.options['name']
  1779. self.name_entry.set_value(self.edited_obj_name)
  1780. sort_temp = []
  1781. for diam in self.olddia_newdia:
  1782. sort_temp.append(float(diam))
  1783. self.sorted_diameters = sorted(sort_temp)
  1784. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1785. n = len(self.sorted_diameters)
  1786. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1787. self.tools_table_exc.setRowCount(n + 2)
  1788. self.tot_drill_cnt = 0
  1789. self.tot_slot_cnt = 0
  1790. self.tool_row = 0
  1791. # this variable will serve as the real tool_number
  1792. tool_id = 0
  1793. for tool_no in self.sorted_diameters:
  1794. tool_id += 1
  1795. drill_cnt = 0 # variable to store the nr of drills per tool
  1796. slot_cnt = 0 # variable to store the nr of slots per tool
  1797. # Find no of drills for the current tool
  1798. for tool_dia in self.points_edit:
  1799. if float(tool_dia) == tool_no:
  1800. drill_cnt = len(self.points_edit[tool_dia])
  1801. self.tot_drill_cnt += drill_cnt
  1802. try:
  1803. # Find no of slots for the current tool
  1804. for slot in self.slots:
  1805. if slot['tool'] == tool_no:
  1806. slot_cnt += 1
  1807. self.tot_slot_cnt += slot_cnt
  1808. except AttributeError:
  1809. # log.debug("No slots in the Excellon file")
  1810. # Find no of slots for the current tool
  1811. for tool_dia in self.slot_points_edit:
  1812. if float(tool_dia) == tool_no:
  1813. slot_cnt = len(self.slot_points_edit[tool_dia])
  1814. self.tot_slot_cnt += slot_cnt
  1815. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1816. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1817. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1818. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1819. # There are no drill bits in MM with more than 3 decimals diameter
  1820. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1821. if self.units == 'MM':
  1822. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1823. else:
  1824. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1825. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1826. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1827. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1828. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1829. if slot_cnt > 0:
  1830. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1831. else:
  1832. slot_count = QtWidgets.QTableWidgetItem('')
  1833. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1834. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1835. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1836. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1837. if first_run is True:
  1838. # set now the last tool selected
  1839. self.last_tool_selected = int(tool_id)
  1840. self.tool_row += 1
  1841. # make the diameter column editable
  1842. for row in range(self.tool_row):
  1843. self.tools_table_exc.item(row, 1).setFlags(
  1844. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1845. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1846. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1847. # add a last row with the Total number of drills
  1848. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1849. # it will have to have the foreground color (font color) white
  1850. empty = QtWidgets.QTableWidgetItem('9998')
  1851. empty.setForeground(QtGui.QColor(255, 255, 255))
  1852. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1853. empty_b = QtWidgets.QTableWidgetItem('')
  1854. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1855. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1856. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1857. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1858. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1859. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1860. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1861. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1862. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1863. font = QtGui.QFont()
  1864. font.setBold(True)
  1865. font.setWeight(75)
  1866. for k in [1, 2]:
  1867. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1868. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1869. self.tool_row += 1
  1870. # add a last row with the Total number of slots
  1871. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1872. # it will have to have the foreground color (font color) white
  1873. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1874. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1875. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1876. empty_3 = QtWidgets.QTableWidgetItem('')
  1877. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1878. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1879. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1880. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1881. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1882. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1883. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1884. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1885. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1886. for kl in [1, 2, 3]:
  1887. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1888. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1889. # all the tools are selected by default
  1890. self.tools_table_exc.selectColumn(0)
  1891. #
  1892. self.tools_table_exc.resizeColumnsToContents()
  1893. self.tools_table_exc.resizeRowsToContents()
  1894. vertical_header = self.tools_table_exc.verticalHeader()
  1895. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1896. vertical_header.hide()
  1897. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1898. horizontal_header = self.tools_table_exc.horizontalHeader()
  1899. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1900. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1901. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1902. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1903. # horizontal_header.setStretchLastSection(True)
  1904. # self.tools_table_exc.setSortingEnabled(True)
  1905. # sort by tool diameter
  1906. self.tools_table_exc.sortItems(1)
  1907. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1908. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1909. # use them
  1910. self.tool2tooldia.clear()
  1911. for row in range(self.tools_table_exc.rowCount() - 2):
  1912. tool = int(self.tools_table_exc.item(row, 0).text())
  1913. diameter = float(self.tools_table_exc.item(row, 1).text())
  1914. self.tool2tooldia[tool] = diameter
  1915. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1916. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1917. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1918. self.tools_table_exc.clearSelection()
  1919. # Remove anything else in the GUI Selected Tab
  1920. self.app.ui.selected_scroll_area.takeWidget()
  1921. # Put ourself in the GUI Selected Tab
  1922. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1923. # Switch notebook to Selected page
  1924. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1925. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1926. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1927. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1928. def on_tool_add(self, tooldia=None):
  1929. self.is_modified = True
  1930. if tooldia:
  1931. tool_dia = tooldia
  1932. else:
  1933. try:
  1934. tool_dia = float(self.addtool_entry.get_value())
  1935. except ValueError:
  1936. # try to convert comma to decimal point. if it's still not working error message and return
  1937. try:
  1938. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1939. except ValueError:
  1940. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1941. "use a number.")
  1942. )
  1943. return
  1944. if tool_dia not in self.olddia_newdia:
  1945. storage_elem = FlatCAMGeoEditor.make_storage()
  1946. self.storage_dict[tool_dia] = storage_elem
  1947. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1948. # each time a tool diameter is edited or added
  1949. self.olddia_newdia[tool_dia] = tool_dia
  1950. else:
  1951. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1952. "Save and reedit Excellon if you need to add this tool. ")
  1953. )
  1954. return
  1955. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1956. # we add a new entry in the tool2tooldia dict
  1957. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1958. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia),
  1959. units=str(self.units)))
  1960. self.build_ui()
  1961. # make a quick sort through the tool2tooldia dict so we find which row to select
  1962. row_to_be_selected = None
  1963. for key in sorted(self.tool2tooldia):
  1964. if self.tool2tooldia[key] == tool_dia:
  1965. row_to_be_selected = int(key) - 1
  1966. self.last_tool_selected = int(key)
  1967. break
  1968. self.tools_table_exc.selectRow(row_to_be_selected)
  1969. def on_tool_delete(self, dia=None):
  1970. self.is_modified = True
  1971. deleted_tool_dia_list = []
  1972. try:
  1973. if dia is None or dia is False:
  1974. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1975. for index in self.tools_table_exc.selectionModel().selectedRows():
  1976. row = index.row()
  1977. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1978. else:
  1979. if isinstance(dia, list):
  1980. for dd in dia:
  1981. deleted_tool_dia_list.append(float('%.4f' % dd))
  1982. else:
  1983. deleted_tool_dia_list.append(float('%.4f' % dia))
  1984. except Exception as e:
  1985. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1986. return
  1987. for deleted_tool_dia in deleted_tool_dia_list:
  1988. # delete de tool offset
  1989. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1990. # delete the storage used for that tool
  1991. storage_elem = FlatCAMGeoEditor.make_storage()
  1992. self.storage_dict[deleted_tool_dia] = storage_elem
  1993. self.storage_dict.pop(deleted_tool_dia, None)
  1994. # I've added this flag_del variable because dictionary don't like
  1995. # having keys deleted while iterating through them
  1996. flag_del = []
  1997. # self.points_edit.pop(deleted_tool_dia, None)
  1998. for deleted_tool in self.tool2tooldia:
  1999. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  2000. flag_del.append(deleted_tool)
  2001. if flag_del:
  2002. for tool_to_be_deleted in flag_del:
  2003. # delete the tool
  2004. self.tool2tooldia.pop(tool_to_be_deleted, None)
  2005. # delete also the drills from points_edit dict just in case we add the tool again,
  2006. # we don't want to show the number of drills from before was deleter
  2007. self.points_edit[deleted_tool_dia] = []
  2008. self.olddia_newdia.pop(deleted_tool_dia, None)
  2009. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(
  2010. del_dia=str(deleted_tool_dia),
  2011. units=str(self.units)))
  2012. self.replot()
  2013. # self.app.inform.emit("Could not delete selected tool")
  2014. self.build_ui()
  2015. def on_tool_edit(self, item_changed):
  2016. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2017. try:
  2018. self.tools_table_exc.itemChanged.disconnect()
  2019. except TypeError:
  2020. pass
  2021. try:
  2022. self.tools_table_exc.cellPressed.disconnect()
  2023. except TypeError:
  2024. pass
  2025. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  2026. self.is_modified = True
  2027. new_dia = None
  2028. if self.tools_table_exc.currentItem() is not None:
  2029. try:
  2030. new_dia = float(self.tools_table_exc.currentItem().text())
  2031. except ValueError as e:
  2032. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  2033. self.tools_table_exc.setCurrentItem(None)
  2034. return
  2035. row_of_item_changed = self.tools_table_exc.currentRow()
  2036. # rows start with 0, tools start with 1 so we adjust the value by 1
  2037. key_in_tool2tooldia = row_of_item_changed + 1
  2038. old_dia = self.tool2tooldia[key_in_tool2tooldia]
  2039. # SOURCE storage
  2040. source_storage = self.storage_dict[old_dia]
  2041. # DESTINATION storage
  2042. # tool diameter is not used so we create a new tool with the desired diameter
  2043. if new_dia not in self.olddia_newdia:
  2044. destination_storage = FlatCAMGeoEditor.make_storage()
  2045. self.storage_dict[new_dia] = destination_storage
  2046. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2047. # each time a tool diameter is edited or added
  2048. self.olddia_newdia[new_dia] = new_dia
  2049. else:
  2050. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  2051. destination_storage = self.storage_dict[new_dia]
  2052. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2053. # we add a new entry in the tool2tooldia dict
  2054. self.tool2tooldia[len(self.olddia_newdia)] = new_dia
  2055. # CHANGE the elements geometry according to the new diameter
  2056. factor = new_dia / old_dia
  2057. new_geo = Polygon()
  2058. for shape_exc in source_storage.get_objects():
  2059. geo_list = []
  2060. if isinstance(shape_exc.geo, MultiLineString):
  2061. for subgeo in shape_exc.geo:
  2062. geo_list.append(affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center'))
  2063. new_geo = MultiLineString(geo_list)
  2064. elif isinstance(shape_exc.geo, Polygon):
  2065. # I don't have any info regarding the angle of the slot geometry, nor how thick it is or
  2066. # how long it is given the angle. So I will have to make an approximation because
  2067. # we need to conserve the slot length, we only resize the diameter for the tool
  2068. # Therefore scaling won't work and buffering will not work either.
  2069. # First we get the Linestring that is one that the original slot is built around with the
  2070. # tool having the diameter sel_dia
  2071. poly = shape_exc.geo
  2072. xmin, ymin, xmax, ymax = poly.bounds
  2073. # a line that is certain to be bigger than our slot because it's the diagonal
  2074. # of it's bounding box
  2075. poly_diagonal = LineString([(xmin, ymin), (xmax, ymax)])
  2076. poly_centroid = poly.centroid
  2077. # center of the slot geometry
  2078. poly_center = (poly_centroid.x, poly_centroid.y)
  2079. # make a list of intersections with the rotated line
  2080. list_of_cuttings = []
  2081. for angle in range(0, 359, 1):
  2082. rot_poly_diagonal = affinity.rotate(poly_diagonal, angle=angle, origin=poly_center)
  2083. cut_line = rot_poly_diagonal.intersection(poly)
  2084. cut_line_len = cut_line.length
  2085. list_of_cuttings.append(
  2086. (cut_line_len, cut_line)
  2087. )
  2088. # find the cut_line with the maximum length which is the LineString for which the start
  2089. # and stop point are the start and stop point of the slot as in the Gerber file
  2090. cut_line_with_max_length = max(list_of_cuttings, key=lambda i: i[0])[1]
  2091. # find the coordinates of this line
  2092. cut_line_with_max_length_coords = list(cut_line_with_max_length.coords)
  2093. # extract the first and last point of the line and build some buffered polygon circles
  2094. # around them
  2095. start_pt = Point(cut_line_with_max_length_coords[0])
  2096. stop_pt = Point(cut_line_with_max_length_coords[1])
  2097. start_cut_geo = start_pt.buffer(new_dia / 2)
  2098. stop_cut_geo = stop_pt.buffer(new_dia / 2)
  2099. # and we cut the above circle polygons from our line and get in this way a line around
  2100. # which we can build the new slot by buffering with the new tool diameter
  2101. new_line = cut_line_with_max_length.difference(start_cut_geo)
  2102. new_line = new_line.difference(stop_cut_geo)
  2103. # create the geometry for the resized slot by buffering with half of the
  2104. # new diameter value: new_dia
  2105. new_geo = new_line.buffer(new_dia / 2)
  2106. try:
  2107. self.points_edit.pop(old_dia, None)
  2108. except KeyError:
  2109. pass
  2110. try:
  2111. self.slot_points_edit.pop(old_dia, None)
  2112. except KeyError:
  2113. pass
  2114. # add bogus drill/slots points (for total count of drills/slots)
  2115. # for drills
  2116. if isinstance(shape_exc.geo, MultiLineString):
  2117. if new_dia not in self.points_edit:
  2118. self.points_edit[new_dia] = [(0, 0)]
  2119. else:
  2120. self.points_edit[new_dia].append((0, 0))
  2121. # for slots
  2122. if isinstance(shape_exc.geo, Polygon):
  2123. if new_dia not in self.slot_points_edit:
  2124. self.slot_points_edit[new_dia] = [(0, 0)]
  2125. else:
  2126. self.slot_points_edit[new_dia].append((0, 0))
  2127. self.add_exc_shape(shape=DrawToolShape(new_geo), storage=destination_storage)
  2128. # update the UI and the CANVAS
  2129. self.build_ui()
  2130. self.replot()
  2131. # delete the old tool
  2132. self.on_tool_delete(dia=old_dia)
  2133. # we reactivate the signals after the after the tool editing
  2134. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2135. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2136. self.app.inform.emit(_("[success] Done. Tool edit completed."))
  2137. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  2138. def on_name_activate(self):
  2139. self.edited_obj_name = self.name_entry.get_value()
  2140. def activate(self):
  2141. # adjust the status of the menu entries related to the editor
  2142. self.app.ui.menueditedit.setDisabled(True)
  2143. self.app.ui.menueditok.setDisabled(False)
  2144. # adjust the visibility of some of the canvas context menu
  2145. self.app.ui.popmenu_edit.setVisible(False)
  2146. self.app.ui.popmenu_save.setVisible(True)
  2147. self.connect_canvas_event_handlers()
  2148. # initialize working objects
  2149. self.storage_dict = {}
  2150. self.current_storage = []
  2151. self.points_edit = {}
  2152. self.sorted_diameters = []
  2153. self.new_drills = []
  2154. self.new_tools = {}
  2155. self.new_slots = []
  2156. self.new_tool_offset = {}
  2157. self.olddia_newdia = {}
  2158. self.shapes.enabled = True
  2159. self.tool_shape.enabled = True
  2160. # self.app.app_cursor.enabled = True
  2161. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2162. self.app.ui.corner_snap_btn.setEnabled(True)
  2163. self.app.ui.snap_magnet.setVisible(True)
  2164. self.app.ui.corner_snap_btn.setVisible(True)
  2165. self.app.ui.exc_editor_menu.setDisabled(False)
  2166. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  2167. self.app.ui.update_obj_btn.setEnabled(True)
  2168. self.app.ui.e_editor_cmenu.setEnabled(True)
  2169. self.app.ui.exc_edit_toolbar.setDisabled(False)
  2170. self.app.ui.exc_edit_toolbar.setVisible(True)
  2171. # self.app.ui.snap_toolbar.setDisabled(False)
  2172. # start with GRID toolbar activated
  2173. if self.app.ui.grid_snap_btn.isChecked() is False:
  2174. self.app.ui.grid_snap_btn.trigger()
  2175. self.app.ui.popmenu_disable.setVisible(False)
  2176. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2177. self.app.ui.popmenu_properties.setVisible(False)
  2178. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  2179. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2180. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2181. # Tell the App that the editor is active
  2182. self.editor_active = True
  2183. # show the UI
  2184. self.drills_frame.show()
  2185. def deactivate(self):
  2186. try:
  2187. QtGui.QGuiApplication.restoreOverrideCursor()
  2188. except Exception as e:
  2189. pass
  2190. # adjust the status of the menu entries related to the editor
  2191. self.app.ui.menueditedit.setDisabled(False)
  2192. self.app.ui.menueditok.setDisabled(True)
  2193. # adjust the visibility of some of the canvas context menu
  2194. self.app.ui.popmenu_edit.setVisible(True)
  2195. self.app.ui.popmenu_save.setVisible(False)
  2196. self.disconnect_canvas_event_handlers()
  2197. self.clear()
  2198. self.app.ui.exc_edit_toolbar.setDisabled(True)
  2199. settings = QSettings("Open Source", "FlatCAM")
  2200. if settings.contains("layout"):
  2201. layout = settings.value('layout', type=str)
  2202. if layout == 'standard':
  2203. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2204. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2205. self.app.ui.corner_snap_btn.setEnabled(False)
  2206. self.app.ui.snap_magnet.setVisible(False)
  2207. self.app.ui.corner_snap_btn.setVisible(False)
  2208. elif layout == 'compact':
  2209. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2210. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2211. self.app.ui.corner_snap_btn.setEnabled(False)
  2212. self.app.ui.snap_magnet.setVisible(True)
  2213. self.app.ui.corner_snap_btn.setVisible(True)
  2214. else:
  2215. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2216. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2217. self.app.ui.corner_snap_btn.setEnabled(False)
  2218. self.app.ui.snap_magnet.setVisible(False)
  2219. self.app.ui.corner_snap_btn.setVisible(False)
  2220. # set the Editor Toolbar visibility to what was before entering in the Editor
  2221. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2222. else self.app.ui.exc_edit_toolbar.setVisible(True)
  2223. # Disable visuals
  2224. self.shapes.enabled = False
  2225. self.tool_shape.enabled = False
  2226. # self.app.app_cursor.enabled = False
  2227. # Tell the app that the editor is no longer active
  2228. self.editor_active = False
  2229. self.app.ui.exc_editor_menu.setDisabled(True)
  2230. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  2231. self.app.ui.update_obj_btn.setEnabled(False)
  2232. self.app.ui.popmenu_disable.setVisible(True)
  2233. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2234. self.app.ui.popmenu_properties.setVisible(True)
  2235. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2236. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2237. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2238. # Show original geometry
  2239. if self.exc_obj:
  2240. self.exc_obj.visible = True
  2241. # hide the UI
  2242. self.drills_frame.hide()
  2243. def connect_canvas_event_handlers(self):
  2244. # ## Canvas events
  2245. # first connect to new, then disconnect the old handlers
  2246. # don't ask why but if there is nothing connected I've seen issues
  2247. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2248. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2249. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  2250. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2251. # but those from FlatCAMGeoEditor
  2252. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2253. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2254. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2255. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2256. self.app.collection.view.clicked.disconnect()
  2257. self.app.ui.popmenu_copy.triggered.disconnect()
  2258. self.app.ui.popmenu_delete.triggered.disconnect()
  2259. self.app.ui.popmenu_move.triggered.disconnect()
  2260. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  2261. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2262. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  2263. # Excellon Editor
  2264. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  2265. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  2266. def disconnect_canvas_event_handlers(self):
  2267. # we restore the key and mouse control to FlatCAMApp method
  2268. # first connect to new, then disconnect the old handlers
  2269. # don't ask why but if there is nothing connected I've seen issues
  2270. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2271. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2272. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2273. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2274. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2275. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2276. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2277. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  2278. try:
  2279. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  2280. except (TypeError, AttributeError):
  2281. pass
  2282. try:
  2283. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2284. except (TypeError, AttributeError):
  2285. pass
  2286. try:
  2287. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  2288. except (TypeError, AttributeError):
  2289. pass
  2290. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2291. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2292. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2293. # Excellon Editor
  2294. try:
  2295. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2296. except (TypeError, AttributeError):
  2297. pass
  2298. try:
  2299. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2300. except (TypeError, AttributeError):
  2301. pass
  2302. def clear(self):
  2303. self.active_tool = None
  2304. # self.shape_buffer = []
  2305. self.selected = []
  2306. self.points_edit = {}
  2307. self.new_tools = {}
  2308. self.new_drills = []
  2309. # self.storage_dict = {}
  2310. self.shapes.clear(update=True)
  2311. self.tool_shape.clear(update=True)
  2312. # self.storage = FlatCAMExcEditor.make_storage()
  2313. self.replot()
  2314. def edit_fcexcellon(self, exc_obj):
  2315. """
  2316. Imports the geometry from the given FlatCAM Excellon object
  2317. into the editor.
  2318. :param exc_obj: FlatCAMExcellon object
  2319. :return: None
  2320. """
  2321. assert isinstance(exc_obj, Excellon), \
  2322. "Expected an Excellon Object, got %s" % type(exc_obj)
  2323. self.deactivate()
  2324. self.activate()
  2325. # Hide original geometry
  2326. self.exc_obj = exc_obj
  2327. exc_obj.visible = False
  2328. self.points_edit = {}
  2329. self.slot_points_edit = {}
  2330. # Set selection tolerance
  2331. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2332. self.select_tool("drill_select")
  2333. self.set_ui()
  2334. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2335. self.build_ui(first_run=True)
  2336. # we activate this after the initial build as we don't need to see the tool been populated
  2337. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2338. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2339. # and then add it to the storage elements (each storage elements is a member of a list
  2340. for tool_dia in self.points_edit:
  2341. storage_elem = FlatCAMGeoEditor.make_storage()
  2342. for point in self.points_edit[tool_dia]:
  2343. # make a '+' sign, the line length is the tool diameter
  2344. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2345. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2346. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2347. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2348. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2349. if shape_geo is not None:
  2350. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2351. self.storage_dict[tool_dia] = storage_elem
  2352. # slots
  2353. for tool_dia in self.slot_points_edit:
  2354. buf_value = float(tool_dia) / 2
  2355. for elem_dict in self.slot_points_edit[tool_dia]:
  2356. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2357. shape_geo = line_geo.buffer(buf_value)
  2358. if tool_dia not in self.storage_dict:
  2359. storage_elem = FlatCAMGeoEditor.make_storage()
  2360. self.storage_dict[tool_dia] = storage_elem
  2361. if shape_geo is not None:
  2362. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2363. self.replot()
  2364. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2365. if not self.tool2tooldia:
  2366. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2367. def update_fcexcellon(self, exc_obj):
  2368. """
  2369. Create a new Excellon object that contain the edited content of the source Excellon object
  2370. :param exc_obj: FlatCAMExcellon
  2371. :return: None
  2372. """
  2373. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2374. # the values of this dict are coordinates of the holes (drills)
  2375. edited_points = {}
  2376. """
  2377. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2378. - the dict element of the list has the structure
  2379. ================ ====================================
  2380. Key Value
  2381. ================ ====================================
  2382. start (Shapely.Point) Start point of the slot
  2383. stop (Shapely.Point) Stop point of the slot
  2384. ================ ====================================
  2385. """
  2386. edited_slot_points = {}
  2387. for storage_tooldia in self.storage_dict:
  2388. for x in self.storage_dict[storage_tooldia].get_objects():
  2389. if isinstance(x.geo, MultiLineString):
  2390. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2391. # each MultiLineString is made out of Linestrings
  2392. # select first Linestring object in the current MultiLineString
  2393. first_linestring = x.geo[0]
  2394. # get it's coordinates
  2395. first_linestring_coords = first_linestring.coords
  2396. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2397. y_coord = first_linestring_coords[0][1]
  2398. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2399. # edited_points dictionary
  2400. point = (x_coord, y_coord)
  2401. if storage_tooldia not in edited_points:
  2402. edited_points[storage_tooldia] = [point]
  2403. else:
  2404. edited_points[storage_tooldia].append(point)
  2405. elif isinstance(x.geo, Polygon):
  2406. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2407. # edited_points dictionary
  2408. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2409. # diameter
  2410. radius = float(storage_tooldia) / 2
  2411. radius = radius - 0.0000001
  2412. poly = x.geo
  2413. poly = poly.buffer(-radius)
  2414. xmin, ymin, xmax, ymax = poly.bounds
  2415. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2416. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2417. if line_one < line_two:
  2418. point_elem = {
  2419. "start": (xmin, ymax),
  2420. "stop": (xmax, ymin)
  2421. }
  2422. else:
  2423. point_elem = {
  2424. "start": (xmin, ymin),
  2425. "stop": (xmax, ymax)
  2426. }
  2427. if storage_tooldia not in edited_slot_points:
  2428. edited_slot_points[storage_tooldia] = [point_elem]
  2429. else:
  2430. edited_slot_points[storage_tooldia].append(point_elem)
  2431. # recreate the drills and tools to be added to the new Excellon edited object
  2432. # first, we look in the tool table if one of the tool diameters was changed then
  2433. # append that a tuple formed by (old_dia, edited_dia) to a list
  2434. changed_key = set()
  2435. for initial_dia in self.olddia_newdia:
  2436. edited_dia = self.olddia_newdia[initial_dia]
  2437. if edited_dia != initial_dia:
  2438. # for drills
  2439. for old_dia in edited_points:
  2440. if old_dia == initial_dia:
  2441. changed_key.add((old_dia, edited_dia))
  2442. # for slots
  2443. for old_dia in edited_slot_points:
  2444. if old_dia == initial_dia:
  2445. changed_key.add((old_dia, edited_dia))
  2446. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2447. # (and we have to add it)
  2448. # because in case we have drill points it will have to be already added in edited_points
  2449. # if initial_dia not in edited_points.keys():
  2450. # edited_points[initial_dia] = []
  2451. for el in changed_key:
  2452. edited_points[el[1]] = edited_points.pop(el[0])
  2453. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2454. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2455. # ordered_edited_points is a ordered list of tuples;
  2456. # element[0] of the tuple is the diameter and
  2457. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2458. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2459. current_tool = 0
  2460. for tool_dia in ordered_edited_points:
  2461. current_tool += 1
  2462. # create the self.tools for the new Excellon object (the one with edited content)
  2463. name = str(current_tool)
  2464. spec = {"C": float(tool_dia[0])}
  2465. self.new_tools[name] = spec
  2466. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2467. self.new_tools[name]['solid_geometry'] = []
  2468. # create the self.drills for the new Excellon object (the one with edited content)
  2469. for point in tool_dia[1]:
  2470. self.new_drills.append(
  2471. {
  2472. 'point': Point(point),
  2473. 'tool': str(current_tool)
  2474. }
  2475. )
  2476. # repopulate the 'solid_geometry' for each tool
  2477. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2478. self.new_tools[name]['solid_geometry'].append(poly)
  2479. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2480. for tool_dia in ordered_edited_slot_points:
  2481. tool_exist_flag = False
  2482. for tool in self.new_tools:
  2483. if tool_dia[0] == self.new_tools[tool]["C"]:
  2484. current_tool = tool
  2485. tool_exist_flag = True
  2486. break
  2487. if tool_exist_flag is False:
  2488. current_tool += 1
  2489. # create the self.tools for the new Excellon object (the one with edited content)
  2490. name = str(current_tool)
  2491. spec = {"C": float(tool_dia[0])}
  2492. self.new_tools[name] = spec
  2493. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2494. self.new_tools[name]['solid_geometry'] = []
  2495. # create the self.slots for the new Excellon object (the one with edited content)
  2496. for coord_dict in tool_dia[1]:
  2497. self.new_slots.append(
  2498. {
  2499. 'start': Point(coord_dict['start']),
  2500. 'stop': Point(coord_dict['stop']),
  2501. 'tool': str(current_tool)
  2502. }
  2503. )
  2504. # repopulate the 'solid_geometry' for each tool
  2505. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2506. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2507. )
  2508. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2509. if self.is_modified is True:
  2510. if "_edit" in self.edited_obj_name:
  2511. try:
  2512. idd = int(self.edited_obj_name[-1]) + 1
  2513. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2514. except ValueError:
  2515. self.edited_obj_name += "_1"
  2516. else:
  2517. self.edited_obj_name += "_edit"
  2518. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2519. 'params': [self.edited_obj_name]})
  2520. self.new_tool_offset = self.exc_obj.tool_offset
  2521. # reset the tool table
  2522. self.tools_table_exc.clear()
  2523. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2524. self.last_tool_selected = None
  2525. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2526. self.app.collection.set_active(self.exc_obj.options['name'])
  2527. self.app.collection.delete_active()
  2528. # restore GUI to the Selected TAB
  2529. # Remove anything else in the GUI
  2530. self.app.ui.tool_scroll_area.takeWidget()
  2531. # Switch notebook to Selected page
  2532. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2533. def update_options(self, obj):
  2534. try:
  2535. if not obj.options:
  2536. obj.options = {}
  2537. obj.options['xmin'] = 0
  2538. obj.options['ymin'] = 0
  2539. obj.options['xmax'] = 0
  2540. obj.options['ymax'] = 0
  2541. return True
  2542. else:
  2543. return False
  2544. except AttributeError:
  2545. obj.options = {}
  2546. return True
  2547. def new_edited_excellon(self, outname):
  2548. """
  2549. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2550. :param outname: Name of the resulting object. None causes the
  2551. name to be that of the file.
  2552. :type outname: str
  2553. :return: None
  2554. """
  2555. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2556. self.exc_obj.options['name'])
  2557. # How the object should be initialized
  2558. def obj_init(excellon_obj, app_obj):
  2559. # self.progress.emit(20)
  2560. excellon_obj.drills = self.new_drills
  2561. excellon_obj.tools = self.new_tools
  2562. excellon_obj.slots = self.new_slots
  2563. excellon_obj.tool_offset = self.new_tool_offset
  2564. excellon_obj.options['name'] = outname
  2565. try:
  2566. excellon_obj.create_geometry()
  2567. except KeyError:
  2568. self.app.inform.emit(
  2569. _("[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  2570. )
  2571. except:
  2572. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2573. msg += traceback.format_exc()
  2574. app_obj.inform.emit(msg)
  2575. raise
  2576. # raise
  2577. with self.app.proc_container.new(_("Creating Excellon.")):
  2578. try:
  2579. self.app.new_object("excellon", outname, obj_init)
  2580. except Exception as e:
  2581. log.error("Error on object creation: %s" % str(e))
  2582. self.app.progress.emit(100)
  2583. return
  2584. self.app.inform.emit(_("[success] Excellon editing finished."))
  2585. # self.progress.emit(100)
  2586. def on_tool_select(self, tool):
  2587. """
  2588. Behavior of the toolbar. Tool initialization.
  2589. :rtype : None
  2590. """
  2591. current_tool = tool
  2592. self.app.log.debug("on_tool_select('%s')" % tool)
  2593. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2594. # self.draw_app.select_tool('drill_select')
  2595. self.complete = True
  2596. current_tool = 'drill_select'
  2597. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  2598. # This is to make the group behave as radio group
  2599. if current_tool in self.tools_exc:
  2600. if self.tools_exc[current_tool]["button"].isChecked():
  2601. self.app.log.debug("%s is checked." % current_tool)
  2602. for t in self.tools_exc:
  2603. if t != current_tool:
  2604. self.tools_exc[t]["button"].setChecked(False)
  2605. # this is where the Editor toolbar classes (button's) are instantiated
  2606. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2607. # self.app.inform.emit(self.active_tool.start_msg)
  2608. else:
  2609. self.app.log.debug("%s is NOT checked." % current_tool)
  2610. for t in self.tools_exc:
  2611. self.tools_exc[t]["button"].setChecked(False)
  2612. self.select_tool('drill_select')
  2613. self.active_tool = FCDrillSelect(self)
  2614. def on_row_selected(self, row, col):
  2615. if col == 0:
  2616. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2617. if self.app.defaults["global_mselect_key"] == 'Control':
  2618. modifier_to_use = Qt.ControlModifier
  2619. else:
  2620. modifier_to_use = Qt.ShiftModifier
  2621. if key_modifier == modifier_to_use:
  2622. pass
  2623. else:
  2624. self.selected = []
  2625. try:
  2626. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2627. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2628. for obj in self.storage_dict[selected_dia].get_objects():
  2629. self.selected.append(obj)
  2630. except Exception as e:
  2631. self.app.log.debug(str(e))
  2632. self.replot()
  2633. def toolbar_tool_toggle(self, key):
  2634. self.options[key] = self.sender().isChecked()
  2635. if self.options[key] is True:
  2636. return 1
  2637. else:
  2638. return 0
  2639. def on_canvas_click(self, event):
  2640. """
  2641. event.x and .y have canvas coordinates
  2642. event.xdata and .ydata have plot coordinates
  2643. :param event: Event object dispatched by VisPy
  2644. :return: None
  2645. """
  2646. self.pos = self.canvas.translate_coords(event.pos)
  2647. if self.app.grid_status() == True:
  2648. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2649. self.app.app_cursor.enabled = True
  2650. # Update cursor
  2651. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2652. size=20)
  2653. else:
  2654. self.pos = (self.pos[0], self.pos[1])
  2655. self.app.app_cursor.enabled = False
  2656. if event.button is 1:
  2657. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2658. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2659. # Selection with left mouse button
  2660. if self.active_tool is not None and event.button is 1:
  2661. # Dispatch event to active_tool
  2662. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2663. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2664. # If it is a shape generating tool
  2665. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2666. if self.current_storage is not None:
  2667. self.on_exc_shape_complete(self.current_storage)
  2668. self.build_ui()
  2669. # MS: always return to the Select Tool if modifier key is not pressed
  2670. # else return to the current tool
  2671. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2672. if self.app.defaults["global_mselect_key"] == 'Control':
  2673. modifier_to_use = Qt.ControlModifier
  2674. else:
  2675. modifier_to_use = Qt.ShiftModifier
  2676. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2677. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2678. if key_modifier == modifier_to_use:
  2679. self.select_tool(self.active_tool.name)
  2680. else:
  2681. # return to Select tool but not for FCDrillAdd or FCSlot
  2682. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2683. self.select_tool(self.active_tool.name)
  2684. else:
  2685. self.select_tool("drill_select")
  2686. return
  2687. if isinstance(self.active_tool, FCDrillSelect):
  2688. # self.app.log.debug("Replotting after click.")
  2689. self.replot()
  2690. else:
  2691. self.app.log.debug("No active tool to respond to click!")
  2692. def on_exc_shape_complete(self, storage):
  2693. self.app.log.debug("on_shape_complete()")
  2694. # Add shape
  2695. if type(storage) is list:
  2696. for item_storage in storage:
  2697. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2698. else:
  2699. self.add_exc_shape(self.active_tool.geometry, storage)
  2700. # Remove any utility shapes
  2701. self.delete_utility_geometry()
  2702. self.tool_shape.clear(update=True)
  2703. # Replot and reset tool.
  2704. self.replot()
  2705. # self.active_tool = type(self.active_tool)(self)
  2706. def add_exc_shape(self, shape, storage):
  2707. """
  2708. Adds a shape to a specified shape storage.
  2709. :param shape: Shape to be added.
  2710. :type shape: DrawToolShape
  2711. :param storage: object where to store the shapes
  2712. :return: None
  2713. """
  2714. # List of DrawToolShape?
  2715. if isinstance(shape, list):
  2716. for subshape in shape:
  2717. self.add_exc_shape(subshape, storage)
  2718. return
  2719. assert isinstance(shape, DrawToolShape), \
  2720. "Expected a DrawToolShape, got %s" % str(type(shape))
  2721. assert shape.geo is not None, \
  2722. "Shape object has empty geometry (None)"
  2723. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2724. "Shape objects has empty geometry ([])"
  2725. if isinstance(shape, DrawToolUtilityShape):
  2726. self.utility.append(shape)
  2727. else:
  2728. storage.insert(shape) # TODO: Check performance
  2729. def add_shape(self, shape):
  2730. """
  2731. Adds a shape to the shape storage.
  2732. :param shape: Shape to be added.
  2733. :type shape: DrawToolShape
  2734. :return: None
  2735. """
  2736. # List of DrawToolShape?
  2737. if isinstance(shape, list):
  2738. for subshape in shape:
  2739. self.add_shape(subshape)
  2740. return
  2741. assert isinstance(shape, DrawToolShape), \
  2742. "Expected a DrawToolShape, got %s" % type(shape)
  2743. assert shape.geo is not None, \
  2744. "Shape object has empty geometry (None)"
  2745. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2746. "Shape objects has empty geometry ([])"
  2747. if isinstance(shape, DrawToolUtilityShape):
  2748. self.utility.append(shape)
  2749. else:
  2750. self.storage.insert(shape) # TODO: Check performance
  2751. def on_exc_click_release(self, event):
  2752. """
  2753. Handler of the "mouse_release" event.
  2754. It will pop-up the context menu on right mouse click unless there was a panning move (decided in the
  2755. "mouse_move" event handler) and only if the current tool is the Select tool.
  2756. It will 'close' a Editor tool if it is the case.
  2757. :param event: Event object dispatched by VisPy SceneCavas
  2758. :return: None
  2759. """
  2760. pos_canvas = self.canvas.translate_coords(event.pos)
  2761. if self.app.grid_status() == True:
  2762. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2763. else:
  2764. pos = (pos_canvas[0], pos_canvas[1])
  2765. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2766. # canvas menu
  2767. try:
  2768. if event.button == 2: # right click
  2769. if self.app.ui.popMenu.mouse_is_panning is False:
  2770. try:
  2771. QtGui.QGuiApplication.restoreOverrideCursor()
  2772. except Exception as e:
  2773. pass
  2774. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2775. self.active_tool.complete = True
  2776. self.in_action = False
  2777. self.delete_utility_geometry()
  2778. self.app.inform.emit(_("[success] Done."))
  2779. self.select_tool('drill_select')
  2780. else:
  2781. if isinstance(self.active_tool, FCDrillAdd):
  2782. self.active_tool.complete = True
  2783. self.in_action = False
  2784. self.delete_utility_geometry()
  2785. self.app.inform.emit(_("[success] Done."))
  2786. self.select_tool('drill_select')
  2787. self.app.cursor = QtGui.QCursor()
  2788. self.app.populate_cmenu_grids()
  2789. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2790. except Exception as e:
  2791. log.warning("Error: %s" % str(e))
  2792. raise
  2793. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2794. # selection and then select a type of selection ("enclosing" or "touching")
  2795. try:
  2796. if event.button == 1: # left click
  2797. if self.app.selection_type is not None:
  2798. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2799. self.app.selection_type = None
  2800. elif isinstance(self.active_tool, FCDrillSelect):
  2801. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2802. # if there are selected objects then plot them
  2803. if self.selected:
  2804. self.replot()
  2805. except Exception as e:
  2806. log.warning("Error: %s" % str(e))
  2807. raise
  2808. def draw_selection_area_handler(self, start, end, sel_type):
  2809. """
  2810. This function is called whenever we have a left mouse click release and only we have a left mouse click drag,
  2811. be it from left to right or from right to left. The direction of the drag is decided in the "mouse_move"
  2812. event handler.
  2813. Pressing a modifier key (eg. Ctrl, Shift or Alt) will change the behavior of the selection.
  2814. Depending on which tool belongs the selected shapes, the corresponding rows in the Tools Table are selected or
  2815. deselected.
  2816. :param start: mouse position when the selection LMB click was done
  2817. :param end: mouse position when the left mouse button is released
  2818. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2819. :return:
  2820. """
  2821. start_pos = (start[0], start[1])
  2822. end_pos = (end[0], end[1])
  2823. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2824. modifiers = None
  2825. # delete the selection shape that was just drawn, we no longer need it
  2826. self.app.delete_selection_shape()
  2827. # detect if a modifier key was pressed while the left mouse button was released
  2828. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2829. if self.modifiers == QtCore.Qt.ShiftModifier:
  2830. modifiers = 'Shift'
  2831. elif self.modifiers == QtCore.Qt.ControlModifier:
  2832. modifiers = 'Control'
  2833. if modifiers == self.app.defaults["global_mselect_key"]:
  2834. for storage in self.storage_dict:
  2835. for obj in self.storage_dict[storage].get_objects():
  2836. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2837. (sel_type is False and poly_selection.intersects(obj.geo)):
  2838. if obj in self.selected:
  2839. # remove the shape object from the selected shapes storage
  2840. self.selected.remove(obj)
  2841. else:
  2842. # add the shape object to the selected shapes storage
  2843. self.selected.append(obj)
  2844. else:
  2845. # clear the selection shapes storage
  2846. self.selected = []
  2847. # then add to the selection shapes storage the shapes that are included (touched) by the selection rectangle
  2848. for storage in self.storage_dict:
  2849. for obj in self.storage_dict[storage].get_objects():
  2850. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2851. (sel_type is False and poly_selection.intersects(obj.geo)):
  2852. self.selected.append(obj)
  2853. try:
  2854. self.tools_table_exc.cellPressed.disconnect()
  2855. except Exception as e:
  2856. pass
  2857. # first deselect all rows (tools) in the Tools Table
  2858. self.tools_table_exc.clearSelection()
  2859. # and select the rows (tools) in the tool table according to the diameter(s) of the selected shape(s)
  2860. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2861. for storage in self.storage_dict:
  2862. for shape_s in self.selected:
  2863. if shape_s in self.storage_dict[storage].get_objects():
  2864. for key_tool_nr in self.tool2tooldia:
  2865. if self.tool2tooldia[key_tool_nr] == storage:
  2866. row_to_sel = key_tool_nr - 1
  2867. # item = self.tools_table_exc.item(row_to_sel, 1)
  2868. # self.tools_table_exc.setCurrentItem(item)
  2869. # item.setSelected(True)
  2870. # if the row to be selected is not already in the selected rows then select it
  2871. # otherwise don't do it as it seems that we have a toggle effect
  2872. if row_to_sel not in set(index.row() for index in self.tools_table_exc.selectedIndexes()):
  2873. self.tools_table_exc.selectRow(row_to_sel)
  2874. self.last_tool_selected = int(key_tool_nr)
  2875. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2876. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2877. self.replot()
  2878. def on_canvas_move(self, event):
  2879. """
  2880. Called on 'mouse_move' event.
  2881. It updates the mouse cursor if the grid snapping is ON.
  2882. 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
  2883. class object which is used in the "mouse_release" handler to decide if to pop-up the context menu or not.
  2884. It draws utility_geometry for the Editor tools.
  2885. Update the position labels from status bar.
  2886. Decide if we have a right to left or a left to right mouse drag with left mouse button and call a function
  2887. that will draw a selection shape on canvas.
  2888. event.pos have canvas screen coordinates
  2889. :param event: Event object dispatched by VisPy SceneCavas
  2890. :return: None
  2891. """
  2892. pos = self.canvas.translate_coords(event.pos)
  2893. event.xdata, event.ydata = pos[0], pos[1]
  2894. self.x = event.xdata
  2895. self.y = event.ydata
  2896. self.app.ui.popMenu.mouse_is_panning = False
  2897. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2898. if event.button == 2 and event.is_dragging == 1:
  2899. self.app.ui.popMenu.mouse_is_panning = True
  2900. return
  2901. try:
  2902. x = float(event.xdata)
  2903. y = float(event.ydata)
  2904. except TypeError:
  2905. return
  2906. if self.active_tool is None:
  2907. return
  2908. # ## Snap coordinates
  2909. if self.app.grid_status() == True:
  2910. x, y = self.app.geo_editor.snap(x, y)
  2911. self.app.app_cursor.enabled = True
  2912. # Update cursor
  2913. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2914. else:
  2915. self.app.app_cursor.enabled = False
  2916. self.snap_x = x
  2917. self.snap_y = y
  2918. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2919. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2920. "<b>Y</b>: %.4f" % (x, y))
  2921. if self.pos is None:
  2922. self.pos = (0, 0)
  2923. dx = x - self.pos[0]
  2924. dy = y - self.pos[1]
  2925. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2926. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2927. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2928. # ## Utility geometry (animated)
  2929. geo = self.active_tool.utility_geometry(data=(x, y))
  2930. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2931. # Remove any previous utility shape
  2932. self.tool_shape.clear(update=True)
  2933. self.draw_utility_geometry(geo=geo)
  2934. # ## Selection area on canvas section # ##
  2935. if event.is_dragging == 1 and event.button == 1:
  2936. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2937. # can create strange issues. Also for FCSlot and FCSlotArray
  2938. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray) or \
  2939. isinstance(self.active_tool, FCSlot) or isinstance(self.active_tool, FCSlotArray):
  2940. self.app.selection_type = None
  2941. else:
  2942. dx = pos[0] - self.pos[0]
  2943. self.app.delete_selection_shape()
  2944. if dx < 0:
  2945. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2946. color=self.app.defaults["global_alt_sel_line"],
  2947. face_color=self.app.defaults['global_alt_sel_fill'])
  2948. self.app.selection_type = False
  2949. else:
  2950. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2951. self.app.selection_type = True
  2952. else:
  2953. self.app.selection_type = None
  2954. # Update cursor
  2955. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2956. def on_canvas_key_release(self, event):
  2957. self.key = None
  2958. def draw_utility_geometry(self, geo):
  2959. # Add the new utility shape
  2960. try:
  2961. # this case is for the Font Parse
  2962. for el in list(geo.geo):
  2963. if type(el) == MultiPolygon:
  2964. for poly in el:
  2965. self.tool_shape.add(
  2966. shape=poly,
  2967. color=(self.app.defaults["global_draw_color"] + '80'),
  2968. update=False,
  2969. layer=0,
  2970. tolerance=None
  2971. )
  2972. elif type(el) == MultiLineString:
  2973. for linestring in el:
  2974. self.tool_shape.add(
  2975. shape=linestring,
  2976. color=(self.app.defaults["global_draw_color"] + '80'),
  2977. update=False,
  2978. layer=0,
  2979. tolerance=None
  2980. )
  2981. else:
  2982. self.tool_shape.add(
  2983. shape=el,
  2984. color=(self.app.defaults["global_draw_color"] + '80'),
  2985. update=False,
  2986. layer=0,
  2987. tolerance=None
  2988. )
  2989. except TypeError:
  2990. self.tool_shape.add(
  2991. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2992. update=False, layer=0, tolerance=None)
  2993. self.tool_shape.redraw()
  2994. def replot(self):
  2995. self.plot_all()
  2996. def plot_all(self):
  2997. """
  2998. Plots all shapes in the editor.
  2999. :return: None
  3000. :rtype: None
  3001. """
  3002. # self.app.log.debug("plot_all()")
  3003. self.shapes.clear(update=True)
  3004. for storage in self.storage_dict:
  3005. for shape_plus in self.storage_dict[storage].get_objects():
  3006. if shape_plus.geo is None:
  3007. continue
  3008. if shape_plus in self.selected:
  3009. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  3010. linewidth=2)
  3011. continue
  3012. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  3013. # for shape in self.storage.get_objects():
  3014. # if shape.geo is None: # TODO: This shouldn't have happened
  3015. # continue
  3016. #
  3017. # if shape in self.selected:
  3018. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3019. # continue
  3020. #
  3021. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3022. for shape_form in self.utility:
  3023. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  3024. continue
  3025. self.shapes.redraw()
  3026. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3027. """
  3028. Plots a geometric object or list of objects without rendering. Plotted objects
  3029. are returned as a list. This allows for efficient/animated rendering.
  3030. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3031. :param color: Shape color
  3032. :param linewidth: Width of lines in # of pixels.
  3033. :return: List of plotted elements.
  3034. """
  3035. plot_elements = []
  3036. if geometry is None:
  3037. geometry = self.active_tool.geometry
  3038. try:
  3039. for geo in geometry:
  3040. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3041. # ## Non-iterable
  3042. except TypeError:
  3043. # ## DrawToolShape
  3044. if isinstance(geometry, DrawToolShape):
  3045. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3046. # ## Polygon: Descend into exterior and each interior.
  3047. if type(geometry) == Polygon:
  3048. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3049. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3050. if type(geometry) == LineString or type(geometry) == LinearRing:
  3051. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0, tolerance=self.tolerance))
  3052. if type(geometry) == Point:
  3053. pass
  3054. return plot_elements
  3055. def on_shape_complete(self):
  3056. self.app.log.debug("on_shape_complete()")
  3057. # Add shape
  3058. self.add_shape(self.active_tool.geometry)
  3059. # Remove any utility shapes
  3060. self.delete_utility_geometry()
  3061. self.tool_shape.clear(update=True)
  3062. # Replot and reset tool.
  3063. self.replot()
  3064. # self.active_tool = type(self.active_tool)(self)
  3065. def get_selected(self):
  3066. """
  3067. Returns list of shapes that are selected in the editor.
  3068. :return: List of shapes.
  3069. """
  3070. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3071. return self.selected
  3072. def delete_selected(self):
  3073. temp_ref = [s for s in self.selected]
  3074. for shape_sel in temp_ref:
  3075. self.delete_shape(shape_sel)
  3076. self.selected = []
  3077. self.build_ui()
  3078. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  3079. def delete_shape(self, del_shape):
  3080. self.is_modified = True
  3081. if del_shape in self.utility:
  3082. self.utility.remove(del_shape)
  3083. return
  3084. for storage in self.storage_dict:
  3085. # try:
  3086. # self.storage_dict[storage].remove(shape)
  3087. # except:
  3088. # pass
  3089. if del_shape in self.storage_dict[storage].get_objects():
  3090. if isinstance(del_shape.geo, MultiLineString):
  3091. self.storage_dict[storage].remove(del_shape)
  3092. # a hack to make the tool_table display less drills per diameter
  3093. # self.points_edit it's only useful first time when we load the data into the storage
  3094. # but is still used as referecen when building tool_table in self.build_ui()
  3095. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  3096. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  3097. del self.points_edit[storage][0]
  3098. else:
  3099. self.storage_dict[storage].remove(del_shape)
  3100. del self.slot_points_edit[storage][0]
  3101. if del_shape in self.selected:
  3102. self.selected.remove(del_shape) # TODO: Check performance
  3103. def delete_utility_geometry(self):
  3104. for_deletion = [util_shape for util_shape in self.utility]
  3105. for util_shape in for_deletion:
  3106. self.delete_shape(util_shape)
  3107. self.tool_shape.clear(update=True)
  3108. self.tool_shape.redraw()
  3109. def on_delete_btn(self):
  3110. self.delete_selected()
  3111. self.replot()
  3112. def select_tool(self, toolname):
  3113. """
  3114. Selects a drawing tool. Impacts the object and GUI.
  3115. :param toolname: Name of the tool.
  3116. :return: None
  3117. """
  3118. self.tools_exc[toolname]["button"].setChecked(True)
  3119. self.on_tool_select(toolname)
  3120. def set_selected(self, sel_shape):
  3121. # Remove and add to the end.
  3122. if sel_shape in self.selected:
  3123. self.selected.remove(sel_shape)
  3124. self.selected.append(sel_shape)
  3125. def set_unselected(self, unsel_shape):
  3126. if unsel_shape in self.selected:
  3127. self.selected.remove(unsel_shape)
  3128. def on_array_type_combo(self):
  3129. if self.array_type_combo.currentIndex() == 0:
  3130. self.array_circular_frame.hide()
  3131. self.array_linear_frame.show()
  3132. else:
  3133. self.delete_utility_geometry()
  3134. self.array_circular_frame.show()
  3135. self.array_linear_frame.hide()
  3136. self.app.inform.emit(_("Click on the circular array Center position"))
  3137. def on_slot_array_type_combo(self):
  3138. if self.slot_array_type_combo.currentIndex() == 0:
  3139. self.slot_array_circular_frame.hide()
  3140. self.slot_array_linear_frame.show()
  3141. else:
  3142. self.delete_utility_geometry()
  3143. self.slot_array_circular_frame.show()
  3144. self.slot_array_linear_frame.hide()
  3145. self.app.inform.emit(_("Click on the circular array Center position"))
  3146. def on_linear_angle_radio(self):
  3147. val = self.drill_axis_radio.get_value()
  3148. if val == 'A':
  3149. self.linear_angle_spinner.show()
  3150. self.linear_angle_label.show()
  3151. else:
  3152. self.linear_angle_spinner.hide()
  3153. self.linear_angle_label.hide()
  3154. def on_slot_array_linear_angle_radio(self):
  3155. val = self.slot_array_axis_radio.get_value()
  3156. if val == 'A':
  3157. self.slot_array_linear_angle_spinner.show()
  3158. self.slot_array_linear_angle_label.show()
  3159. else:
  3160. self.slot_array_linear_angle_spinner.hide()
  3161. self.slot_array_linear_angle_label.hide()
  3162. def on_slot_angle_radio(self):
  3163. val = self.slot_axis_radio.get_value()
  3164. if val == 'A':
  3165. self.slot_angle_spinner.show()
  3166. self.slot_angle_label.show()
  3167. else:
  3168. self.slot_angle_spinner.hide()
  3169. self.slot_angle_label.hide()
  3170. def exc_add_drill(self):
  3171. self.select_tool('drill_add')
  3172. return
  3173. def exc_add_drill_array(self):
  3174. self.select_tool('drill_array')
  3175. return
  3176. def exc_add_slot(self):
  3177. self.select_tool('slot_add')
  3178. return
  3179. def exc_add_slot_array(self):
  3180. self.select_tool('slot_array')
  3181. return
  3182. def exc_resize_drills(self):
  3183. self.select_tool('drill_resize')
  3184. return
  3185. def exc_copy_drills(self):
  3186. self.select_tool('drill_copy')
  3187. return
  3188. def exc_move_drills(self):
  3189. self.select_tool('drill_move')
  3190. return
  3191. def get_shapely_list_bounds(geometry_list):
  3192. xmin = Inf
  3193. ymin = Inf
  3194. xmax = -Inf
  3195. ymax = -Inf
  3196. for gs in geometry_list:
  3197. try:
  3198. gxmin, gymin, gxmax, gymax = gs.bounds
  3199. xmin = min([xmin, gxmin])
  3200. ymin = min([ymin, gymin])
  3201. xmax = max([xmax, gxmax])
  3202. ymax = max([ymax, gymax])
  3203. except Exception as e:
  3204. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3205. return [xmin, ymin, xmax, ymax]
  3206. # EOF