FlatCAMExcEditor.py 168 KB

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