FlatCAMExcEditor.py 147 KB

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