FlatCAMExcEditor.py 174 KB

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