AppExcEditor.py 195 KB

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