AppExcEditor.py 194 KB

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