AppExcEditor.py 185 KB

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