FlatCAMExcEditor.py 163 KB

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