AppExcEditor.py 196 KB

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