FlatCAMExcEditor.py 155 KB

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