FlatCAMExcEditor.py 137 KB

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