AppExcEditor.py 176 KB

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