AppExcEditor.py 185 KB

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