FlatCAMExcEditor.py 167 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969
  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] Done. %s' %
  879. _("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. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1641. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1642. self.app.pool_recreated.connect(self.pool_recreated)
  1643. # Remove from scene
  1644. self.shapes.enabled = False
  1645. self.tool_shape.enabled = False
  1646. # ## List of selected shapes.
  1647. self.selected = []
  1648. self.move_timer = QtCore.QTimer()
  1649. self.move_timer.setSingleShot(True)
  1650. self.key = None # Currently pressed key
  1651. self.modifiers = None
  1652. self.x = None # Current mouse cursor pos
  1653. self.y = None
  1654. # Current snapped mouse pos
  1655. self.snap_x = None
  1656. self.snap_y = None
  1657. self.pos = None
  1658. self.complete = False
  1659. def make_callback(thetool):
  1660. def f():
  1661. self.on_tool_select(thetool)
  1662. return f
  1663. for tool in self.tools_exc:
  1664. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1665. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1666. self.options = {
  1667. "global_gridx": 0.1,
  1668. "global_gridy": 0.1,
  1669. "snap_max": 0.05,
  1670. "grid_snap": True,
  1671. "corner_snap": False,
  1672. "grid_gap_link": True
  1673. }
  1674. self.app.options_read_form()
  1675. for option in self.options:
  1676. if option in self.app.options:
  1677. self.options[option] = self.app.options[option]
  1678. self.rtree_exc_index = rtindex.Index()
  1679. # flag to show if the object was modified
  1680. self.is_modified = False
  1681. self.edited_obj_name = ""
  1682. # variable to store the total amount of drills per job
  1683. self.tot_drill_cnt = 0
  1684. self.tool_row = 0
  1685. # variable to store the total amount of slots per job
  1686. self.tot_slot_cnt = 0
  1687. self.tool_row_slots = 0
  1688. self.tool_row = 0
  1689. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1690. self.editor_active = False
  1691. def entry2option(option, entry):
  1692. self.options[option] = float(entry.text())
  1693. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1694. self.editor_active = False
  1695. log.debug("Initialization of the FlatCAM Excellon Editor is finished ...")
  1696. def pool_recreated(self, pool):
  1697. self.shapes.pool = pool
  1698. self.tool_shape.pool = pool
  1699. @staticmethod
  1700. def make_storage():
  1701. # ## Shape storage.
  1702. storage = FlatCAMRTreeStorage()
  1703. storage.get_points = DrawToolShape.get_pts
  1704. return storage
  1705. def set_ui(self):
  1706. # updated units
  1707. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1708. self.olddia_newdia.clear()
  1709. self.tool2tooldia.clear()
  1710. # build the self.points_edit dict {dimaters: [point_list]}
  1711. for drill in self.exc_obj.drills:
  1712. if drill['tool'] in self.exc_obj.tools:
  1713. if self.units == 'IN':
  1714. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1715. else:
  1716. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1717. try:
  1718. self.points_edit[tool_dia].append(drill['point'])
  1719. except KeyError:
  1720. self.points_edit[tool_dia] = [drill['point']]
  1721. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1722. for slot in self.exc_obj.slots:
  1723. if slot['tool'] in self.exc_obj.tools:
  1724. if self.units == 'IN':
  1725. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1726. else:
  1727. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1728. try:
  1729. self.slot_points_edit[tool_dia].append({
  1730. "start": slot["start"],
  1731. "stop": slot["stop"]
  1732. })
  1733. except KeyError:
  1734. self.slot_points_edit[tool_dia] = [{
  1735. "start": slot["start"],
  1736. "stop": slot["stop"]
  1737. }]
  1738. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1739. for key in self.points_edit:
  1740. self.olddia_newdia[key] = key
  1741. for key in self.slot_points_edit:
  1742. if key not in self.olddia_newdia:
  1743. self.olddia_newdia[key] = key
  1744. sort_temp = []
  1745. for diam in self.olddia_newdia:
  1746. sort_temp.append(float(diam))
  1747. self.sorted_diameters = sorted(sort_temp)
  1748. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1749. if self.exc_obj.diameterless is False:
  1750. for i in range(len(self.sorted_diameters)):
  1751. tt_dia = self.sorted_diameters[i]
  1752. self.tool2tooldia[i + 1] = tt_dia
  1753. else:
  1754. # the Excellon object has diameters that are bogus information, added by the application because the
  1755. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1756. # but use the real order found in the exc_obj.tools
  1757. for k, v in self.exc_obj.tools.items():
  1758. if self.units == 'IN':
  1759. tool_dia = float('%.4f' % v['C'])
  1760. else:
  1761. tool_dia = float('%.2f' % v['C'])
  1762. self.tool2tooldia[int(k)] = tool_dia
  1763. # Init GUI
  1764. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1765. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1766. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1767. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1768. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1769. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1770. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1771. self.slot_length_entry.set_value(float(self.app.defaults['excellon_editor_slot_length']))
  1772. self.slot_axis_radio.set_value(self.app.defaults['excellon_editor_slot_direction'])
  1773. self.slot_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_angle']))
  1774. self.slot_array_size_entry.set_value(int(self.app.defaults['excellon_editor_slot_array_size']))
  1775. self.slot_array_axis_radio.set_value(self.app.defaults['excellon_editor_slot_lin_dir'])
  1776. self.slot_array_pitch_entry.set_value(float(self.app.defaults['excellon_editor_slot_lin_pitch']))
  1777. self.slot_array_linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_lin_angle']))
  1778. self.slot_array_direction_radio.set_value(self.app.defaults['excellon_editor_slot_circ_dir'])
  1779. self.slot_array_angle_entry.set_value(float(self.app.defaults['excellon_editor_slot_circ_angle']))
  1780. self.slot_array_circular_frame.hide()
  1781. self.slot_array_linear_frame.show()
  1782. def build_ui(self, first_run=None):
  1783. try:
  1784. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1785. self.tools_table_exc.itemChanged.disconnect()
  1786. except (TypeError, AttributeError):
  1787. pass
  1788. try:
  1789. self.tools_table_exc.cellPressed.disconnect()
  1790. except (TypeError, AttributeError):
  1791. pass
  1792. # updated units
  1793. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1794. # make a new name for the new Excellon object (the one with edited content)
  1795. self.edited_obj_name = self.exc_obj.options['name']
  1796. self.name_entry.set_value(self.edited_obj_name)
  1797. sort_temp = []
  1798. for diam in self.olddia_newdia:
  1799. sort_temp.append(float(diam))
  1800. self.sorted_diameters = sorted(sort_temp)
  1801. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1802. n = len(self.sorted_diameters)
  1803. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1804. self.tools_table_exc.setRowCount(n + 2)
  1805. self.tot_drill_cnt = 0
  1806. self.tot_slot_cnt = 0
  1807. self.tool_row = 0
  1808. # this variable will serve as the real tool_number
  1809. tool_id = 0
  1810. for tool_no in self.sorted_diameters:
  1811. tool_id += 1
  1812. drill_cnt = 0 # variable to store the nr of drills per tool
  1813. slot_cnt = 0 # variable to store the nr of slots per tool
  1814. # Find no of drills for the current tool
  1815. for tool_dia in self.points_edit:
  1816. if float(tool_dia) == tool_no:
  1817. drill_cnt = len(self.points_edit[tool_dia])
  1818. self.tot_drill_cnt += drill_cnt
  1819. try:
  1820. # Find no of slots for the current tool
  1821. for slot in self.slots:
  1822. if slot['tool'] == tool_no:
  1823. slot_cnt += 1
  1824. self.tot_slot_cnt += slot_cnt
  1825. except AttributeError:
  1826. # log.debug("No slots in the Excellon file")
  1827. # Find no of slots for the current tool
  1828. for tool_dia in self.slot_points_edit:
  1829. if float(tool_dia) == tool_no:
  1830. slot_cnt = len(self.slot_points_edit[tool_dia])
  1831. self.tot_slot_cnt += slot_cnt
  1832. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1833. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1834. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1835. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1836. # There are no drill bits in MM with more than 3 decimals diameter
  1837. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1838. if self.units == 'MM':
  1839. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1840. else:
  1841. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1842. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1843. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1844. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1845. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1846. if slot_cnt > 0:
  1847. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1848. else:
  1849. slot_count = QtWidgets.QTableWidgetItem('')
  1850. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1851. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1852. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1853. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1854. if first_run is True:
  1855. # set now the last tool selected
  1856. self.last_tool_selected = int(tool_id)
  1857. self.tool_row += 1
  1858. # make the diameter column editable
  1859. for row in range(self.tool_row):
  1860. self.tools_table_exc.item(row, 1).setFlags(
  1861. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1862. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1863. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1864. # add a last row with the Total number of drills
  1865. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1866. # it will have to have the foreground color (font color) white
  1867. empty = QtWidgets.QTableWidgetItem('9998')
  1868. empty.setForeground(QtGui.QColor(255, 255, 255))
  1869. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1870. empty_b = QtWidgets.QTableWidgetItem('')
  1871. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1872. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1873. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1874. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1875. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1876. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1877. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1878. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1879. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1880. font = QtGui.QFont()
  1881. font.setBold(True)
  1882. font.setWeight(75)
  1883. for k in [1, 2]:
  1884. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1885. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1886. self.tool_row += 1
  1887. # add a last row with the Total number of slots
  1888. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1889. # it will have to have the foreground color (font color) white
  1890. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1891. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1892. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1893. empty_3 = QtWidgets.QTableWidgetItem('')
  1894. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1895. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1896. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1897. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1898. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1899. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1900. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1901. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1902. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1903. for kl in [1, 2, 3]:
  1904. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1905. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1906. # all the tools are selected by default
  1907. self.tools_table_exc.selectColumn(0)
  1908. #
  1909. self.tools_table_exc.resizeColumnsToContents()
  1910. self.tools_table_exc.resizeRowsToContents()
  1911. vertical_header = self.tools_table_exc.verticalHeader()
  1912. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1913. vertical_header.hide()
  1914. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1915. horizontal_header = self.tools_table_exc.horizontalHeader()
  1916. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1917. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1918. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1919. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1920. # horizontal_header.setStretchLastSection(True)
  1921. # self.tools_table_exc.setSortingEnabled(True)
  1922. # sort by tool diameter
  1923. self.tools_table_exc.sortItems(1)
  1924. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1925. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1926. # use them
  1927. self.tool2tooldia.clear()
  1928. for row in range(self.tools_table_exc.rowCount() - 2):
  1929. tool = int(self.tools_table_exc.item(row, 0).text())
  1930. diameter = float(self.tools_table_exc.item(row, 1).text())
  1931. self.tool2tooldia[tool] = diameter
  1932. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1933. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1934. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1935. self.tools_table_exc.clearSelection()
  1936. # Remove anything else in the GUI Selected Tab
  1937. self.app.ui.selected_scroll_area.takeWidget()
  1938. # Put ourself in the GUI Selected Tab
  1939. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1940. # Switch notebook to Selected page
  1941. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1942. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1943. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1944. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1945. def on_tool_add(self, tooldia=None):
  1946. self.is_modified = True
  1947. if tooldia:
  1948. tool_dia = tooldia
  1949. else:
  1950. try:
  1951. tool_dia = float(self.addtool_entry.get_value())
  1952. except ValueError:
  1953. # try to convert comma to decimal point. if it's still not working error message and return
  1954. try:
  1955. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1956. except ValueError:
  1957. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1958. _("Wrong value format entered, use a number."))
  1959. return
  1960. if tool_dia not in self.olddia_newdia:
  1961. storage_elem = FlatCAMGeoEditor.make_storage()
  1962. self.storage_dict[tool_dia] = storage_elem
  1963. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1964. # each time a tool diameter is edited or added
  1965. self.olddia_newdia[tool_dia] = tool_dia
  1966. else:
  1967. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1968. _("Tool already in the original or actual tool list.\n"
  1969. "Save and reedit Excellon if you need to add this tool. "))
  1970. return
  1971. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1972. # we add a new entry in the tool2tooldia dict
  1973. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1974. self.app.inform.emit('[success] %s: %s %s' %
  1975. (_("Added new tool with dia"), str(tool_dia), str(self.units)))
  1976. self.build_ui()
  1977. # make a quick sort through the tool2tooldia dict so we find which row to select
  1978. row_to_be_selected = None
  1979. for key in sorted(self.tool2tooldia):
  1980. if self.tool2tooldia[key] == tool_dia:
  1981. row_to_be_selected = int(key) - 1
  1982. self.last_tool_selected = int(key)
  1983. break
  1984. self.tools_table_exc.selectRow(row_to_be_selected)
  1985. def on_tool_delete(self, dia=None):
  1986. self.is_modified = True
  1987. deleted_tool_dia_list = []
  1988. try:
  1989. if dia is None or dia is False:
  1990. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1991. for index in self.tools_table_exc.selectionModel().selectedRows():
  1992. row = index.row()
  1993. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1994. else:
  1995. if isinstance(dia, list):
  1996. for dd in dia:
  1997. deleted_tool_dia_list.append(float('%.4f' % dd))
  1998. else:
  1999. deleted_tool_dia_list.append(float('%.4f' % dia))
  2000. except Exception as e:
  2001. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2002. _("Select a tool in Tool Table"))
  2003. return
  2004. for deleted_tool_dia in deleted_tool_dia_list:
  2005. # delete de tool offset
  2006. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  2007. # delete the storage used for that tool
  2008. storage_elem = FlatCAMGeoEditor.make_storage()
  2009. self.storage_dict[deleted_tool_dia] = storage_elem
  2010. self.storage_dict.pop(deleted_tool_dia, None)
  2011. # I've added this flag_del variable because dictionary don't like
  2012. # having keys deleted while iterating through them
  2013. flag_del = []
  2014. # self.points_edit.pop(deleted_tool_dia, None)
  2015. for deleted_tool in self.tool2tooldia:
  2016. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  2017. flag_del.append(deleted_tool)
  2018. if flag_del:
  2019. for tool_to_be_deleted in flag_del:
  2020. # delete the tool
  2021. self.tool2tooldia.pop(tool_to_be_deleted, None)
  2022. # delete also the drills from points_edit dict just in case we add the tool again,
  2023. # we don't want to show the number of drills from before was deleter
  2024. self.points_edit[deleted_tool_dia] = []
  2025. self.olddia_newdia.pop(deleted_tool_dia, None)
  2026. self.app.inform.emit('[success] %s: %s %s' %
  2027. (_("Deleted tool with diameter"), str(deleted_tool_dia), str(self.units)))
  2028. self.replot()
  2029. # self.app.inform.emit("Could not delete selected tool")
  2030. self.build_ui()
  2031. def on_tool_edit(self, item_changed):
  2032. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2033. try:
  2034. self.tools_table_exc.itemChanged.disconnect()
  2035. except TypeError:
  2036. pass
  2037. try:
  2038. self.tools_table_exc.cellPressed.disconnect()
  2039. except TypeError:
  2040. pass
  2041. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  2042. self.is_modified = True
  2043. new_dia = None
  2044. if self.tools_table_exc.currentItem() is not None:
  2045. try:
  2046. new_dia = float(self.tools_table_exc.currentItem().text())
  2047. except ValueError as e:
  2048. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  2049. self.tools_table_exc.setCurrentItem(None)
  2050. return
  2051. row_of_item_changed = self.tools_table_exc.currentRow()
  2052. # rows start with 0, tools start with 1 so we adjust the value by 1
  2053. key_in_tool2tooldia = row_of_item_changed + 1
  2054. old_dia = self.tool2tooldia[key_in_tool2tooldia]
  2055. # SOURCE storage
  2056. source_storage = self.storage_dict[old_dia]
  2057. # DESTINATION storage
  2058. # tool diameter is not used so we create a new tool with the desired diameter
  2059. if new_dia not in self.olddia_newdia:
  2060. destination_storage = FlatCAMGeoEditor.make_storage()
  2061. self.storage_dict[new_dia] = destination_storage
  2062. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2063. # each time a tool diameter is edited or added
  2064. self.olddia_newdia[new_dia] = new_dia
  2065. else:
  2066. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  2067. destination_storage = self.storage_dict[new_dia]
  2068. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2069. # we add a new entry in the tool2tooldia dict
  2070. self.tool2tooldia[len(self.olddia_newdia)] = new_dia
  2071. # CHANGE the elements geometry according to the new diameter
  2072. factor = new_dia / old_dia
  2073. new_geo = Polygon()
  2074. for shape_exc in source_storage.get_objects():
  2075. geo_list = []
  2076. if isinstance(shape_exc.geo, MultiLineString):
  2077. for subgeo in shape_exc.geo:
  2078. geo_list.append(affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center'))
  2079. new_geo = MultiLineString(geo_list)
  2080. elif isinstance(shape_exc.geo, Polygon):
  2081. # I don't have any info regarding the angle of the slot geometry, nor how thick it is or
  2082. # how long it is given the angle. So I will have to make an approximation because
  2083. # we need to conserve the slot length, we only resize the diameter for the tool
  2084. # Therefore scaling won't work and buffering will not work either.
  2085. # First we get the Linestring that is one that the original slot is built around with the
  2086. # tool having the diameter sel_dia
  2087. poly = shape_exc.geo
  2088. xmin, ymin, xmax, ymax = poly.bounds
  2089. # a line that is certain to be bigger than our slot because it's the diagonal
  2090. # of it's bounding box
  2091. poly_diagonal = LineString([(xmin, ymin), (xmax, ymax)])
  2092. poly_centroid = poly.centroid
  2093. # center of the slot geometry
  2094. poly_center = (poly_centroid.x, poly_centroid.y)
  2095. # make a list of intersections with the rotated line
  2096. list_of_cuttings = []
  2097. for angle in range(0, 359, 1):
  2098. rot_poly_diagonal = affinity.rotate(poly_diagonal, angle=angle, origin=poly_center)
  2099. cut_line = rot_poly_diagonal.intersection(poly)
  2100. cut_line_len = cut_line.length
  2101. list_of_cuttings.append(
  2102. (cut_line_len, cut_line)
  2103. )
  2104. # find the cut_line with the maximum length which is the LineString for which the start
  2105. # and stop point are the start and stop point of the slot as in the Gerber file
  2106. cut_line_with_max_length = max(list_of_cuttings, key=lambda i: i[0])[1]
  2107. # find the coordinates of this line
  2108. cut_line_with_max_length_coords = list(cut_line_with_max_length.coords)
  2109. # extract the first and last point of the line and build some buffered polygon circles
  2110. # around them
  2111. start_pt = Point(cut_line_with_max_length_coords[0])
  2112. stop_pt = Point(cut_line_with_max_length_coords[1])
  2113. start_cut_geo = start_pt.buffer(new_dia / 2)
  2114. stop_cut_geo = stop_pt.buffer(new_dia / 2)
  2115. # and we cut the above circle polygons from our line and get in this way a line around
  2116. # which we can build the new slot by buffering with the new tool diameter
  2117. new_line = cut_line_with_max_length.difference(start_cut_geo)
  2118. new_line = new_line.difference(stop_cut_geo)
  2119. # create the geometry for the resized slot by buffering with half of the
  2120. # new diameter value: new_dia
  2121. new_geo = new_line.buffer(new_dia / 2)
  2122. try:
  2123. self.points_edit.pop(old_dia, None)
  2124. except KeyError:
  2125. pass
  2126. try:
  2127. self.slot_points_edit.pop(old_dia, None)
  2128. except KeyError:
  2129. pass
  2130. # add bogus drill/slots points (for total count of drills/slots)
  2131. # for drills
  2132. if isinstance(shape_exc.geo, MultiLineString):
  2133. if new_dia not in self.points_edit:
  2134. self.points_edit[new_dia] = [(0, 0)]
  2135. else:
  2136. self.points_edit[new_dia].append((0, 0))
  2137. # for slots
  2138. if isinstance(shape_exc.geo, Polygon):
  2139. if new_dia not in self.slot_points_edit:
  2140. self.slot_points_edit[new_dia] = [(0, 0)]
  2141. else:
  2142. self.slot_points_edit[new_dia].append((0, 0))
  2143. self.add_exc_shape(shape=DrawToolShape(new_geo), storage=destination_storage)
  2144. # update the UI and the CANVAS
  2145. self.build_ui()
  2146. self.replot()
  2147. # delete the old tool
  2148. self.on_tool_delete(dia=old_dia)
  2149. # we reactivate the signals after the after the tool editing
  2150. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2151. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2152. self.app.inform.emit('[success] %s' %
  2153. _("Done. Tool edit completed."))
  2154. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  2155. def on_name_activate(self):
  2156. self.edited_obj_name = self.name_entry.get_value()
  2157. def activate(self):
  2158. # adjust the status of the menu entries related to the editor
  2159. self.app.ui.menueditedit.setDisabled(True)
  2160. self.app.ui.menueditok.setDisabled(False)
  2161. # adjust the visibility of some of the canvas context menu
  2162. self.app.ui.popmenu_edit.setVisible(False)
  2163. self.app.ui.popmenu_save.setVisible(True)
  2164. self.connect_canvas_event_handlers()
  2165. # initialize working objects
  2166. self.storage_dict = {}
  2167. self.current_storage = []
  2168. self.points_edit = {}
  2169. self.sorted_diameters = []
  2170. self.new_drills = []
  2171. self.new_tools = {}
  2172. self.new_slots = []
  2173. self.new_tool_offset = {}
  2174. self.olddia_newdia = {}
  2175. self.shapes.enabled = True
  2176. self.tool_shape.enabled = True
  2177. # self.app.app_cursor.enabled = True
  2178. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2179. self.app.ui.corner_snap_btn.setEnabled(True)
  2180. self.app.ui.snap_magnet.setVisible(True)
  2181. self.app.ui.corner_snap_btn.setVisible(True)
  2182. self.app.ui.exc_editor_menu.setDisabled(False)
  2183. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  2184. self.app.ui.update_obj_btn.setEnabled(True)
  2185. self.app.ui.e_editor_cmenu.setEnabled(True)
  2186. self.app.ui.exc_edit_toolbar.setDisabled(False)
  2187. self.app.ui.exc_edit_toolbar.setVisible(True)
  2188. # self.app.ui.snap_toolbar.setDisabled(False)
  2189. # start with GRID toolbar activated
  2190. if self.app.ui.grid_snap_btn.isChecked() is False:
  2191. self.app.ui.grid_snap_btn.trigger()
  2192. self.app.ui.popmenu_disable.setVisible(False)
  2193. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2194. self.app.ui.popmenu_properties.setVisible(False)
  2195. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  2196. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2197. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2198. # Tell the App that the editor is active
  2199. self.editor_active = True
  2200. # show the UI
  2201. self.drills_frame.show()
  2202. def deactivate(self):
  2203. try:
  2204. QtGui.QGuiApplication.restoreOverrideCursor()
  2205. except Exception as e:
  2206. pass
  2207. # adjust the status of the menu entries related to the editor
  2208. self.app.ui.menueditedit.setDisabled(False)
  2209. self.app.ui.menueditok.setDisabled(True)
  2210. # adjust the visibility of some of the canvas context menu
  2211. self.app.ui.popmenu_edit.setVisible(True)
  2212. self.app.ui.popmenu_save.setVisible(False)
  2213. self.disconnect_canvas_event_handlers()
  2214. self.clear()
  2215. self.app.ui.exc_edit_toolbar.setDisabled(True)
  2216. settings = QSettings("Open Source", "FlatCAM")
  2217. if settings.contains("layout"):
  2218. layout = settings.value('layout', type=str)
  2219. if layout == 'standard':
  2220. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2221. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2222. self.app.ui.corner_snap_btn.setEnabled(False)
  2223. self.app.ui.snap_magnet.setVisible(False)
  2224. self.app.ui.corner_snap_btn.setVisible(False)
  2225. elif layout == 'compact':
  2226. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2227. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2228. self.app.ui.corner_snap_btn.setEnabled(False)
  2229. self.app.ui.snap_magnet.setVisible(True)
  2230. self.app.ui.corner_snap_btn.setVisible(True)
  2231. else:
  2232. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2233. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2234. self.app.ui.corner_snap_btn.setEnabled(False)
  2235. self.app.ui.snap_magnet.setVisible(False)
  2236. self.app.ui.corner_snap_btn.setVisible(False)
  2237. # set the Editor Toolbar visibility to what was before entering in the Editor
  2238. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2239. else self.app.ui.exc_edit_toolbar.setVisible(True)
  2240. # Disable visuals
  2241. self.shapes.enabled = False
  2242. self.tool_shape.enabled = False
  2243. # self.app.app_cursor.enabled = False
  2244. # Tell the app that the editor is no longer active
  2245. self.editor_active = False
  2246. self.app.ui.exc_editor_menu.setDisabled(True)
  2247. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  2248. self.app.ui.update_obj_btn.setEnabled(False)
  2249. self.app.ui.popmenu_disable.setVisible(True)
  2250. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2251. self.app.ui.popmenu_properties.setVisible(True)
  2252. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2253. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2254. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2255. # Show original geometry
  2256. if self.exc_obj:
  2257. self.exc_obj.visible = True
  2258. # hide the UI
  2259. self.drills_frame.hide()
  2260. def connect_canvas_event_handlers(self):
  2261. # ## Canvas events
  2262. # first connect to new, then disconnect the old handlers
  2263. # don't ask why but if there is nothing connected I've seen issues
  2264. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2265. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2266. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  2267. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2268. # but those from FlatCAMGeoEditor
  2269. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2270. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2271. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2272. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2273. self.app.collection.view.clicked.disconnect()
  2274. self.app.ui.popmenu_copy.triggered.disconnect()
  2275. self.app.ui.popmenu_delete.triggered.disconnect()
  2276. self.app.ui.popmenu_move.triggered.disconnect()
  2277. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  2278. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2279. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  2280. # Excellon Editor
  2281. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  2282. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  2283. def disconnect_canvas_event_handlers(self):
  2284. # we restore the key and mouse control to FlatCAMApp method
  2285. # first connect to new, then disconnect the old handlers
  2286. # don't ask why but if there is nothing connected I've seen issues
  2287. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2288. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2289. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2290. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2291. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2292. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2293. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2294. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  2295. try:
  2296. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  2297. except (TypeError, AttributeError):
  2298. pass
  2299. try:
  2300. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2301. except (TypeError, AttributeError):
  2302. pass
  2303. try:
  2304. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  2305. except (TypeError, AttributeError):
  2306. pass
  2307. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2308. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2309. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2310. # Excellon Editor
  2311. try:
  2312. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2313. except (TypeError, AttributeError):
  2314. pass
  2315. try:
  2316. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2317. except (TypeError, AttributeError):
  2318. pass
  2319. def clear(self):
  2320. self.active_tool = None
  2321. # self.shape_buffer = []
  2322. self.selected = []
  2323. self.points_edit = {}
  2324. self.new_tools = {}
  2325. self.new_drills = []
  2326. # self.storage_dict = {}
  2327. self.shapes.clear(update=True)
  2328. self.tool_shape.clear(update=True)
  2329. # self.storage = FlatCAMExcEditor.make_storage()
  2330. self.replot()
  2331. def edit_fcexcellon(self, exc_obj):
  2332. """
  2333. Imports the geometry from the given FlatCAM Excellon object
  2334. into the editor.
  2335. :param exc_obj: FlatCAMExcellon object
  2336. :return: None
  2337. """
  2338. assert isinstance(exc_obj, Excellon), \
  2339. "Expected an Excellon Object, got %s" % type(exc_obj)
  2340. self.deactivate()
  2341. self.activate()
  2342. # Hide original geometry
  2343. self.exc_obj = exc_obj
  2344. exc_obj.visible = False
  2345. self.points_edit = {}
  2346. self.slot_points_edit = {}
  2347. # Set selection tolerance
  2348. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2349. self.select_tool("drill_select")
  2350. self.set_ui()
  2351. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2352. self.build_ui(first_run=True)
  2353. # we activate this after the initial build as we don't need to see the tool been populated
  2354. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2355. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2356. # and then add it to the storage elements (each storage elements is a member of a list
  2357. for tool_dia in self.points_edit:
  2358. storage_elem = FlatCAMGeoEditor.make_storage()
  2359. for point in self.points_edit[tool_dia]:
  2360. # make a '+' sign, the line length is the tool diameter
  2361. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2362. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2363. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2364. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2365. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2366. if shape_geo is not None:
  2367. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2368. self.storage_dict[tool_dia] = storage_elem
  2369. # slots
  2370. for tool_dia in self.slot_points_edit:
  2371. buf_value = float(tool_dia) / 2
  2372. for elem_dict in self.slot_points_edit[tool_dia]:
  2373. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2374. shape_geo = line_geo.buffer(buf_value)
  2375. if tool_dia not in self.storage_dict:
  2376. storage_elem = FlatCAMGeoEditor.make_storage()
  2377. self.storage_dict[tool_dia] = storage_elem
  2378. if shape_geo is not None:
  2379. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2380. self.replot()
  2381. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2382. if not self.tool2tooldia:
  2383. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2384. def update_fcexcellon(self, exc_obj):
  2385. """
  2386. Create a new Excellon object that contain the edited content of the source Excellon object
  2387. :param exc_obj: FlatCAMExcellon
  2388. :return: None
  2389. """
  2390. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2391. # the values of this dict are coordinates of the holes (drills)
  2392. edited_points = {}
  2393. """
  2394. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2395. - the dict element of the list has the structure
  2396. ================ ====================================
  2397. Key Value
  2398. ================ ====================================
  2399. start (Shapely.Point) Start point of the slot
  2400. stop (Shapely.Point) Stop point of the slot
  2401. ================ ====================================
  2402. """
  2403. edited_slot_points = {}
  2404. for storage_tooldia in self.storage_dict:
  2405. for x in self.storage_dict[storage_tooldia].get_objects():
  2406. if isinstance(x.geo, MultiLineString):
  2407. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2408. # each MultiLineString is made out of Linestrings
  2409. # select first Linestring object in the current MultiLineString
  2410. first_linestring = x.geo[0]
  2411. # get it's coordinates
  2412. first_linestring_coords = first_linestring.coords
  2413. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2414. y_coord = first_linestring_coords[0][1]
  2415. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2416. # edited_points dictionary
  2417. point = (x_coord, y_coord)
  2418. if storage_tooldia not in edited_points:
  2419. edited_points[storage_tooldia] = [point]
  2420. else:
  2421. edited_points[storage_tooldia].append(point)
  2422. elif isinstance(x.geo, Polygon):
  2423. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2424. # edited_points dictionary
  2425. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2426. # diameter
  2427. radius = float(storage_tooldia) / 2
  2428. radius = radius - 0.0000001
  2429. poly = x.geo
  2430. poly = poly.buffer(-radius)
  2431. xmin, ymin, xmax, ymax = poly.bounds
  2432. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2433. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2434. if line_one < line_two:
  2435. point_elem = {
  2436. "start": (xmin, ymax),
  2437. "stop": (xmax, ymin)
  2438. }
  2439. else:
  2440. point_elem = {
  2441. "start": (xmin, ymin),
  2442. "stop": (xmax, ymax)
  2443. }
  2444. if storage_tooldia not in edited_slot_points:
  2445. edited_slot_points[storage_tooldia] = [point_elem]
  2446. else:
  2447. edited_slot_points[storage_tooldia].append(point_elem)
  2448. # recreate the drills and tools to be added to the new Excellon edited object
  2449. # first, we look in the tool table if one of the tool diameters was changed then
  2450. # append that a tuple formed by (old_dia, edited_dia) to a list
  2451. changed_key = set()
  2452. for initial_dia in self.olddia_newdia:
  2453. edited_dia = self.olddia_newdia[initial_dia]
  2454. if edited_dia != initial_dia:
  2455. # for drills
  2456. for old_dia in edited_points:
  2457. if old_dia == initial_dia:
  2458. changed_key.add((old_dia, edited_dia))
  2459. # for slots
  2460. for old_dia in edited_slot_points:
  2461. if old_dia == initial_dia:
  2462. changed_key.add((old_dia, edited_dia))
  2463. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2464. # (and we have to add it)
  2465. # because in case we have drill points it will have to be already added in edited_points
  2466. # if initial_dia not in edited_points.keys():
  2467. # edited_points[initial_dia] = []
  2468. for el in changed_key:
  2469. edited_points[el[1]] = edited_points.pop(el[0])
  2470. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2471. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2472. # ordered_edited_points is a ordered list of tuples;
  2473. # element[0] of the tuple is the diameter and
  2474. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2475. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2476. current_tool = 0
  2477. for tool_dia in ordered_edited_points:
  2478. current_tool += 1
  2479. # create the self.tools for the new Excellon object (the one with edited content)
  2480. name = str(current_tool)
  2481. spec = {"C": float(tool_dia[0])}
  2482. self.new_tools[name] = spec
  2483. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2484. self.new_tools[name]['solid_geometry'] = []
  2485. # create the self.drills for the new Excellon object (the one with edited content)
  2486. for point in tool_dia[1]:
  2487. self.new_drills.append(
  2488. {
  2489. 'point': Point(point),
  2490. 'tool': str(current_tool)
  2491. }
  2492. )
  2493. # repopulate the 'solid_geometry' for each tool
  2494. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2495. self.new_tools[name]['solid_geometry'].append(poly)
  2496. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2497. for tool_dia in ordered_edited_slot_points:
  2498. tool_exist_flag = False
  2499. for tool in self.new_tools:
  2500. if tool_dia[0] == self.new_tools[tool]["C"]:
  2501. current_tool = tool
  2502. tool_exist_flag = True
  2503. break
  2504. if tool_exist_flag is False:
  2505. current_tool += 1
  2506. # create the self.tools for the new Excellon object (the one with edited content)
  2507. name = str(current_tool)
  2508. spec = {"C": float(tool_dia[0])}
  2509. self.new_tools[name] = spec
  2510. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2511. self.new_tools[name]['solid_geometry'] = []
  2512. # create the self.slots for the new Excellon object (the one with edited content)
  2513. for coord_dict in tool_dia[1]:
  2514. self.new_slots.append(
  2515. {
  2516. 'start': Point(coord_dict['start']),
  2517. 'stop': Point(coord_dict['stop']),
  2518. 'tool': str(current_tool)
  2519. }
  2520. )
  2521. # repopulate the 'solid_geometry' for each tool
  2522. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2523. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2524. )
  2525. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2526. if self.is_modified is True:
  2527. if "_edit" in self.edited_obj_name:
  2528. try:
  2529. idd = int(self.edited_obj_name[-1]) + 1
  2530. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2531. except ValueError:
  2532. self.edited_obj_name += "_1"
  2533. else:
  2534. self.edited_obj_name += "_edit"
  2535. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2536. 'params': [self.edited_obj_name]})
  2537. self.new_tool_offset = self.exc_obj.tool_offset
  2538. # reset the tool table
  2539. self.tools_table_exc.clear()
  2540. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2541. self.last_tool_selected = None
  2542. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2543. # self.app.collection.set_active(self.exc_obj.options['name'])
  2544. # self.app.collection.delete_active()
  2545. # restore GUI to the Selected TAB
  2546. # Remove anything else in the GUI
  2547. self.app.ui.tool_scroll_area.takeWidget()
  2548. # Switch notebook to Selected page
  2549. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2550. def update_options(self, obj):
  2551. try:
  2552. if not obj.options:
  2553. obj.options = {}
  2554. obj.options['xmin'] = 0
  2555. obj.options['ymin'] = 0
  2556. obj.options['xmax'] = 0
  2557. obj.options['ymax'] = 0
  2558. return True
  2559. else:
  2560. return False
  2561. except AttributeError:
  2562. obj.options = {}
  2563. return True
  2564. def new_edited_excellon(self, outname):
  2565. """
  2566. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2567. :param outname: Name of the resulting object. None causes the
  2568. name to be that of the file.
  2569. :type outname: str
  2570. :return: None
  2571. """
  2572. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2573. self.exc_obj.options['name'])
  2574. # How the object should be initialized
  2575. def obj_init(excellon_obj, app_obj):
  2576. # self.progress.emit(20)
  2577. excellon_obj.drills = self.new_drills
  2578. excellon_obj.tools = self.new_tools
  2579. excellon_obj.slots = self.new_slots
  2580. excellon_obj.tool_offset = self.new_tool_offset
  2581. excellon_obj.options['name'] = outname
  2582. try:
  2583. excellon_obj.create_geometry()
  2584. except KeyError:
  2585. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2586. _("There are no Tools definitions in the file. Aborting Excellon creation.")
  2587. )
  2588. except:
  2589. msg = '[ERROR] %s' % \
  2590. _("An internal error has ocurred. See Shell.\n")
  2591. msg += traceback.format_exc()
  2592. app_obj.inform.emit(msg)
  2593. raise
  2594. # raise
  2595. excellon_obj.source_file = self.app.export_excellon(obj_name=outname, filename=None,
  2596. local_use=excellon_obj, use_thread=False)
  2597. with self.app.proc_container.new(_("Creating Excellon.")):
  2598. try:
  2599. self.app.new_object("excellon", outname, obj_init)
  2600. except Exception as e:
  2601. log.error("Error on object creation: %s" % str(e))
  2602. self.app.progress.emit(100)
  2603. return
  2604. self.app.inform.emit('[success] %s' %
  2605. _("Excellon editing finished."))
  2606. # self.progress.emit(100)
  2607. def on_tool_select(self, tool):
  2608. """
  2609. Behavior of the toolbar. Tool initialization.
  2610. :rtype : None
  2611. """
  2612. current_tool = tool
  2613. self.app.log.debug("on_tool_select('%s')" % tool)
  2614. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2615. # self.draw_app.select_tool('drill_select')
  2616. self.complete = True
  2617. current_tool = 'drill_select'
  2618. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2619. _("Cancelled. There is no Tool/Drill selected"))
  2620. # This is to make the group behave as radio group
  2621. if current_tool in self.tools_exc:
  2622. if self.tools_exc[current_tool]["button"].isChecked():
  2623. self.app.log.debug("%s is checked." % current_tool)
  2624. for t in self.tools_exc:
  2625. if t != current_tool:
  2626. self.tools_exc[t]["button"].setChecked(False)
  2627. # this is where the Editor toolbar classes (button's) are instantiated
  2628. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2629. # self.app.inform.emit(self.active_tool.start_msg)
  2630. else:
  2631. self.app.log.debug("%s is NOT checked." % current_tool)
  2632. for t in self.tools_exc:
  2633. self.tools_exc[t]["button"].setChecked(False)
  2634. self.select_tool('drill_select')
  2635. self.active_tool = FCDrillSelect(self)
  2636. def on_row_selected(self, row, col):
  2637. if col == 0:
  2638. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2639. if self.app.defaults["global_mselect_key"] == 'Control':
  2640. modifier_to_use = Qt.ControlModifier
  2641. else:
  2642. modifier_to_use = Qt.ShiftModifier
  2643. if key_modifier == modifier_to_use:
  2644. pass
  2645. else:
  2646. self.selected = []
  2647. try:
  2648. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2649. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2650. for obj in self.storage_dict[selected_dia].get_objects():
  2651. self.selected.append(obj)
  2652. except Exception as e:
  2653. self.app.log.debug(str(e))
  2654. self.replot()
  2655. def toolbar_tool_toggle(self, key):
  2656. self.options[key] = self.sender().isChecked()
  2657. if self.options[key] is True:
  2658. return 1
  2659. else:
  2660. return 0
  2661. def on_canvas_click(self, event):
  2662. """
  2663. event.x and .y have canvas coordinates
  2664. event.xdata and .ydata have plot coordinates
  2665. :param event: Event object dispatched by VisPy
  2666. :return: None
  2667. """
  2668. self.pos = self.canvas.translate_coords(event.pos)
  2669. if self.app.grid_status() == True:
  2670. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2671. self.app.app_cursor.enabled = True
  2672. # Update cursor
  2673. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2674. size=20)
  2675. else:
  2676. self.pos = (self.pos[0], self.pos[1])
  2677. self.app.app_cursor.enabled = False
  2678. if event.button is 1:
  2679. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2680. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2681. # Selection with left mouse button
  2682. if self.active_tool is not None and event.button is 1:
  2683. # Dispatch event to active_tool
  2684. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2685. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2686. # If it is a shape generating tool
  2687. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2688. if self.current_storage is not None:
  2689. self.on_exc_shape_complete(self.current_storage)
  2690. self.build_ui()
  2691. # MS: always return to the Select Tool if modifier key is not pressed
  2692. # else return to the current tool
  2693. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2694. if self.app.defaults["global_mselect_key"] == 'Control':
  2695. modifier_to_use = Qt.ControlModifier
  2696. else:
  2697. modifier_to_use = Qt.ShiftModifier
  2698. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2699. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2700. if key_modifier == modifier_to_use:
  2701. self.select_tool(self.active_tool.name)
  2702. else:
  2703. # return to Select tool but not for FCDrillAdd or FCSlot
  2704. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2705. self.select_tool(self.active_tool.name)
  2706. else:
  2707. self.select_tool("drill_select")
  2708. return
  2709. if isinstance(self.active_tool, FCDrillSelect):
  2710. # self.app.log.debug("Replotting after click.")
  2711. self.replot()
  2712. else:
  2713. self.app.log.debug("No active tool to respond to click!")
  2714. def on_exc_shape_complete(self, storage):
  2715. self.app.log.debug("on_shape_complete()")
  2716. # Add shape
  2717. if type(storage) is list:
  2718. for item_storage in storage:
  2719. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2720. else:
  2721. self.add_exc_shape(self.active_tool.geometry, storage)
  2722. # Remove any utility shapes
  2723. self.delete_utility_geometry()
  2724. self.tool_shape.clear(update=True)
  2725. # Replot and reset tool.
  2726. self.replot()
  2727. # self.active_tool = type(self.active_tool)(self)
  2728. def add_exc_shape(self, shape, storage):
  2729. """
  2730. Adds a shape to a specified shape storage.
  2731. :param shape: Shape to be added.
  2732. :type shape: DrawToolShape
  2733. :param storage: object where to store the shapes
  2734. :return: None
  2735. """
  2736. # List of DrawToolShape?
  2737. if isinstance(shape, list):
  2738. for subshape in shape:
  2739. self.add_exc_shape(subshape, storage)
  2740. return
  2741. assert isinstance(shape, DrawToolShape), \
  2742. "Expected a DrawToolShape, got %s" % str(type(shape))
  2743. assert shape.geo is not None, \
  2744. "Shape object has empty geometry (None)"
  2745. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2746. "Shape objects has empty geometry ([])"
  2747. if isinstance(shape, DrawToolUtilityShape):
  2748. self.utility.append(shape)
  2749. else:
  2750. storage.insert(shape) # TODO: Check performance
  2751. def add_shape(self, shape):
  2752. """
  2753. Adds a shape to the shape storage.
  2754. :param shape: Shape to be added.
  2755. :type shape: DrawToolShape
  2756. :return: None
  2757. """
  2758. # List of DrawToolShape?
  2759. if isinstance(shape, list):
  2760. for subshape in shape:
  2761. self.add_shape(subshape)
  2762. return
  2763. assert isinstance(shape, DrawToolShape), \
  2764. "Expected a DrawToolShape, got %s" % type(shape)
  2765. assert shape.geo is not None, \
  2766. "Shape object has empty geometry (None)"
  2767. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2768. "Shape objects has empty geometry ([])"
  2769. if isinstance(shape, DrawToolUtilityShape):
  2770. self.utility.append(shape)
  2771. else:
  2772. self.storage.insert(shape) # TODO: Check performance
  2773. def on_exc_click_release(self, event):
  2774. """
  2775. Handler of the "mouse_release" event.
  2776. It will pop-up the context menu on right mouse click unless there was a panning move (decided in the
  2777. "mouse_move" event handler) and only if the current tool is the Select tool.
  2778. It will 'close' a Editor tool if it is the case.
  2779. :param event: Event object dispatched by VisPy SceneCavas
  2780. :return: None
  2781. """
  2782. pos_canvas = self.canvas.translate_coords(event.pos)
  2783. if self.app.grid_status() == True:
  2784. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2785. else:
  2786. pos = (pos_canvas[0], pos_canvas[1])
  2787. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2788. # canvas menu
  2789. try:
  2790. if event.button == 2: # right click
  2791. if self.app.ui.popMenu.mouse_is_panning is False:
  2792. try:
  2793. QtGui.QGuiApplication.restoreOverrideCursor()
  2794. except Exception as e:
  2795. pass
  2796. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2797. self.active_tool.complete = True
  2798. self.in_action = False
  2799. self.delete_utility_geometry()
  2800. self.app.inform.emit('[success] %s' %
  2801. _("Done."))
  2802. self.select_tool('drill_select')
  2803. else:
  2804. if isinstance(self.active_tool, FCDrillAdd):
  2805. self.active_tool.complete = True
  2806. self.in_action = False
  2807. self.delete_utility_geometry()
  2808. self.app.inform.emit('[success] %s' %
  2809. _("Done."))
  2810. self.select_tool('drill_select')
  2811. self.app.cursor = QtGui.QCursor()
  2812. self.app.populate_cmenu_grids()
  2813. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2814. except Exception as e:
  2815. log.warning("Error: %s" % str(e))
  2816. raise
  2817. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2818. # selection and then select a type of selection ("enclosing" or "touching")
  2819. try:
  2820. if event.button == 1: # left click
  2821. if self.app.selection_type is not None:
  2822. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2823. self.app.selection_type = None
  2824. elif isinstance(self.active_tool, FCDrillSelect):
  2825. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2826. # if there are selected objects then plot them
  2827. if self.selected:
  2828. self.replot()
  2829. except Exception as e:
  2830. log.warning("Error: %s" % str(e))
  2831. raise
  2832. def draw_selection_area_handler(self, start, end, sel_type):
  2833. """
  2834. This function is called whenever we have a left mouse click release and only we have a left mouse click drag,
  2835. be it from left to right or from right to left. The direction of the drag is decided in the "mouse_move"
  2836. event handler.
  2837. Pressing a modifier key (eg. Ctrl, Shift or Alt) will change the behavior of the selection.
  2838. Depending on which tool belongs the selected shapes, the corresponding rows in the Tools Table are selected or
  2839. deselected.
  2840. :param start: mouse position when the selection LMB click was done
  2841. :param end: mouse position when the left mouse button is released
  2842. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2843. :return:
  2844. """
  2845. start_pos = (start[0], start[1])
  2846. end_pos = (end[0], end[1])
  2847. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2848. modifiers = None
  2849. # delete the selection shape that was just drawn, we no longer need it
  2850. self.app.delete_selection_shape()
  2851. # detect if a modifier key was pressed while the left mouse button was released
  2852. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2853. if self.modifiers == QtCore.Qt.ShiftModifier:
  2854. modifiers = 'Shift'
  2855. elif self.modifiers == QtCore.Qt.ControlModifier:
  2856. modifiers = 'Control'
  2857. if modifiers == self.app.defaults["global_mselect_key"]:
  2858. for storage in self.storage_dict:
  2859. for obj in self.storage_dict[storage].get_objects():
  2860. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2861. (sel_type is False and poly_selection.intersects(obj.geo)):
  2862. if obj in self.selected:
  2863. # remove the shape object from the selected shapes storage
  2864. self.selected.remove(obj)
  2865. else:
  2866. # add the shape object to the selected shapes storage
  2867. self.selected.append(obj)
  2868. else:
  2869. # clear the selection shapes storage
  2870. self.selected = []
  2871. # then add to the selection shapes storage the shapes that are included (touched) by the selection rectangle
  2872. for storage in self.storage_dict:
  2873. for obj in self.storage_dict[storage].get_objects():
  2874. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2875. (sel_type is False and poly_selection.intersects(obj.geo)):
  2876. self.selected.append(obj)
  2877. try:
  2878. self.tools_table_exc.cellPressed.disconnect()
  2879. except Exception as e:
  2880. pass
  2881. # first deselect all rows (tools) in the Tools Table
  2882. self.tools_table_exc.clearSelection()
  2883. # and select the rows (tools) in the tool table according to the diameter(s) of the selected shape(s)
  2884. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2885. for storage in self.storage_dict:
  2886. for shape_s in self.selected:
  2887. if shape_s in self.storage_dict[storage].get_objects():
  2888. for key_tool_nr in self.tool2tooldia:
  2889. if self.tool2tooldia[key_tool_nr] == storage:
  2890. row_to_sel = key_tool_nr - 1
  2891. # item = self.tools_table_exc.item(row_to_sel, 1)
  2892. # self.tools_table_exc.setCurrentItem(item)
  2893. # item.setSelected(True)
  2894. # if the row to be selected is not already in the selected rows then select it
  2895. # otherwise don't do it as it seems that we have a toggle effect
  2896. if row_to_sel not in set(index.row() for index in self.tools_table_exc.selectedIndexes()):
  2897. self.tools_table_exc.selectRow(row_to_sel)
  2898. self.last_tool_selected = int(key_tool_nr)
  2899. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2900. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2901. self.replot()
  2902. def on_canvas_move(self, event):
  2903. """
  2904. Called on 'mouse_move' event.
  2905. It updates the mouse cursor if the grid snapping is ON.
  2906. 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
  2907. class object which is used in the "mouse_release" handler to decide if to pop-up the context menu or not.
  2908. It draws utility_geometry for the Editor tools.
  2909. Update the position labels from status bar.
  2910. Decide if we have a right to left or a left to right mouse drag with left mouse button and call a function
  2911. that will draw a selection shape on canvas.
  2912. event.pos have canvas screen coordinates
  2913. :param event: Event object dispatched by VisPy SceneCavas
  2914. :return: None
  2915. """
  2916. pos = self.canvas.translate_coords(event.pos)
  2917. event.xdata, event.ydata = pos[0], pos[1]
  2918. self.x = event.xdata
  2919. self.y = event.ydata
  2920. self.app.ui.popMenu.mouse_is_panning = False
  2921. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2922. if event.button == 2 and event.is_dragging == 1:
  2923. self.app.ui.popMenu.mouse_is_panning = True
  2924. return
  2925. try:
  2926. x = float(event.xdata)
  2927. y = float(event.ydata)
  2928. except TypeError:
  2929. return
  2930. if self.active_tool is None:
  2931. return
  2932. # ## Snap coordinates
  2933. if self.app.grid_status() == True:
  2934. x, y = self.app.geo_editor.snap(x, y)
  2935. self.app.app_cursor.enabled = True
  2936. # Update cursor
  2937. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2938. else:
  2939. self.app.app_cursor.enabled = False
  2940. self.snap_x = x
  2941. self.snap_y = y
  2942. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2943. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2944. "<b>Y</b>: %.4f" % (x, y))
  2945. if self.pos is None:
  2946. self.pos = (0, 0)
  2947. dx = x - self.pos[0]
  2948. dy = y - self.pos[1]
  2949. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2950. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2951. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2952. # ## Utility geometry (animated)
  2953. geo = self.active_tool.utility_geometry(data=(x, y))
  2954. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2955. # Remove any previous utility shape
  2956. self.tool_shape.clear(update=True)
  2957. self.draw_utility_geometry(geo=geo)
  2958. # ## Selection area on canvas section # ##
  2959. if event.is_dragging == 1 and event.button == 1:
  2960. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2961. # can create strange issues. Also for FCSlot and FCSlotArray
  2962. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray) or \
  2963. isinstance(self.active_tool, FCSlot) or isinstance(self.active_tool, FCSlotArray):
  2964. self.app.selection_type = None
  2965. else:
  2966. dx = pos[0] - self.pos[0]
  2967. self.app.delete_selection_shape()
  2968. if dx < 0:
  2969. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2970. color=self.app.defaults["global_alt_sel_line"],
  2971. face_color=self.app.defaults['global_alt_sel_fill'])
  2972. self.app.selection_type = False
  2973. else:
  2974. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2975. self.app.selection_type = True
  2976. else:
  2977. self.app.selection_type = None
  2978. # Update cursor
  2979. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2980. def on_canvas_key_release(self, event):
  2981. self.key = None
  2982. def draw_utility_geometry(self, geo):
  2983. # Add the new utility shape
  2984. try:
  2985. # this case is for the Font Parse
  2986. for el in list(geo.geo):
  2987. if type(el) == MultiPolygon:
  2988. for poly in el:
  2989. self.tool_shape.add(
  2990. shape=poly,
  2991. color=(self.app.defaults["global_draw_color"] + '80'),
  2992. update=False,
  2993. layer=0,
  2994. tolerance=None
  2995. )
  2996. elif type(el) == MultiLineString:
  2997. for linestring in el:
  2998. self.tool_shape.add(
  2999. shape=linestring,
  3000. color=(self.app.defaults["global_draw_color"] + '80'),
  3001. update=False,
  3002. layer=0,
  3003. tolerance=None
  3004. )
  3005. else:
  3006. self.tool_shape.add(
  3007. shape=el,
  3008. color=(self.app.defaults["global_draw_color"] + '80'),
  3009. update=False,
  3010. layer=0,
  3011. tolerance=None
  3012. )
  3013. except TypeError:
  3014. self.tool_shape.add(
  3015. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3016. update=False, layer=0, tolerance=None)
  3017. self.tool_shape.redraw()
  3018. def replot(self):
  3019. self.plot_all()
  3020. def plot_all(self):
  3021. """
  3022. Plots all shapes in the editor.
  3023. :return: None
  3024. :rtype: None
  3025. """
  3026. # self.app.log.debug("plot_all()")
  3027. self.shapes.clear(update=True)
  3028. for storage in self.storage_dict:
  3029. for shape_plus in self.storage_dict[storage].get_objects():
  3030. if shape_plus.geo is None:
  3031. continue
  3032. if shape_plus in self.selected:
  3033. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  3034. linewidth=2)
  3035. continue
  3036. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  3037. # for shape in self.storage.get_objects():
  3038. # if shape.geo is None: # TODO: This shouldn't have happened
  3039. # continue
  3040. #
  3041. # if shape in self.selected:
  3042. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3043. # continue
  3044. #
  3045. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3046. for shape_form in self.utility:
  3047. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  3048. continue
  3049. self.shapes.redraw()
  3050. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3051. """
  3052. Plots a geometric object or list of objects without rendering. Plotted objects
  3053. are returned as a list. This allows for efficient/animated rendering.
  3054. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3055. :param color: Shape color
  3056. :param linewidth: Width of lines in # of pixels.
  3057. :return: List of plotted elements.
  3058. """
  3059. plot_elements = []
  3060. if geometry is None:
  3061. geometry = self.active_tool.geometry
  3062. try:
  3063. for geo in geometry:
  3064. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3065. # ## Non-iterable
  3066. except TypeError:
  3067. # ## DrawToolShape
  3068. if isinstance(geometry, DrawToolShape):
  3069. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3070. # ## Polygon: Descend into exterior and each interior.
  3071. if type(geometry) == Polygon:
  3072. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3073. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3074. if type(geometry) == LineString or type(geometry) == LinearRing:
  3075. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0, tolerance=self.tolerance))
  3076. if type(geometry) == Point:
  3077. pass
  3078. return plot_elements
  3079. def on_shape_complete(self):
  3080. self.app.log.debug("on_shape_complete()")
  3081. # Add shape
  3082. self.add_shape(self.active_tool.geometry)
  3083. # Remove any utility shapes
  3084. self.delete_utility_geometry()
  3085. self.tool_shape.clear(update=True)
  3086. # Replot and reset tool.
  3087. self.replot()
  3088. # self.active_tool = type(self.active_tool)(self)
  3089. def get_selected(self):
  3090. """
  3091. Returns list of shapes that are selected in the editor.
  3092. :return: List of shapes.
  3093. """
  3094. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3095. return self.selected
  3096. def delete_selected(self):
  3097. temp_ref = [s for s in self.selected]
  3098. for shape_sel in temp_ref:
  3099. self.delete_shape(shape_sel)
  3100. self.selected = []
  3101. self.build_ui()
  3102. self.app.inform.emit('[success] %s' %
  3103. _("Done. Drill(s) deleted."))
  3104. def delete_shape(self, del_shape):
  3105. self.is_modified = True
  3106. if del_shape in self.utility:
  3107. self.utility.remove(del_shape)
  3108. return
  3109. for storage in self.storage_dict:
  3110. # try:
  3111. # self.storage_dict[storage].remove(shape)
  3112. # except:
  3113. # pass
  3114. if del_shape in self.storage_dict[storage].get_objects():
  3115. if isinstance(del_shape.geo, MultiLineString):
  3116. self.storage_dict[storage].remove(del_shape)
  3117. # a hack to make the tool_table display less drills per diameter
  3118. # self.points_edit it's only useful first time when we load the data into the storage
  3119. # but is still used as referecen when building tool_table in self.build_ui()
  3120. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  3121. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  3122. del self.points_edit[storage][0]
  3123. else:
  3124. self.storage_dict[storage].remove(del_shape)
  3125. del self.slot_points_edit[storage][0]
  3126. if del_shape in self.selected:
  3127. self.selected.remove(del_shape) # TODO: Check performance
  3128. def delete_utility_geometry(self):
  3129. for_deletion = [util_shape for util_shape in self.utility]
  3130. for util_shape in for_deletion:
  3131. self.delete_shape(util_shape)
  3132. self.tool_shape.clear(update=True)
  3133. self.tool_shape.redraw()
  3134. def on_delete_btn(self):
  3135. self.delete_selected()
  3136. self.replot()
  3137. def select_tool(self, toolname):
  3138. """
  3139. Selects a drawing tool. Impacts the object and GUI.
  3140. :param toolname: Name of the tool.
  3141. :return: None
  3142. """
  3143. self.tools_exc[toolname]["button"].setChecked(True)
  3144. self.on_tool_select(toolname)
  3145. def set_selected(self, sel_shape):
  3146. # Remove and add to the end.
  3147. if sel_shape in self.selected:
  3148. self.selected.remove(sel_shape)
  3149. self.selected.append(sel_shape)
  3150. def set_unselected(self, unsel_shape):
  3151. if unsel_shape in self.selected:
  3152. self.selected.remove(unsel_shape)
  3153. def on_array_type_combo(self):
  3154. if self.array_type_combo.currentIndex() == 0:
  3155. self.array_circular_frame.hide()
  3156. self.array_linear_frame.show()
  3157. else:
  3158. self.delete_utility_geometry()
  3159. self.array_circular_frame.show()
  3160. self.array_linear_frame.hide()
  3161. self.app.inform.emit(_("Click on the circular array Center position"))
  3162. def on_slot_array_type_combo(self):
  3163. if self.slot_array_type_combo.currentIndex() == 0:
  3164. self.slot_array_circular_frame.hide()
  3165. self.slot_array_linear_frame.show()
  3166. else:
  3167. self.delete_utility_geometry()
  3168. self.slot_array_circular_frame.show()
  3169. self.slot_array_linear_frame.hide()
  3170. self.app.inform.emit(_("Click on the circular array Center position"))
  3171. def on_linear_angle_radio(self):
  3172. val = self.drill_axis_radio.get_value()
  3173. if val == 'A':
  3174. self.linear_angle_spinner.show()
  3175. self.linear_angle_label.show()
  3176. else:
  3177. self.linear_angle_spinner.hide()
  3178. self.linear_angle_label.hide()
  3179. def on_slot_array_linear_angle_radio(self):
  3180. val = self.slot_array_axis_radio.get_value()
  3181. if val == 'A':
  3182. self.slot_array_linear_angle_spinner.show()
  3183. self.slot_array_linear_angle_label.show()
  3184. else:
  3185. self.slot_array_linear_angle_spinner.hide()
  3186. self.slot_array_linear_angle_label.hide()
  3187. def on_slot_angle_radio(self):
  3188. val = self.slot_axis_radio.get_value()
  3189. if val == 'A':
  3190. self.slot_angle_spinner.show()
  3191. self.slot_angle_label.show()
  3192. else:
  3193. self.slot_angle_spinner.hide()
  3194. self.slot_angle_label.hide()
  3195. def exc_add_drill(self):
  3196. self.select_tool('drill_add')
  3197. return
  3198. def exc_add_drill_array(self):
  3199. self.select_tool('drill_array')
  3200. return
  3201. def exc_add_slot(self):
  3202. self.select_tool('slot_add')
  3203. return
  3204. def exc_add_slot_array(self):
  3205. self.select_tool('slot_array')
  3206. return
  3207. def exc_resize_drills(self):
  3208. self.select_tool('drill_resize')
  3209. return
  3210. def exc_copy_drills(self):
  3211. self.select_tool('drill_copy')
  3212. return
  3213. def exc_move_drills(self):
  3214. self.select_tool('drill_move')
  3215. return
  3216. def get_shapely_list_bounds(geometry_list):
  3217. xmin = Inf
  3218. ymin = Inf
  3219. xmax = -Inf
  3220. ymax = -Inf
  3221. for gs in geometry_list:
  3222. try:
  3223. gxmin, gymin, gxmax, gymax = gs.bounds
  3224. xmin = min([xmin, gxmin])
  3225. ymin = min([ymin, gymin])
  3226. xmax = max([xmax, gxmax])
  3227. ymax = max([ymax, gymax])
  3228. except Exception as e:
  3229. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3230. return [xmin, ymin, xmax, ymax]
  3231. # EOF