AppExcEditor.py 190 KB

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