FlatCAMExcEditor.py 170 KB

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