FlatCAMExcEditor.py 170 KB

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