FlatCAMExcEditor.py 170 KB

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