FlatCAMExcEditor.py 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512
  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. try:
  398. self.geometry = DrawToolShape(self.util_shape(self.points))
  399. except Exception as e:
  400. log.debug("FCSlot.make() --> %s" % str(e))
  401. # add the point to drills/slots if the diameter is a key in the dict, if not, create it add the drill location
  402. # to the value, as a list of itself
  403. if self.selected_dia in self.draw_app.slot_points_edit:
  404. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  405. else:
  406. self.draw_app.slot_points_edit[self.selected_dia] = [self.points]
  407. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  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. xmin, ymin, xmax, ymax = 0, 0, 0, 0
  944. try:
  945. for storage in self.exc_editor_app.storage_dict:
  946. for sh in self.exc_editor_app.storage_dict[storage].get_objects():
  947. self.sel_storage.insert(sh)
  948. _, closest_shape = self.sel_storage.nearest(pos)
  949. # constrain selection to happen only within a certain bounding box; it works only for MultiLineStrings
  950. if isinstance(closest_shape.geo, MultiLineString):
  951. x_coord, y_coord = closest_shape.geo[0].xy
  952. delta = (x_coord[1] - x_coord[0])
  953. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  954. xmin = x_coord[0] - (0.7 * delta)
  955. xmax = x_coord[0] + (1.7 * delta)
  956. ymin = y_coord[0] - (0.7 * delta)
  957. ymax = y_coord[0] + (1.7 * delta)
  958. elif isinstance(closest_shape.geo, Polygon):
  959. xmin, ymin, xmax, ymax = closest_shape.geo.bounds
  960. dx = xmax - xmin
  961. dy = ymax - ymin
  962. delta = dx if dx > dy else dy
  963. xmin -= 0.7 * delta
  964. xmax += 0.7 * delta
  965. ymin -= 0.7 * delta
  966. ymax += 0.7 * delta
  967. except StopIteration:
  968. return ""
  969. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  970. self.exc_editor_app.selected = []
  971. else:
  972. modifiers = QtWidgets.QApplication.keyboardModifiers()
  973. mod_key = 'Control'
  974. if modifiers == QtCore.Qt.ShiftModifier:
  975. mod_key = 'Shift'
  976. elif modifiers == QtCore.Qt.ControlModifier:
  977. mod_key = 'Control'
  978. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  979. if closest_shape in self.exc_editor_app.selected:
  980. self.exc_editor_app.selected.remove(closest_shape)
  981. else:
  982. self.exc_editor_app.selected.append(closest_shape)
  983. else:
  984. self.draw_app.selected = []
  985. self.draw_app.selected.append(closest_shape)
  986. # select the diameter of the selected shape in the tool table
  987. try:
  988. self.draw_app.tools_table_exc.cellPressed.disconnect()
  989. except (TypeError, AttributeError):
  990. pass
  991. sel_tools = set()
  992. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  993. for shape_s in self.exc_editor_app.selected:
  994. for storage in self.exc_editor_app.storage_dict:
  995. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  996. sel_tools.add(storage)
  997. for storage in sel_tools:
  998. for k, v in self.draw_app.tool2tooldia.items():
  999. if v == storage:
  1000. self.exc_editor_app.tools_table_exc.selectRow(int(k) - 1)
  1001. self.draw_app.last_tool_selected = int(k)
  1002. break
  1003. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1004. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  1005. # delete whatever is in selection storage, there is no longer need for those shapes
  1006. self.sel_storage = FlatCAMExcEditor.make_storage()
  1007. return ""
  1008. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1009. # for storage in self.exc_editor_app.storage_dict:
  1010. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1011. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1012. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1013. # over_shape_list.append(obj_shape)
  1014. #
  1015. # try:
  1016. # # if there is no shape under our click then deselect all shapes
  1017. # if not over_shape_list:
  1018. # self.exc_editor_app.selected = []
  1019. # FlatCAMExcEditor.draw_shape_idx = -1
  1020. # self.exc_editor_app.tools_table_exc.clearSelection()
  1021. # else:
  1022. # # if there are shapes under our click then advance through the list of them, one at the time in a
  1023. # # circular way
  1024. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  1025. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  1026. #
  1027. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  1028. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  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. # else:
  1037. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1038. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  1039. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  1040. # if obj_to_add in self.exc_editor_app.selected:
  1041. # self.exc_editor_app.selected.remove(obj_to_add)
  1042. # else:
  1043. # self.exc_editor_app.selected.append(obj_to_add)
  1044. # else:
  1045. # self.exc_editor_app.selected = []
  1046. # self.exc_editor_app.selected.append(obj_to_add)
  1047. #
  1048. # for storage in self.exc_editor_app.storage_dict:
  1049. # for shape in self.exc_editor_app.selected:
  1050. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1051. # for key in self.exc_editor_app.tool2tooldia:
  1052. # if self.exc_editor_app.tool2tooldia[key] == storage:
  1053. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1054. # item.setSelected(True)
  1055. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1056. #
  1057. # except Exception as e:
  1058. # log.error("[ERROR] Something went bad. %s" % str(e))
  1059. # raise
  1060. class FlatCAMExcEditor(QtCore.QObject):
  1061. draw_shape_idx = -1
  1062. def __init__(self, app):
  1063. assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1064. super(FlatCAMExcEditor, self).__init__()
  1065. self.app = app
  1066. self.canvas = self.app.plotcanvas
  1067. # ## Current application units in Upper Case
  1068. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1069. self.exc_edit_widget = QtWidgets.QWidget()
  1070. # ## Box for custom widgets
  1071. # This gets populated in offspring implementations.
  1072. layout = QtWidgets.QVBoxLayout()
  1073. self.exc_edit_widget.setLayout(layout)
  1074. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1075. # this way I can hide/show the frame
  1076. self.drills_frame = QtWidgets.QFrame()
  1077. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  1078. layout.addWidget(self.drills_frame)
  1079. self.tools_box = QtWidgets.QVBoxLayout()
  1080. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1081. self.drills_frame.setLayout(self.tools_box)
  1082. # ## Page Title box (spacing between children)
  1083. self.title_box = QtWidgets.QHBoxLayout()
  1084. self.tools_box.addLayout(self.title_box)
  1085. # ## Page Title icon
  1086. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1087. self.icon = QtWidgets.QLabel()
  1088. self.icon.setPixmap(pixmap)
  1089. self.title_box.addWidget(self.icon, stretch=0)
  1090. # ## Title label
  1091. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  1092. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1093. self.title_box.addWidget(self.title_label, stretch=1)
  1094. # ## Object name
  1095. self.name_box = QtWidgets.QHBoxLayout()
  1096. self.tools_box.addLayout(self.name_box)
  1097. name_label = QtWidgets.QLabel(_("Name:"))
  1098. self.name_box.addWidget(name_label)
  1099. self.name_entry = FCEntry()
  1100. self.name_box.addWidget(self.name_entry)
  1101. # ### Tools Drills ## ##
  1102. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  1103. self.tools_table_label.setToolTip(
  1104. _("Tools in this Excellon object\n"
  1105. "when are used for drilling.")
  1106. )
  1107. self.tools_box.addWidget(self.tools_table_label)
  1108. self.tools_table_exc = FCTable()
  1109. # delegate = SpinBoxDelegate(units=self.units)
  1110. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  1111. self.tools_box.addWidget(self.tools_table_exc)
  1112. self.tools_table_exc.setColumnCount(4)
  1113. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1114. self.tools_table_exc.setSortingEnabled(False)
  1115. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1116. self.empty_label = QtWidgets.QLabel('')
  1117. self.tools_box.addWidget(self.empty_label)
  1118. # ### Add a new Tool ## ##
  1119. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  1120. self.addtool_label.setToolTip(
  1121. _("Add/Delete a tool to the tool list\n"
  1122. "for this Excellon object.")
  1123. )
  1124. self.tools_box.addWidget(self.addtool_label)
  1125. grid1 = QtWidgets.QGridLayout()
  1126. self.tools_box.addLayout(grid1)
  1127. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  1128. addtool_entry_lbl.setToolTip(
  1129. _("Diameter for the new tool")
  1130. )
  1131. hlay = QtWidgets.QHBoxLayout()
  1132. self.addtool_entry = FCEntry()
  1133. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1134. hlay.addWidget(self.addtool_entry)
  1135. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  1136. self.addtool_btn.setToolTip(
  1137. _("Add a new tool to the tool list\n"
  1138. "with the diameter specified above.")
  1139. )
  1140. self.addtool_btn.setFixedWidth(80)
  1141. hlay.addWidget(self.addtool_btn)
  1142. grid1.addWidget(addtool_entry_lbl, 0, 0)
  1143. grid1.addLayout(hlay, 0, 1)
  1144. grid2 = QtWidgets.QGridLayout()
  1145. self.tools_box.addLayout(grid2)
  1146. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  1147. self.deltool_btn.setToolTip(
  1148. _("Delete a tool in the tool list\n"
  1149. "by selecting a row in the tool table.")
  1150. )
  1151. grid2.addWidget(self.deltool_btn, 0, 1)
  1152. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1153. # this way I can hide/show the frame
  1154. self.resize_frame = QtWidgets.QFrame()
  1155. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  1156. self.tools_box.addWidget(self.resize_frame)
  1157. self.resize_box = QtWidgets.QVBoxLayout()
  1158. self.resize_box.setContentsMargins(0, 0, 0, 0)
  1159. self.resize_frame.setLayout(self.resize_box)
  1160. # ### Resize a drill ## ##
  1161. self.emptyresize_label = QtWidgets.QLabel('')
  1162. self.resize_box.addWidget(self.emptyresize_label)
  1163. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  1164. self.drillresize_label.setToolTip(
  1165. _("Resize a drill or a selection of drills.")
  1166. )
  1167. self.resize_box.addWidget(self.drillresize_label)
  1168. grid3 = QtWidgets.QGridLayout()
  1169. self.resize_box.addLayout(grid3)
  1170. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  1171. res_entry_lbl.setToolTip(
  1172. _("Diameter to resize to.")
  1173. )
  1174. grid3.addWidget(res_entry_lbl, 0, 0)
  1175. hlay2 = QtWidgets.QHBoxLayout()
  1176. self.resdrill_entry = LengthEntry()
  1177. hlay2.addWidget(self.resdrill_entry)
  1178. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  1179. self.resize_btn.setToolTip(
  1180. _("Resize drill(s)")
  1181. )
  1182. self.resize_btn.setFixedWidth(80)
  1183. hlay2.addWidget(self.resize_btn)
  1184. grid3.addLayout(hlay2, 0, 1)
  1185. self.resize_frame.hide()
  1186. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1187. # all the add drill array widgets
  1188. # this way I can hide/show the frame
  1189. self.array_frame = QtWidgets.QFrame()
  1190. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1191. self.tools_box.addWidget(self.array_frame)
  1192. self.array_box = QtWidgets.QVBoxLayout()
  1193. self.array_box.setContentsMargins(0, 0, 0, 0)
  1194. self.array_frame.setLayout(self.array_box)
  1195. # ### Add DRILL Array ## ##
  1196. self.emptyarray_label = QtWidgets.QLabel('')
  1197. self.array_box.addWidget(self.emptyarray_label)
  1198. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  1199. self.drillarray_label.setToolTip(
  1200. _("Add an array of drills (linear or circular array)")
  1201. )
  1202. self.array_box.addWidget(self.drillarray_label)
  1203. self.array_type_combo = FCComboBox()
  1204. self.array_type_combo.setToolTip(
  1205. _("Select the type of drills array to create.\n"
  1206. "It can be Linear X(Y) or Circular")
  1207. )
  1208. self.array_type_combo.addItem(_("Linear"))
  1209. self.array_type_combo.addItem(_("Circular"))
  1210. self.array_box.addWidget(self.array_type_combo)
  1211. self.array_form = QtWidgets.QFormLayout()
  1212. self.array_box.addLayout(self.array_form)
  1213. # Set the number of drill holes in the drill array
  1214. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  1215. self.drill_array_size_label.setToolTip(_("Specify how many drills to be in the array."))
  1216. self.drill_array_size_label.setMinimumWidth(100)
  1217. self.drill_array_size_entry = LengthEntry()
  1218. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  1219. self.array_linear_frame = QtWidgets.QFrame()
  1220. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1221. self.array_box.addWidget(self.array_linear_frame)
  1222. self.linear_box = QtWidgets.QVBoxLayout()
  1223. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1224. self.array_linear_frame.setLayout(self.linear_box)
  1225. self.linear_form = QtWidgets.QFormLayout()
  1226. self.linear_box.addLayout(self.linear_form)
  1227. # Linear Drill Array direction
  1228. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  1229. self.drill_axis_label.setToolTip(
  1230. _("Direction on which the linear array is oriented:\n"
  1231. "- 'X' - horizontal axis \n"
  1232. "- 'Y' - vertical axis or \n"
  1233. "- 'Angle' - a custom angle for the array inclination")
  1234. )
  1235. self.drill_axis_label.setFixedWidth(100)
  1236. self.drill_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1237. {'label': _('Y'), 'value': 'Y'},
  1238. {'label': _('Angle'), 'value': 'A'}])
  1239. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  1240. # Linear Drill Array pitch distance
  1241. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1242. self.drill_pitch_label.setToolTip(
  1243. _("Pitch = Distance between elements of the array.")
  1244. )
  1245. self.drill_pitch_label.setFixedWidth(100)
  1246. self.drill_pitch_entry = LengthEntry()
  1247. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  1248. # Linear Drill Array angle
  1249. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1250. self.linear_angle_label.setToolTip(
  1251. _("Angle at which the linear array is placed.\n"
  1252. "The precision is of max 2 decimals.\n"
  1253. "Min value is: -359.99 degrees.\n"
  1254. "Max value is: 360.00 degrees.")
  1255. )
  1256. self.linear_angle_label.setFixedWidth(100)
  1257. self.linear_angle_spinner = FCDoubleSpinner()
  1258. self.linear_angle_spinner.set_precision(2)
  1259. self.linear_angle_spinner.setSingleStep(1.0)
  1260. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1261. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1262. self.array_circular_frame = QtWidgets.QFrame()
  1263. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1264. self.array_box.addWidget(self.array_circular_frame)
  1265. self.circular_box = QtWidgets.QVBoxLayout()
  1266. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1267. self.array_circular_frame.setLayout(self.circular_box)
  1268. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  1269. self.drill_direction_label.setToolTip(_("Direction for circular array."
  1270. "Can be CW = clockwise or CCW = counter clockwise."))
  1271. self.drill_direction_label.setFixedWidth(100)
  1272. self.circular_form = QtWidgets.QFormLayout()
  1273. self.circular_box.addLayout(self.circular_form)
  1274. self.drill_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1275. {'label': _('CCW'), 'value': 'CCW'}])
  1276. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  1277. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  1278. self.drill_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1279. self.drill_angle_label.setMinimumWidth(100)
  1280. self.drill_angle_entry = LengthEntry()
  1281. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  1282. self.array_circular_frame.hide()
  1283. self.linear_angle_spinner.hide()
  1284. self.linear_angle_label.hide()
  1285. self.array_frame.hide()
  1286. # ######################################################
  1287. # ##### ADDING SLOTS ###################################
  1288. # ######################################################
  1289. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1290. # all the add slot widgets
  1291. # this way I can hide/show the frame
  1292. self.slot_frame = QtWidgets.QFrame()
  1293. self.slot_frame.setContentsMargins(0, 0, 0, 0)
  1294. self.tools_box.addWidget(self.slot_frame)
  1295. self.slot_box = QtWidgets.QVBoxLayout()
  1296. self.slot_box.setContentsMargins(0, 0, 0, 0)
  1297. self.slot_frame.setLayout(self.slot_box)
  1298. self.emptyarray_label = QtWidgets.QLabel('')
  1299. self.slot_box.addWidget(self.emptyarray_label)
  1300. self.slot_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Slot"))
  1301. self.slot_label.setToolTip(
  1302. _("Add slot (hole with oval shape)")
  1303. )
  1304. self.slot_box.addWidget(self.slot_label)
  1305. self.slot_form = QtWidgets.QFormLayout()
  1306. self.slot_box.addLayout(self.slot_form)
  1307. # Slot length
  1308. self.slot_length_label = QtWidgets.QLabel(_('Length:'))
  1309. self.slot_length_label.setToolTip(
  1310. _("Length = The length of the slot.")
  1311. )
  1312. self.slot_length_label.setMinimumWidth(100)
  1313. self.slot_length_entry = LengthEntry()
  1314. self.slot_form.addRow(self.slot_length_label, self.slot_length_entry)
  1315. # Slot direction
  1316. self.slot_axis_label = QtWidgets.QLabel(_('Direction:'))
  1317. self.slot_axis_label.setToolTip(
  1318. _("Direction on which the slot is oriented:\n"
  1319. "- 'X' - horizontal axis \n"
  1320. "- 'Y' - vertical axis or \n"
  1321. "- 'Angle' - a custom angle for the slot inclination")
  1322. )
  1323. self.slot_axis_label.setMinimumWidth(100)
  1324. self.slot_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1325. {'label': _('Y'), 'value': 'Y'},
  1326. {'label': _('Angle'), 'value': 'A'}])
  1327. self.slot_form.addRow(self.slot_axis_label, self.slot_axis_radio)
  1328. # Slot custom angle
  1329. self.slot_angle_label = QtWidgets.QLabel(_('Angle:'))
  1330. self.slot_angle_label.setToolTip(
  1331. _("Angle at which the slot is placed.\n"
  1332. "The precision is of max 2 decimals.\n"
  1333. "Min value is: -359.99 degrees.\n"
  1334. "Max value is: 360.00 degrees.")
  1335. )
  1336. self.slot_angle_label.setMinimumWidth(100)
  1337. self.slot_angle_spinner = FCDoubleSpinner()
  1338. self.slot_angle_spinner.set_precision(2)
  1339. self.slot_angle_spinner.setWrapping(True)
  1340. self.slot_angle_spinner.setRange(-359.99, 360.00)
  1341. self.slot_angle_spinner.setSingleStep(1.0)
  1342. self.slot_form.addRow(self.slot_angle_label, self.slot_angle_spinner)
  1343. self.slot_frame.hide()
  1344. self.tools_box.addStretch()
  1345. # ## Toolbar events and properties
  1346. self.tools_exc = {
  1347. "drill_select": {"button": self.app.ui.select_drill_btn,
  1348. "constructor": FCDrillSelect},
  1349. "drill_add": {"button": self.app.ui.add_drill_btn,
  1350. "constructor": FCDrillAdd},
  1351. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  1352. "constructor": FCDrillArray},
  1353. "drill_slot": {"button": self.app.ui.add_slot_btn,
  1354. "constructor": FCSlot},
  1355. "drill_slotarray": {"button": self.app.ui.add_slot_array_btn,
  1356. "constructor": FCSlotArray},
  1357. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  1358. "constructor": FCDrillResize},
  1359. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  1360. "constructor": FCDrillCopy},
  1361. "drill_move": {"button": self.app.ui.move_drill_btn,
  1362. "constructor": FCDrillMove},
  1363. }
  1364. # ## Data
  1365. self.active_tool = None
  1366. self.in_action = False
  1367. self.storage_dict = {}
  1368. self.current_storage = []
  1369. # build the data from the Excellon point into a dictionary
  1370. # {tool_dia: [geometry_in_points]}
  1371. self.points_edit = {}
  1372. self.slot_points_edit = {}
  1373. self.sorted_diameters = []
  1374. self.new_drills = []
  1375. self.new_tools = {}
  1376. self.new_slots = []
  1377. self.new_tool_offset = {}
  1378. # dictionary to store the tool_row and diameters in Tool_table
  1379. # it will be updated everytime self.build_ui() is called
  1380. self.olddia_newdia = {}
  1381. self.tool2tooldia = {}
  1382. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1383. # is cleared but as a side effect also the selected tool is cleared
  1384. self.last_tool_selected = None
  1385. self.utility = []
  1386. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1387. self.launched_from_shortcuts = False
  1388. # this var will store the state of the toolbar before starting the editor
  1389. self.toolbar_old_state = False
  1390. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  1391. self.name_entry.returnPressed.connect(self.on_name_activate)
  1392. self.addtool_btn.clicked.connect(self.on_tool_add)
  1393. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  1394. self.deltool_btn.clicked.connect(self.on_tool_delete)
  1395. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1396. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1397. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1398. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1399. self.slot_axis_radio.activated_custom.connect(self.on_slot_angle_radio)
  1400. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  1401. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  1402. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  1403. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  1404. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  1405. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  1406. self.exc_obj = None
  1407. # VisPy Visuals
  1408. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1409. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1410. self.app.pool_recreated.connect(self.pool_recreated)
  1411. # Remove from scene
  1412. self.shapes.enabled = False
  1413. self.tool_shape.enabled = False
  1414. # ## List of selected shapes.
  1415. self.selected = []
  1416. self.move_timer = QtCore.QTimer()
  1417. self.move_timer.setSingleShot(True)
  1418. self.key = None # Currently pressed key
  1419. self.modifiers = None
  1420. self.x = None # Current mouse cursor pos
  1421. self.y = None
  1422. # Current snapped mouse pos
  1423. self.snap_x = None
  1424. self.snap_y = None
  1425. self.pos = None
  1426. self.complete = False
  1427. def make_callback(thetool):
  1428. def f():
  1429. self.on_tool_select(thetool)
  1430. return f
  1431. for tool in self.tools_exc:
  1432. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1433. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1434. self.options = {
  1435. "global_gridx": 0.1,
  1436. "global_gridy": 0.1,
  1437. "snap_max": 0.05,
  1438. "grid_snap": True,
  1439. "corner_snap": False,
  1440. "grid_gap_link": True
  1441. }
  1442. self.app.options_read_form()
  1443. for option in self.options:
  1444. if option in self.app.options:
  1445. self.options[option] = self.app.options[option]
  1446. self.rtree_exc_index = rtindex.Index()
  1447. # flag to show if the object was modified
  1448. self.is_modified = False
  1449. self.edited_obj_name = ""
  1450. # variable to store the total amount of drills per job
  1451. self.tot_drill_cnt = 0
  1452. self.tool_row = 0
  1453. # variable to store the total amount of slots per job
  1454. self.tot_slot_cnt = 0
  1455. self.tool_row_slots = 0
  1456. self.tool_row = 0
  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 entry2option(option, entry):
  1460. self.options[option] = float(entry.text())
  1461. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1462. self.editor_active = False
  1463. def pool_recreated(self, pool):
  1464. self.shapes.pool = pool
  1465. self.tool_shape.pool = pool
  1466. @staticmethod
  1467. def make_storage():
  1468. # ## Shape storage.
  1469. storage = FlatCAMRTreeStorage()
  1470. storage.get_points = DrawToolShape.get_pts
  1471. return storage
  1472. def set_ui(self):
  1473. # updated units
  1474. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1475. self.olddia_newdia.clear()
  1476. self.tool2tooldia.clear()
  1477. # build the self.points_edit dict {dimaters: [point_list]}
  1478. for drill in self.exc_obj.drills:
  1479. if drill['tool'] in self.exc_obj.tools:
  1480. if self.units == 'IN':
  1481. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1482. else:
  1483. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1484. try:
  1485. self.points_edit[tool_dia].append(drill['point'])
  1486. except KeyError:
  1487. self.points_edit[tool_dia] = [drill['point']]
  1488. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1489. for slot in self.exc_obj.slots:
  1490. if slot['tool'] in self.exc_obj.tools:
  1491. if self.units == 'IN':
  1492. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1493. else:
  1494. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1495. try:
  1496. self.slot_points_edit[tool_dia].append({
  1497. "start": slot["start"],
  1498. "stop": slot["stop"]
  1499. })
  1500. except KeyError:
  1501. self.slot_points_edit[tool_dia] = [{
  1502. "start": slot["start"],
  1503. "stop": slot["stop"]
  1504. }]
  1505. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1506. for key in self.points_edit:
  1507. self.olddia_newdia[key] = key
  1508. for key in self.slot_points_edit:
  1509. if key not in self.olddia_newdia:
  1510. self.olddia_newdia[key] = key
  1511. sort_temp = []
  1512. for diam in self.olddia_newdia:
  1513. sort_temp.append(float(diam))
  1514. self.sorted_diameters = sorted(sort_temp)
  1515. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1516. if self.exc_obj.diameterless is False:
  1517. for i in range(len(self.sorted_diameters)):
  1518. tt_dia = self.sorted_diameters[i]
  1519. self.tool2tooldia[i + 1] = tt_dia
  1520. else:
  1521. # the Excellon object has diameters that are bogus information, added by the application because the
  1522. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1523. # but use the real order found in the exc_obj.tools
  1524. for k, v in self.exc_obj.tools.items():
  1525. if self.units == 'IN':
  1526. tool_dia = float('%.4f' % v['C'])
  1527. else:
  1528. tool_dia = float('%.2f' % v['C'])
  1529. self.tool2tooldia[int(k)] = tool_dia
  1530. # Init GUI
  1531. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1532. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1533. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1534. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1535. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1536. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1537. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1538. self.slot_length_entry.set_value(1.0)
  1539. self.slot_axis_radio.set_value('X')
  1540. self.slot_angle_spinner.set_value(0.0)
  1541. def build_ui(self, first_run=None):
  1542. try:
  1543. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1544. self.tools_table_exc.itemChanged.disconnect()
  1545. except (TypeError, AttributeError):
  1546. pass
  1547. try:
  1548. self.tools_table_exc.cellPressed.disconnect()
  1549. except (TypeError, AttributeError):
  1550. pass
  1551. # updated units
  1552. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1553. # make a new name for the new Excellon object (the one with edited content)
  1554. self.edited_obj_name = self.exc_obj.options['name']
  1555. self.name_entry.set_value(self.edited_obj_name)
  1556. sort_temp = []
  1557. for diam in self.olddia_newdia:
  1558. sort_temp.append(float(diam))
  1559. self.sorted_diameters = sorted(sort_temp)
  1560. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1561. n = len(self.sorted_diameters)
  1562. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1563. self.tools_table_exc.setRowCount(n + 2)
  1564. self.tot_drill_cnt = 0
  1565. self.tot_slot_cnt = 0
  1566. self.tool_row = 0
  1567. # this variable will serve as the real tool_number
  1568. tool_id = 0
  1569. for tool_no in self.sorted_diameters:
  1570. tool_id += 1
  1571. drill_cnt = 0 # variable to store the nr of drills per tool
  1572. slot_cnt = 0 # variable to store the nr of slots per tool
  1573. # Find no of drills for the current tool
  1574. for tool_dia in self.points_edit:
  1575. if float(tool_dia) == tool_no:
  1576. drill_cnt = len(self.points_edit[tool_dia])
  1577. self.tot_drill_cnt += drill_cnt
  1578. try:
  1579. # Find no of slots for the current tool
  1580. for slot in self.slots:
  1581. if slot['tool'] == tool_no:
  1582. slot_cnt += 1
  1583. self.tot_slot_cnt += slot_cnt
  1584. except AttributeError:
  1585. # log.debug("No slots in the Excellon file")
  1586. # Find no of slots for the current tool
  1587. for tool_dia in self.slot_points_edit:
  1588. if float(tool_dia) == tool_no:
  1589. slot_cnt = len(self.slot_points_edit[tool_dia])
  1590. self.tot_slot_cnt += slot_cnt
  1591. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1592. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1593. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1594. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1595. # There are no drill bits in MM with more than 3 decimals diameter
  1596. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1597. if self.units == 'MM':
  1598. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1599. else:
  1600. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1601. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1602. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1603. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1604. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1605. if slot_cnt > 0:
  1606. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1607. else:
  1608. slot_count = QtWidgets.QTableWidgetItem('')
  1609. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1610. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1611. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1612. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1613. if first_run is True:
  1614. # set now the last tool selected
  1615. self.last_tool_selected = int(tool_id)
  1616. self.tool_row += 1
  1617. # make the diameter column editable
  1618. for row in range(self.tool_row):
  1619. self.tools_table_exc.item(row, 1).setFlags(
  1620. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1621. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1622. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1623. # add a last row with the Total number of drills
  1624. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1625. # it will have to have the foreground color (font color) white
  1626. empty = QtWidgets.QTableWidgetItem('9998')
  1627. empty.setForeground(QtGui.QColor(255, 255, 255))
  1628. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1629. empty_b = QtWidgets.QTableWidgetItem('')
  1630. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1631. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1632. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1633. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1634. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1635. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1636. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1637. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1638. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1639. font = QtGui.QFont()
  1640. font.setBold(True)
  1641. font.setWeight(75)
  1642. for k in [1, 2]:
  1643. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1644. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1645. self.tool_row += 1
  1646. # add a last row with the Total number of slots
  1647. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1648. # it will have to have the foreground color (font color) white
  1649. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1650. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1651. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1652. empty_3 = QtWidgets.QTableWidgetItem('')
  1653. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1654. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1655. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1656. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1657. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1658. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1659. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1660. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1661. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1662. for kl in [1, 2, 3]:
  1663. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1664. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1665. # all the tools are selected by default
  1666. self.tools_table_exc.selectColumn(0)
  1667. #
  1668. self.tools_table_exc.resizeColumnsToContents()
  1669. self.tools_table_exc.resizeRowsToContents()
  1670. vertical_header = self.tools_table_exc.verticalHeader()
  1671. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1672. vertical_header.hide()
  1673. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1674. horizontal_header = self.tools_table_exc.horizontalHeader()
  1675. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1676. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1677. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1678. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1679. # horizontal_header.setStretchLastSection(True)
  1680. # self.tools_table_exc.setSortingEnabled(True)
  1681. # sort by tool diameter
  1682. self.tools_table_exc.sortItems(1)
  1683. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1684. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1685. # use them
  1686. self.tool2tooldia.clear()
  1687. for row in range(self.tools_table_exc.rowCount() - 2):
  1688. tool = int(self.tools_table_exc.item(row, 0).text())
  1689. diameter = float(self.tools_table_exc.item(row, 1).text())
  1690. self.tool2tooldia[tool] = diameter
  1691. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1692. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1693. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1694. self.tools_table_exc.clearSelection()
  1695. # Remove anything else in the GUI Selected Tab
  1696. self.app.ui.selected_scroll_area.takeWidget()
  1697. # Put ourself in the GUI Selected Tab
  1698. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1699. # Switch notebook to Selected page
  1700. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1701. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1702. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1703. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1704. def on_tool_add(self, tooldia=None):
  1705. self.is_modified = True
  1706. if tooldia:
  1707. tool_dia = tooldia
  1708. else:
  1709. try:
  1710. tool_dia = float(self.addtool_entry.get_value())
  1711. except ValueError:
  1712. # try to convert comma to decimal point. if it's still not working error message and return
  1713. try:
  1714. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1715. except ValueError:
  1716. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1717. "use a number.")
  1718. )
  1719. return
  1720. if tool_dia not in self.olddia_newdia:
  1721. storage_elem = FlatCAMGeoEditor.make_storage()
  1722. self.storage_dict[tool_dia] = storage_elem
  1723. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1724. # each time a tool diameter is edited or added
  1725. self.olddia_newdia[tool_dia] = tool_dia
  1726. else:
  1727. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1728. "Save and reedit Excellon if you need to add this tool. ")
  1729. )
  1730. return
  1731. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1732. # we add a new entry in the tool2tooldia dict
  1733. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1734. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia),
  1735. units=str(self.units)))
  1736. self.build_ui()
  1737. # make a quick sort through the tool2tooldia dict so we find which row to select
  1738. row_to_be_selected = None
  1739. for key in sorted(self.tool2tooldia):
  1740. if self.tool2tooldia[key] == tool_dia:
  1741. row_to_be_selected = int(key) - 1
  1742. self.last_tool_selected = int(key)
  1743. break
  1744. self.tools_table_exc.selectRow(row_to_be_selected)
  1745. def on_tool_delete(self, dia=None):
  1746. self.is_modified = True
  1747. deleted_tool_dia_list = []
  1748. try:
  1749. if dia is None or dia is False:
  1750. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1751. for index in self.tools_table_exc.selectionModel().selectedRows():
  1752. row = index.row()
  1753. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1754. else:
  1755. if isinstance(dia, list):
  1756. for dd in dia:
  1757. deleted_tool_dia_list.append(float('%.4f' % dd))
  1758. else:
  1759. deleted_tool_dia_list.append(float('%.4f' % dia))
  1760. except Exception as e:
  1761. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1762. return
  1763. for deleted_tool_dia in deleted_tool_dia_list:
  1764. # delete de tool offset
  1765. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1766. # delete the storage used for that tool
  1767. storage_elem = FlatCAMGeoEditor.make_storage()
  1768. self.storage_dict[deleted_tool_dia] = storage_elem
  1769. self.storage_dict.pop(deleted_tool_dia, None)
  1770. # I've added this flag_del variable because dictionary don't like
  1771. # having keys deleted while iterating through them
  1772. flag_del = []
  1773. # self.points_edit.pop(deleted_tool_dia, None)
  1774. for deleted_tool in self.tool2tooldia:
  1775. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1776. flag_del.append(deleted_tool)
  1777. if flag_del:
  1778. for tool_to_be_deleted in flag_del:
  1779. # delete the tool
  1780. self.tool2tooldia.pop(tool_to_be_deleted, None)
  1781. # delete also the drills from points_edit dict just in case we add the tool again,
  1782. # we don't want to show the number of drills from before was deleter
  1783. self.points_edit[deleted_tool_dia] = []
  1784. self.olddia_newdia.pop(deleted_tool_dia, None)
  1785. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(
  1786. del_dia=str(deleted_tool_dia),
  1787. units=str(self.units)))
  1788. self.replot()
  1789. # self.app.inform.emit("Could not delete selected tool")
  1790. self.build_ui()
  1791. def on_tool_edit(self, item_changed):
  1792. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1793. self.tools_table_exc.itemChanged.disconnect()
  1794. self.tools_table_exc.cellPressed.disconnect()
  1795. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1796. self.is_modified = True
  1797. current_table_dia_edited = None
  1798. if self.tools_table_exc.currentItem() is not None:
  1799. try:
  1800. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  1801. except ValueError as e:
  1802. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1803. self.tools_table_exc.setCurrentItem(None)
  1804. return
  1805. row_of_item_changed = self.tools_table_exc.currentRow()
  1806. # rows start with 0, tools start with 1 so we adjust the value by 1
  1807. key_in_tool2tooldia = row_of_item_changed + 1
  1808. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1809. # tool diameter is not used so we create a new tool with the desired diameter
  1810. if current_table_dia_edited not in self.olddia_newdia.values():
  1811. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1812. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1813. # update the dict that holds tool_no as key and tool_dia as value
  1814. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1815. # update the tool offset
  1816. modified_offset = self.exc_obj.tool_offset.pop(dia_changed, None)
  1817. if modified_offset is not None:
  1818. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  1819. self.replot()
  1820. else:
  1821. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  1822. factor = current_table_dia_edited / dia_changed
  1823. geometry = []
  1824. for shape_exc in self.storage_dict[dia_changed].get_objects():
  1825. scaled_geo = MultiLineString(
  1826. [affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center') for subgeo in shape_exc.geo]
  1827. )
  1828. geometry.append(DrawToolShape(scaled_geo))
  1829. # add bogus drill points (for total count of drills)
  1830. for k, v in self.olddia_newdia.items():
  1831. if v == current_table_dia_edited:
  1832. self.points_edit[k].append((0, 0))
  1833. break
  1834. # search for the old dia that correspond to the new dia and add the drills in it's storage
  1835. # everything will be sort out later, when the edited Excellon is updated
  1836. for k, v in self.olddia_newdia.items():
  1837. if v == current_table_dia_edited:
  1838. self.add_exc_shape(geometry, self.storage_dict[k])
  1839. break
  1840. # delete the old tool from which we moved the drills
  1841. self.on_tool_delete(dia=dia_changed)
  1842. # delete the tool offset
  1843. self.exc_obj.tool_offset.pop(dia_changed, None)
  1844. # we reactivate the signals after the after the tool editing
  1845. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1846. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1847. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1848. def on_name_activate(self):
  1849. self.edited_obj_name = self.name_entry.get_value()
  1850. def activate(self):
  1851. # adjust the status of the menu entries related to the editor
  1852. self.app.ui.menueditedit.setDisabled(True)
  1853. self.app.ui.menueditok.setDisabled(False)
  1854. # adjust the visibility of some of the canvas context menu
  1855. self.app.ui.popmenu_edit.setVisible(False)
  1856. self.app.ui.popmenu_save.setVisible(True)
  1857. self.connect_canvas_event_handlers()
  1858. # initialize working objects
  1859. self.storage_dict = {}
  1860. self.current_storage = []
  1861. self.points_edit = {}
  1862. self.sorted_diameters = []
  1863. self.new_drills = []
  1864. self.new_tools = {}
  1865. self.new_slots = []
  1866. self.new_tool_offset = {}
  1867. self.olddia_newdia = {}
  1868. self.shapes.enabled = True
  1869. self.tool_shape.enabled = True
  1870. # self.app.app_cursor.enabled = True
  1871. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1872. self.app.ui.corner_snap_btn.setEnabled(True)
  1873. self.app.ui.snap_magnet.setVisible(True)
  1874. self.app.ui.corner_snap_btn.setVisible(True)
  1875. self.app.ui.exc_editor_menu.setDisabled(False)
  1876. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  1877. self.app.ui.update_obj_btn.setEnabled(True)
  1878. self.app.ui.e_editor_cmenu.setEnabled(True)
  1879. self.app.ui.exc_edit_toolbar.setDisabled(False)
  1880. self.app.ui.exc_edit_toolbar.setVisible(True)
  1881. # self.app.ui.snap_toolbar.setDisabled(False)
  1882. # start with GRID toolbar activated
  1883. if self.app.ui.grid_snap_btn.isChecked() is False:
  1884. self.app.ui.grid_snap_btn.trigger()
  1885. self.app.ui.popmenu_disable.setVisible(False)
  1886. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  1887. self.app.ui.popmenu_properties.setVisible(False)
  1888. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  1889. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1890. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1891. # Tell the App that the editor is active
  1892. self.editor_active = True
  1893. # show the UI
  1894. self.drills_frame.show()
  1895. def deactivate(self):
  1896. try:
  1897. QtGui.QGuiApplication.restoreOverrideCursor()
  1898. except Exception as e:
  1899. pass
  1900. # adjust the status of the menu entries related to the editor
  1901. self.app.ui.menueditedit.setDisabled(False)
  1902. self.app.ui.menueditok.setDisabled(True)
  1903. # adjust the visibility of some of the canvas context menu
  1904. self.app.ui.popmenu_edit.setVisible(True)
  1905. self.app.ui.popmenu_save.setVisible(False)
  1906. self.disconnect_canvas_event_handlers()
  1907. self.clear()
  1908. self.app.ui.exc_edit_toolbar.setDisabled(True)
  1909. settings = QSettings("Open Source", "FlatCAM")
  1910. if settings.contains("layout"):
  1911. layout = settings.value('layout', type=str)
  1912. if layout == 'standard':
  1913. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1914. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1915. self.app.ui.corner_snap_btn.setEnabled(False)
  1916. self.app.ui.snap_magnet.setVisible(False)
  1917. self.app.ui.corner_snap_btn.setVisible(False)
  1918. elif layout == 'compact':
  1919. # self.app.ui.exc_edit_toolbar.setVisible(True)
  1920. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1921. self.app.ui.corner_snap_btn.setEnabled(False)
  1922. self.app.ui.snap_magnet.setVisible(True)
  1923. self.app.ui.corner_snap_btn.setVisible(True)
  1924. else:
  1925. # self.app.ui.exc_edit_toolbar.setVisible(False)
  1926. self.app.ui.snap_max_dist_entry.setEnabled(False)
  1927. self.app.ui.corner_snap_btn.setEnabled(False)
  1928. self.app.ui.snap_magnet.setVisible(False)
  1929. self.app.ui.corner_snap_btn.setVisible(False)
  1930. # set the Editor Toolbar visibility to what was before entering in the Editor
  1931. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  1932. else self.app.ui.exc_edit_toolbar.setVisible(True)
  1933. # Disable visuals
  1934. self.shapes.enabled = False
  1935. self.tool_shape.enabled = False
  1936. # self.app.app_cursor.enabled = False
  1937. # Tell the app that the editor is no longer active
  1938. self.editor_active = False
  1939. self.app.ui.exc_editor_menu.setDisabled(True)
  1940. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  1941. self.app.ui.update_obj_btn.setEnabled(False)
  1942. self.app.ui.popmenu_disable.setVisible(True)
  1943. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  1944. self.app.ui.popmenu_properties.setVisible(True)
  1945. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1946. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  1947. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1948. # Show original geometry
  1949. if self.exc_obj:
  1950. self.exc_obj.visible = True
  1951. # hide the UI
  1952. self.drills_frame.hide()
  1953. def connect_canvas_event_handlers(self):
  1954. # ## Canvas events
  1955. # first connect to new, then disconnect the old handlers
  1956. # don't ask why but if there is nothing connected I've seen issues
  1957. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  1958. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  1959. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  1960. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  1961. # but those from FlatCAMGeoEditor
  1962. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1963. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1964. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1965. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  1966. self.app.collection.view.clicked.disconnect()
  1967. self.app.ui.popmenu_copy.triggered.disconnect()
  1968. self.app.ui.popmenu_delete.triggered.disconnect()
  1969. self.app.ui.popmenu_move.triggered.disconnect()
  1970. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  1971. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  1972. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  1973. # Excellon Editor
  1974. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  1975. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  1976. def disconnect_canvas_event_handlers(self):
  1977. # we restore the key and mouse control to FlatCAMApp method
  1978. # first connect to new, then disconnect the old handlers
  1979. # don't ask why but if there is nothing connected I've seen issues
  1980. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1981. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1982. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1983. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  1984. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  1985. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  1986. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  1987. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  1988. try:
  1989. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  1990. except (TypeError, AttributeError):
  1991. pass
  1992. try:
  1993. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  1994. except (TypeError, AttributeError):
  1995. pass
  1996. try:
  1997. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  1998. except (TypeError, AttributeError):
  1999. pass
  2000. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2001. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2002. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2003. # Excellon Editor
  2004. try:
  2005. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2006. except (TypeError, AttributeError):
  2007. pass
  2008. try:
  2009. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2010. except (TypeError, AttributeError):
  2011. pass
  2012. def clear(self):
  2013. self.active_tool = None
  2014. # self.shape_buffer = []
  2015. self.selected = []
  2016. self.points_edit = {}
  2017. self.new_tools = {}
  2018. self.new_drills = []
  2019. # self.storage_dict = {}
  2020. self.shapes.clear(update=True)
  2021. self.tool_shape.clear(update=True)
  2022. # self.storage = FlatCAMExcEditor.make_storage()
  2023. self.replot()
  2024. def edit_fcexcellon(self, exc_obj):
  2025. """
  2026. Imports the geometry from the given FlatCAM Excellon object
  2027. into the editor.
  2028. :param exc_obj: FlatCAMExcellon object
  2029. :return: None
  2030. """
  2031. assert isinstance(exc_obj, Excellon), \
  2032. "Expected an Excellon Object, got %s" % type(exc_obj)
  2033. self.deactivate()
  2034. self.activate()
  2035. # Hide original geometry
  2036. self.exc_obj = exc_obj
  2037. exc_obj.visible = False
  2038. # Set selection tolerance
  2039. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2040. self.select_tool("drill_select")
  2041. self.set_ui()
  2042. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2043. self.build_ui(first_run=True)
  2044. # we activate this after the initial build as we don't need to see the tool been populated
  2045. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2046. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2047. # and then add it to the storage elements (each storage elements is a member of a list
  2048. for tool_dia in self.points_edit:
  2049. storage_elem = FlatCAMGeoEditor.make_storage()
  2050. for point in self.points_edit[tool_dia]:
  2051. # make a '+' sign, the line length is the tool diameter
  2052. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2053. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2054. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2055. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2056. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2057. if shape_geo is not None:
  2058. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2059. self.storage_dict[tool_dia] = storage_elem
  2060. # slots
  2061. for tool_dia in self.slot_points_edit:
  2062. buf_value = float(tool_dia) / 2
  2063. for elem_dict in self.slot_points_edit[tool_dia]:
  2064. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2065. shape_geo = line_geo.buffer(buf_value)
  2066. if tool_dia not in self.storage_dict:
  2067. storage_elem = FlatCAMGeoEditor.make_storage()
  2068. self.storage_dict[tool_dia] = storage_elem
  2069. if shape_geo is not None:
  2070. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2071. self.replot()
  2072. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2073. if not self.tool2tooldia:
  2074. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2075. def update_fcexcellon(self, exc_obj):
  2076. """
  2077. Create a new Excellon object that contain the edited content of the source Excellon object
  2078. :param exc_obj: FlatCAMExcellon
  2079. :return: None
  2080. """
  2081. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2082. # the values of this dict are coordinates of the holes (drills)
  2083. edited_points = {}
  2084. """
  2085. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2086. - the dict element of the list has the structure
  2087. ================ ====================================
  2088. Key Value
  2089. ================ ====================================
  2090. start (Shapely.Point) Start point of the slot
  2091. stop (Shapely.Point) Stop point of the slot
  2092. ================ ====================================
  2093. """
  2094. edited_slot_points = {}
  2095. for storage_tooldia in self.storage_dict:
  2096. for x in self.storage_dict[storage_tooldia].get_objects():
  2097. if isinstance(x.geo, MultiLineString):
  2098. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2099. # each MultiLineString is made out of Linestrings
  2100. # select first Linestring object in the current MultiLineString
  2101. first_linestring = x.geo[0]
  2102. # get it's coordinates
  2103. first_linestring_coords = first_linestring.coords
  2104. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2105. y_coord = first_linestring_coords[0][1]
  2106. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2107. # edited_points dictionary
  2108. point = (x_coord, y_coord)
  2109. if storage_tooldia not in edited_points:
  2110. edited_points[storage_tooldia] = [point]
  2111. else:
  2112. edited_points[storage_tooldia].append(point)
  2113. elif isinstance(x.geo, Polygon):
  2114. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2115. # edited_points dictionary
  2116. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2117. # diameter
  2118. radius = float(storage_tooldia) / 2
  2119. radius = radius - 0.0000001
  2120. poly = x.geo
  2121. poly = poly.buffer(-radius)
  2122. xmin, ymin, xmax, ymax = poly.bounds
  2123. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2124. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2125. if line_one < line_two:
  2126. point = {
  2127. "start": (xmin, ymax),
  2128. "stop": (xmax, ymin)
  2129. }
  2130. else:
  2131. point = {
  2132. "start": (xmin, ymin),
  2133. "stop": (xmax, ymax)
  2134. }
  2135. if storage_tooldia not in edited_slot_points:
  2136. edited_slot_points[storage_tooldia] = [point]
  2137. else:
  2138. edited_slot_points[storage_tooldia].append(point)
  2139. # recreate the drills and tools to be added to the new Excellon edited object
  2140. # first, we look in the tool table if one of the tool diameters was changed then
  2141. # append that a tuple formed by (old_dia, edited_dia) to a list
  2142. changed_key = set()
  2143. for initial_dia in self.olddia_newdia:
  2144. edited_dia = self.olddia_newdia[initial_dia]
  2145. if edited_dia != initial_dia:
  2146. # for drills
  2147. for old_dia in edited_points:
  2148. if old_dia == initial_dia:
  2149. changed_key.add((old_dia, edited_dia))
  2150. # for slots
  2151. for old_dia in edited_slot_points:
  2152. if old_dia == initial_dia:
  2153. changed_key.add((old_dia, edited_dia))
  2154. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2155. # (and we have to add it)
  2156. # because in case we have drill points it will have to be already added in edited_points
  2157. # if initial_dia not in edited_points.keys():
  2158. # edited_points[initial_dia] = []
  2159. for el in changed_key:
  2160. edited_points[el[1]] = edited_points.pop(el[0])
  2161. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2162. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2163. # ordered_edited_points is a ordered list of tuples;
  2164. # element[0] of the tuple is the diameter and
  2165. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2166. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2167. current_tool = 0
  2168. for tool_dia in ordered_edited_points:
  2169. current_tool += 1
  2170. # create the self.tools for the new Excellon object (the one with edited content)
  2171. name = str(current_tool)
  2172. spec = {"C": float(tool_dia[0])}
  2173. self.new_tools[name] = spec
  2174. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2175. self.new_tools[name]['solid_geometry'] = []
  2176. # create the self.drills for the new Excellon object (the one with edited content)
  2177. for point in tool_dia[1]:
  2178. self.new_drills.append(
  2179. {
  2180. 'point': Point(point),
  2181. 'tool': str(current_tool)
  2182. }
  2183. )
  2184. # repopulate the 'solid_geometry' for each tool
  2185. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2186. self.new_tools[name]['solid_geometry'].append(poly)
  2187. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2188. for tool_dia in ordered_edited_slot_points:
  2189. tool_exist_flag = False
  2190. for tool in self.new_tools:
  2191. if tool_dia[0] == self.new_tools[tool]["C"]:
  2192. current_tool = tool
  2193. tool_exist_flag = True
  2194. break
  2195. if tool_exist_flag is False:
  2196. current_tool += 1
  2197. # create the self.tools for the new Excellon object (the one with edited content)
  2198. name = str(current_tool)
  2199. spec = {"C": float(tool_dia[0])}
  2200. self.new_tools[name] = spec
  2201. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2202. self.new_tools[name]['solid_geometry'] = []
  2203. # create the self.slots for the new Excellon object (the one with edited content)
  2204. for coord_dict in tool_dia[1]:
  2205. self.new_slots.append(
  2206. {
  2207. 'start': Point(coord_dict['start']),
  2208. 'stop': Point(coord_dict['stop']),
  2209. 'tool': str(current_tool)
  2210. }
  2211. )
  2212. # repopulate the 'solid_geometry' for each tool
  2213. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2214. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2215. )
  2216. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2217. if self.is_modified is True:
  2218. if "_edit" in self.edited_obj_name:
  2219. try:
  2220. idd = int(self.edited_obj_name[-1]) + 1
  2221. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2222. except ValueError:
  2223. self.edited_obj_name += "_1"
  2224. else:
  2225. self.edited_obj_name += "_edit"
  2226. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2227. 'params': [self.edited_obj_name]})
  2228. self.new_tool_offset = self.exc_obj.tool_offset
  2229. # reset the tool table
  2230. self.tools_table_exc.clear()
  2231. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2232. self.last_tool_selected = None
  2233. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2234. self.app.collection.set_active(self.exc_obj.options['name'])
  2235. self.app.collection.delete_active()
  2236. # restore GUI to the Selected TAB
  2237. # Remove anything else in the GUI
  2238. self.app.ui.tool_scroll_area.takeWidget()
  2239. # Switch notebook to Selected page
  2240. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2241. def update_options(self, obj):
  2242. try:
  2243. if not obj.options:
  2244. obj.options = {}
  2245. obj.options['xmin'] = 0
  2246. obj.options['ymin'] = 0
  2247. obj.options['xmax'] = 0
  2248. obj.options['ymax'] = 0
  2249. return True
  2250. else:
  2251. return False
  2252. except AttributeError:
  2253. obj.options = {}
  2254. return True
  2255. def new_edited_excellon(self, outname):
  2256. """
  2257. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2258. :param outname: Name of the resulting object. None causes the
  2259. name to be that of the file.
  2260. :type outname: str
  2261. :return: None
  2262. """
  2263. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2264. self.exc_obj.options['name'])
  2265. # How the object should be initialized
  2266. def obj_init(excellon_obj, app_obj):
  2267. # self.progress.emit(20)
  2268. excellon_obj.drills = self.new_drills
  2269. excellon_obj.tools = self.new_tools
  2270. excellon_obj.slots = self.new_slots
  2271. excellon_obj.tool_offset = self.new_tool_offset
  2272. excellon_obj.options['name'] = outname
  2273. try:
  2274. excellon_obj.create_geometry()
  2275. except KeyError:
  2276. self.app.inform.emit(
  2277. _("[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  2278. )
  2279. except:
  2280. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2281. msg += traceback.format_exc()
  2282. app_obj.inform.emit(msg)
  2283. raise
  2284. # raise
  2285. with self.app.proc_container.new(_("Creating Excellon.")):
  2286. try:
  2287. self.app.new_object("excellon", outname, obj_init)
  2288. except Exception as e:
  2289. log.error("Error on object creation: %s" % str(e))
  2290. self.app.progress.emit(100)
  2291. return
  2292. self.app.inform.emit(_("[success] Excellon editing finished."))
  2293. # self.progress.emit(100)
  2294. def on_tool_select(self, tool):
  2295. """
  2296. Behavior of the toolbar. Tool initialization.
  2297. :rtype : None
  2298. """
  2299. current_tool = tool
  2300. self.app.log.debug("on_tool_select('%s')" % tool)
  2301. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2302. # self.draw_app.select_tool('drill_select')
  2303. self.complete = True
  2304. current_tool = 'drill_select'
  2305. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  2306. # This is to make the group behave as radio group
  2307. if current_tool in self.tools_exc:
  2308. if self.tools_exc[current_tool]["button"].isChecked():
  2309. self.app.log.debug("%s is checked." % current_tool)
  2310. for t in self.tools_exc:
  2311. if t != current_tool:
  2312. self.tools_exc[t]["button"].setChecked(False)
  2313. # this is where the Editor toolbar classes (button's) are instantiated
  2314. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2315. # self.app.inform.emit(self.active_tool.start_msg)
  2316. else:
  2317. self.app.log.debug("%s is NOT checked." % current_tool)
  2318. for t in self.tools_exc:
  2319. self.tools_exc[t]["button"].setChecked(False)
  2320. self.select_tool('drill_select')
  2321. self.active_tool = FCDrillSelect(self)
  2322. def on_row_selected(self, row, col):
  2323. if col == 0:
  2324. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2325. if self.app.defaults["global_mselect_key"] == 'Control':
  2326. modifier_to_use = Qt.ControlModifier
  2327. else:
  2328. modifier_to_use = Qt.ShiftModifier
  2329. if key_modifier == modifier_to_use:
  2330. pass
  2331. else:
  2332. self.selected = []
  2333. try:
  2334. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2335. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2336. for obj in self.storage_dict[selected_dia].get_objects():
  2337. self.selected.append(obj)
  2338. except Exception as e:
  2339. self.app.log.debug(str(e))
  2340. self.replot()
  2341. def toolbar_tool_toggle(self, key):
  2342. self.options[key] = self.sender().isChecked()
  2343. if self.options[key] is True:
  2344. return 1
  2345. else:
  2346. return 0
  2347. def on_canvas_click(self, event):
  2348. """
  2349. event.x and .y have canvas coordinates
  2350. event.xdata and .ydata have plot coordinates
  2351. :param event: Event object dispatched by VisPy
  2352. :return: None
  2353. """
  2354. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2355. if self.app.grid_status() == True:
  2356. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2357. self.app.app_cursor.enabled = True
  2358. # Update cursor
  2359. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2360. size=20)
  2361. else:
  2362. self.pos = (self.pos[0], self.pos[1])
  2363. self.app.app_cursor.enabled = False
  2364. if event.button is 1:
  2365. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2366. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2367. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2368. # Selection with left mouse button
  2369. if self.active_tool is not None and event.button is 1:
  2370. # Dispatch event to active_tool
  2371. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2372. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2373. # If it is a shape generating tool
  2374. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2375. if self.current_storage is not None:
  2376. self.on_exc_shape_complete(self.current_storage)
  2377. self.build_ui()
  2378. # MS: always return to the Select Tool if modifier key is not pressed
  2379. # else return to the current tool
  2380. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2381. if self.app.defaults["global_mselect_key"] == 'Control':
  2382. modifier_to_use = Qt.ControlModifier
  2383. else:
  2384. modifier_to_use = Qt.ShiftModifier
  2385. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2386. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2387. if key_modifier == modifier_to_use:
  2388. self.select_tool(self.active_tool.name)
  2389. else:
  2390. # return to Select tool but not for FCDrillAdd or FCSlot
  2391. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2392. self.select_tool(self.active_tool.name)
  2393. else:
  2394. self.select_tool("drill_select")
  2395. return
  2396. if isinstance(self.active_tool, FCDrillSelect):
  2397. # self.app.log.debug("Replotting after click.")
  2398. self.replot()
  2399. else:
  2400. self.app.log.debug("No active tool to respond to click!")
  2401. def on_exc_shape_complete(self, storage):
  2402. self.app.log.debug("on_shape_complete()")
  2403. # Add shape
  2404. if type(storage) is list:
  2405. for item_storage in storage:
  2406. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2407. else:
  2408. self.add_exc_shape(self.active_tool.geometry, storage)
  2409. # Remove any utility shapes
  2410. self.delete_utility_geometry()
  2411. self.tool_shape.clear(update=True)
  2412. # Replot and reset tool.
  2413. self.replot()
  2414. # self.active_tool = type(self.active_tool)(self)
  2415. def add_exc_shape(self, shape, storage):
  2416. """
  2417. Adds a shape to the shape storage.
  2418. :param shape: Shape to be added.
  2419. :type shape: DrawToolShape
  2420. :param storage: object where to store the shapes
  2421. :return: None
  2422. """
  2423. # List of DrawToolShape?
  2424. if isinstance(shape, list):
  2425. for subshape in shape:
  2426. self.add_exc_shape(subshape, storage)
  2427. return
  2428. assert isinstance(shape, DrawToolShape), \
  2429. "Expected a DrawToolShape, got %s" % str(type(shape))
  2430. assert shape.geo is not None, \
  2431. "Shape object has empty geometry (None)"
  2432. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2433. "Shape objects has empty geometry ([])"
  2434. if isinstance(shape, DrawToolUtilityShape):
  2435. self.utility.append(shape)
  2436. else:
  2437. storage.insert(shape) # TODO: Check performance
  2438. def add_shape(self, shape):
  2439. """
  2440. Adds a shape to the shape storage.
  2441. :param shape: Shape to be added.
  2442. :type shape: DrawToolShape
  2443. :return: None
  2444. """
  2445. # List of DrawToolShape?
  2446. if isinstance(shape, list):
  2447. for subshape in shape:
  2448. self.add_shape(subshape)
  2449. return
  2450. assert isinstance(shape, DrawToolShape), \
  2451. "Expected a DrawToolShape, got %s" % type(shape)
  2452. assert shape.geo is not None, \
  2453. "Shape object has empty geometry (None)"
  2454. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2455. "Shape objects has empty geometry ([])"
  2456. if isinstance(shape, DrawToolUtilityShape):
  2457. self.utility.append(shape)
  2458. else:
  2459. self.storage.insert(shape) # TODO: Check performance
  2460. def on_exc_click_release(self, event):
  2461. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2462. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2463. if self.app.grid_status() == True:
  2464. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2465. else:
  2466. pos = (pos_canvas[0], pos_canvas[1])
  2467. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2468. # canvas menu
  2469. try:
  2470. if event.button == 2: # right click
  2471. if self.app.ui.popMenu.mouse_is_panning is False:
  2472. try:
  2473. QtGui.QGuiApplication.restoreOverrideCursor()
  2474. except Exception as e:
  2475. pass
  2476. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2477. self.active_tool.complete = True
  2478. self.in_action = False
  2479. self.delete_utility_geometry()
  2480. self.app.inform.emit(_("[success] Done."))
  2481. self.select_tool('drill_select')
  2482. else:
  2483. if isinstance(self.active_tool, FCDrillAdd):
  2484. self.active_tool.complete = True
  2485. self.in_action = False
  2486. self.delete_utility_geometry()
  2487. self.app.inform.emit(_("[success] Done."))
  2488. self.select_tool('drill_select')
  2489. self.app.cursor = QtGui.QCursor()
  2490. self.app.populate_cmenu_grids()
  2491. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2492. except Exception as e:
  2493. log.warning("Error: %s" % str(e))
  2494. raise
  2495. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2496. # selection and then select a type of selection ("enclosing" or "touching")
  2497. try:
  2498. if event.button == 1: # left click
  2499. if self.app.selection_type is not None:
  2500. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2501. self.app.selection_type = None
  2502. elif isinstance(self.active_tool, FCDrillSelect):
  2503. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2504. # if there are selected objects then plot them
  2505. if self.selected:
  2506. self.replot()
  2507. except Exception as e:
  2508. log.warning("Error: %s" % str(e))
  2509. raise
  2510. def draw_selection_area_handler(self, start, end, sel_type):
  2511. """
  2512. :param start_pos: mouse position when the selection LMB click was done
  2513. :param end_pos: mouse position when the left mouse button is released
  2514. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2515. :return:
  2516. """
  2517. start_pos = (start[0], start[1])
  2518. end_pos = (end[0], end[1])
  2519. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2520. self.app.delete_selection_shape()
  2521. for storage in self.storage_dict:
  2522. for obj in self.storage_dict[storage].get_objects():
  2523. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2524. (sel_type is False and poly_selection.intersects(obj.geo)):
  2525. if self.key == self.app.defaults["global_mselect_key"]:
  2526. if obj in self.selected:
  2527. self.selected.remove(obj)
  2528. else:
  2529. # add the object to the selected shapes
  2530. self.selected.append(obj)
  2531. else:
  2532. self.selected.append(obj)
  2533. try:
  2534. self.tools_table_exc.cellPressed.disconnect()
  2535. except Exception as e:
  2536. pass
  2537. # select the diameter of the selected shape in the tool table
  2538. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2539. for storage in self.storage_dict:
  2540. for shape_s in self.selected:
  2541. if shape_s in self.storage_dict[storage].get_objects():
  2542. for key in self.tool2tooldia:
  2543. if self.tool2tooldia[key] == storage:
  2544. item = self.tools_table_exc.item((key - 1), 1)
  2545. self.tools_table_exc.setCurrentItem(item)
  2546. self.last_tool_selected = int(key)
  2547. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2548. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2549. self.replot()
  2550. def on_canvas_move(self, event):
  2551. """
  2552. Called on 'mouse_move' event
  2553. event.pos have canvas screen coordinates
  2554. :param event: Event object dispatched by VisPy SceneCavas
  2555. :return: None
  2556. """
  2557. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2558. event.xdata, event.ydata = pos[0], pos[1]
  2559. self.x = event.xdata
  2560. self.y = event.ydata
  2561. self.app.ui.popMenu.mouse_is_panning = False
  2562. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2563. if event.button == 2 and event.is_dragging == 1:
  2564. self.app.ui.popMenu.mouse_is_panning = True
  2565. return
  2566. try:
  2567. x = float(event.xdata)
  2568. y = float(event.ydata)
  2569. except TypeError:
  2570. return
  2571. if self.active_tool is None:
  2572. return
  2573. # ## Snap coordinates
  2574. if self.app.grid_status() == True:
  2575. x, y = self.app.geo_editor.snap(x, y)
  2576. self.app.app_cursor.enabled = True
  2577. # Update cursor
  2578. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2579. else:
  2580. self.app.app_cursor.enabled = False
  2581. self.snap_x = x
  2582. self.snap_y = y
  2583. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2584. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2585. "<b>Y</b>: %.4f" % (x, y))
  2586. if self.pos is None:
  2587. self.pos = (0, 0)
  2588. dx = x - self.pos[0]
  2589. dy = y - self.pos[1]
  2590. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2591. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2592. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2593. # ## Utility geometry (animated)
  2594. geo = self.active_tool.utility_geometry(data=(x, y))
  2595. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2596. # Remove any previous utility shape
  2597. self.tool_shape.clear(update=True)
  2598. self.draw_utility_geometry(geo=geo)
  2599. # ## Selection area on canvas section # ##
  2600. if event.is_dragging == 1 and event.button == 1:
  2601. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2602. # can create strange issues
  2603. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray):
  2604. pass
  2605. else:
  2606. dx = pos[0] - self.pos[0]
  2607. self.app.delete_selection_shape()
  2608. if dx < 0:
  2609. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2610. color=self.app.defaults["global_alt_sel_line"],
  2611. face_color=self.app.defaults['global_alt_sel_fill'])
  2612. self.app.selection_type = False
  2613. else:
  2614. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2615. self.app.selection_type = True
  2616. else:
  2617. self.app.selection_type = None
  2618. # Update cursor
  2619. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2620. def on_canvas_key_release(self, event):
  2621. self.key = None
  2622. def draw_utility_geometry(self, geo):
  2623. # Add the new utility shape
  2624. try:
  2625. # this case is for the Font Parse
  2626. for el in list(geo.geo):
  2627. if type(el) == MultiPolygon:
  2628. for poly in el:
  2629. self.tool_shape.add(
  2630. shape=poly,
  2631. color=(self.app.defaults["global_draw_color"] + '80'),
  2632. update=False,
  2633. layer=0,
  2634. tolerance=None
  2635. )
  2636. elif type(el) == MultiLineString:
  2637. for linestring in el:
  2638. self.tool_shape.add(
  2639. shape=linestring,
  2640. color=(self.app.defaults["global_draw_color"] + '80'),
  2641. update=False,
  2642. layer=0,
  2643. tolerance=None
  2644. )
  2645. else:
  2646. self.tool_shape.add(
  2647. shape=el,
  2648. color=(self.app.defaults["global_draw_color"] + '80'),
  2649. update=False,
  2650. layer=0,
  2651. tolerance=None
  2652. )
  2653. except TypeError:
  2654. self.tool_shape.add(
  2655. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2656. update=False, layer=0, tolerance=None)
  2657. self.tool_shape.redraw()
  2658. def replot(self):
  2659. self.plot_all()
  2660. def plot_all(self):
  2661. """
  2662. Plots all shapes in the editor.
  2663. :return: None
  2664. :rtype: None
  2665. """
  2666. # self.app.log.debug("plot_all()")
  2667. self.shapes.clear(update=True)
  2668. for storage in self.storage_dict:
  2669. for shape_plus in self.storage_dict[storage].get_objects():
  2670. if shape_plus.geo is None:
  2671. continue
  2672. if shape_plus in self.selected:
  2673. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  2674. linewidth=2)
  2675. continue
  2676. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  2677. # for shape in self.storage.get_objects():
  2678. # if shape.geo is None: # TODO: This shouldn't have happened
  2679. # continue
  2680. #
  2681. # if shape in self.selected:
  2682. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2683. # continue
  2684. #
  2685. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2686. for shape_form in self.utility:
  2687. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  2688. continue
  2689. self.shapes.redraw()
  2690. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2691. """
  2692. Plots a geometric object or list of objects without rendering. Plotted objects
  2693. are returned as a list. This allows for efficient/animated rendering.
  2694. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2695. :param color: Shape color
  2696. :param linewidth: Width of lines in # of pixels.
  2697. :return: List of plotted elements.
  2698. """
  2699. plot_elements = []
  2700. if geometry is None:
  2701. geometry = self.active_tool.geometry
  2702. try:
  2703. for geo in geometry:
  2704. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2705. # ## Non-iterable
  2706. except TypeError:
  2707. # ## DrawToolShape
  2708. if isinstance(geometry, DrawToolShape):
  2709. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2710. # ## Polygon: Descend into exterior and each interior.
  2711. if type(geometry) == Polygon:
  2712. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2713. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2714. if type(geometry) == LineString or type(geometry) == LinearRing:
  2715. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  2716. if type(geometry) == Point:
  2717. pass
  2718. return plot_elements
  2719. def on_shape_complete(self):
  2720. self.app.log.debug("on_shape_complete()")
  2721. # Add shape
  2722. self.add_shape(self.active_tool.geometry)
  2723. # Remove any utility shapes
  2724. self.delete_utility_geometry()
  2725. self.tool_shape.clear(update=True)
  2726. # Replot and reset tool.
  2727. self.replot()
  2728. # self.active_tool = type(self.active_tool)(self)
  2729. def get_selected(self):
  2730. """
  2731. Returns list of shapes that are selected in the editor.
  2732. :return: List of shapes.
  2733. """
  2734. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2735. return self.selected
  2736. def delete_selected(self):
  2737. temp_ref = [s for s in self.selected]
  2738. for shape_sel in temp_ref:
  2739. self.delete_shape(shape_sel)
  2740. self.selected = []
  2741. self.build_ui()
  2742. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  2743. def delete_shape(self, del_shape):
  2744. self.is_modified = True
  2745. if del_shape in self.utility:
  2746. self.utility.remove(del_shape)
  2747. return
  2748. for storage in self.storage_dict:
  2749. # try:
  2750. # self.storage_dict[storage].remove(shape)
  2751. # except:
  2752. # pass
  2753. if del_shape in self.storage_dict[storage].get_objects():
  2754. if isinstance(del_shape.geo, MultiLineString):
  2755. self.storage_dict[storage].remove(del_shape)
  2756. # a hack to make the tool_table display less drills per diameter
  2757. # self.points_edit it's only useful first time when we load the data into the storage
  2758. # but is still used as referecen when building tool_table in self.build_ui()
  2759. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2760. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  2761. del self.points_edit[storage][0]
  2762. else:
  2763. self.storage_dict[storage].remove(del_shape)
  2764. del self.slot_points_edit[storage][0]
  2765. if del_shape in self.selected:
  2766. self.selected.remove(del_shape) # TODO: Check performance
  2767. def delete_utility_geometry(self):
  2768. for_deletion = [util_shape for util_shape in self.utility]
  2769. for util_shape in for_deletion:
  2770. self.delete_shape(util_shape)
  2771. self.tool_shape.clear(update=True)
  2772. self.tool_shape.redraw()
  2773. def on_delete_btn(self):
  2774. self.delete_selected()
  2775. self.replot()
  2776. def select_tool(self, toolname):
  2777. """
  2778. Selects a drawing tool. Impacts the object and GUI.
  2779. :param toolname: Name of the tool.
  2780. :return: None
  2781. """
  2782. self.tools_exc[toolname]["button"].setChecked(True)
  2783. self.on_tool_select(toolname)
  2784. def set_selected(self, sel_shape):
  2785. # Remove and add to the end.
  2786. if sel_shape in self.selected:
  2787. self.selected.remove(sel_shape)
  2788. self.selected.append(sel_shape)
  2789. def set_unselected(self, unsel_shape):
  2790. if unsel_shape in self.selected:
  2791. self.selected.remove(unsel_shape)
  2792. def on_array_type_combo(self):
  2793. if self.array_type_combo.currentIndex() == 0:
  2794. self.array_circular_frame.hide()
  2795. self.array_linear_frame.show()
  2796. else:
  2797. self.delete_utility_geometry()
  2798. self.array_circular_frame.show()
  2799. self.array_linear_frame.hide()
  2800. self.app.inform.emit(_("Click on the circular array Center position"))
  2801. def on_linear_angle_radio(self):
  2802. val = self.drill_axis_radio.get_value()
  2803. if val == 'A':
  2804. self.linear_angle_spinner.show()
  2805. self.linear_angle_label.show()
  2806. else:
  2807. self.linear_angle_spinner.hide()
  2808. self.linear_angle_label.hide()
  2809. def on_slot_angle_radio(self):
  2810. val = self.slot_axis_radio.get_value()
  2811. if val == 'A':
  2812. self.slot_angle_spinner.show()
  2813. self.slot_angle_label.show()
  2814. else:
  2815. self.slot_angle_spinner.hide()
  2816. self.slot_angle_label.hide()
  2817. def exc_add_drill(self):
  2818. self.select_tool('drill_add')
  2819. return
  2820. def exc_add_drill_array(self):
  2821. self.select_tool('drill_array')
  2822. return
  2823. def exc_resize_drills(self):
  2824. self.select_tool('drill_resize')
  2825. return
  2826. def exc_copy_drills(self):
  2827. self.select_tool('drill_copy')
  2828. return
  2829. def exc_move_drills(self):
  2830. self.select_tool('drill_move')
  2831. return
  2832. def get_shapely_list_bounds(geometry_list):
  2833. xmin = Inf
  2834. ymin = Inf
  2835. xmax = -Inf
  2836. ymax = -Inf
  2837. for gs in geometry_list:
  2838. try:
  2839. gxmin, gymin, gxmax, gymax = gs.bounds
  2840. xmin = min([xmin, gxmin])
  2841. ymin = min([ymin, gymin])
  2842. xmax = max([xmax, gxmax])
  2843. ymax = max([ymax, gymax])
  2844. except Exception as e:
  2845. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  2846. return [xmin, ymin, xmax, ymax]
  2847. # EOF