AppExcEditor.py 182 KB

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