FlatCAMGrbEditor.py 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, QSettings
  3. from shapely.geometry import LineString, LinearRing, MultiLineString
  4. from shapely.ops import cascaded_union, unary_union
  5. import shapely.affinity as affinity
  6. from numpy import arctan2, Inf, array, sqrt, sign, dot
  7. from rtree import index as rtindex
  8. import threading, time
  9. from copy import copy, deepcopy
  10. from camlib import *
  11. from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, LengthEntry, RadioSet, \
  12. SpinBoxDelegate, EvalEntry, EvalEntry2, FCInputDialog, FCButton, OptionalInputSection, FCCheckBox
  13. from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
  14. from FlatCAMObj import FlatCAMGerber
  15. from FlatCAMTool import FlatCAMTool
  16. from numpy.linalg import norm as numpy_norm
  17. import gettext
  18. import FlatCAMTranslation as fcTranslate
  19. fcTranslate.apply_language('strings')
  20. import builtins
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. class FCPad(FCShapeTool):
  24. """
  25. Resulting type: Polygon
  26. """
  27. def __init__(self, draw_app):
  28. DrawTool.__init__(self, draw_app)
  29. self.name = 'pad'
  30. self.draw_app = draw_app
  31. try:
  32. QtGui.QGuiApplication.restoreOverrideCursor()
  33. except:
  34. pass
  35. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_circle.png'))
  36. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  37. try:
  38. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  39. except KeyError:
  40. self.draw_app.app.inform.emit(_(
  41. "[WARNING_NOTCL] To add an Pad first select a aperture in Aperture Table"))
  42. self.draw_app.in_action = False
  43. self.complete = True
  44. return
  45. if self.radius == 0:
  46. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Aperture size is zero. It needs to be greater than zero."))
  47. self.dont_execute = True
  48. return
  49. else:
  50. self.dont_execute = False
  51. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  52. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  53. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  54. try:
  55. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  56. except KeyError:
  57. pass
  58. try:
  59. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  60. except KeyError:
  61. pass
  62. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  63. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  64. self.draw_app.draw_utility_geometry(geo=geo)
  65. self.draw_app.app.inform.emit(_("Click to place ..."))
  66. # Switch notebook to Selected page
  67. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  68. self.start_msg = _("Click to place ...")
  69. def click(self, point):
  70. self.make()
  71. return "Done."
  72. def utility_geometry(self, data=None):
  73. if self.dont_execute is True:
  74. self.draw_app.select_tool('select')
  75. return
  76. self.points = data
  77. geo_data = self.util_shape(data)
  78. if geo_data:
  79. return DrawToolUtilityShape(geo_data)
  80. else:
  81. return None
  82. def util_shape(self, point):
  83. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  84. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  85. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  86. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  87. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  88. try:
  89. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  90. except KeyError:
  91. pass
  92. try:
  93. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  94. except KeyError:
  95. pass
  96. if point[0] is None and point[1] is None:
  97. point_x = self.draw_app.x
  98. point_y = self.draw_app.y
  99. else:
  100. point_x = point[0]
  101. point_y = point[1]
  102. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  103. if ap_type == 'C':
  104. center = Point([point_x, point_y])
  105. return center.buffer(self.radius)
  106. elif ap_type == 'R':
  107. p1 = (point_x - self.half_width, point_y - self.half_height)
  108. p2 = (point_x + self.half_width, point_y - self.half_height)
  109. p3 = (point_x + self.half_width, point_y + self.half_height)
  110. p4 = (point_x - self.half_width, point_y + self.half_height)
  111. return Polygon([p1, p2, p3, p4, p1])
  112. elif ap_type == 'O':
  113. geo = []
  114. if self.half_height > self.half_width:
  115. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  116. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  117. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  118. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  119. down_center = (point_x, point_y - self.half_height + self.half_width)
  120. d_start_angle = math.pi
  121. d_stop_angle = 0.0
  122. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  123. up_center = (point_x, point_y + self.half_height - self.half_width)
  124. u_start_angle = 0.0
  125. u_stop_angle = math.pi
  126. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  127. geo.append(p1)
  128. for pt in down_arc:
  129. geo.append(pt)
  130. geo.append(p2)
  131. geo.append(p3)
  132. for pt in up_arc:
  133. geo.append(pt)
  134. geo.append(p4)
  135. return Polygon(geo)
  136. else:
  137. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  138. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  139. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  140. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  141. left_center = (point_x - self.half_width + self.half_height, point_y)
  142. d_start_angle = math.pi / 2
  143. d_stop_angle = 1.5 * math.pi
  144. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  145. right_center = (point_x + self.half_width - self.half_height, point_y)
  146. u_start_angle = 1.5 * math.pi
  147. u_stop_angle = math.pi / 2
  148. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  149. geo.append(p1)
  150. geo.append(p2)
  151. for pt in right_arc:
  152. geo.append(pt)
  153. geo.append(p3)
  154. geo.append(p4)
  155. for pt in left_arc:
  156. geo.append(pt)
  157. return Polygon(geo)
  158. else:
  159. self.draw_app.app.inform.emit(_(
  160. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  161. return None
  162. def make(self):
  163. self.draw_app.current_storage = self.storage_obj
  164. try:
  165. self.geometry = DrawToolShape(self.util_shape(self.points))
  166. except Exception as e:
  167. log.debug("FCPad.make() --> %s" % str(e))
  168. self.draw_app.in_action = False
  169. self.complete = True
  170. self.draw_app.app.inform.emit(_("[success] Done. Adding Pad completed."))
  171. def clean_up(self):
  172. self.draw_app.selected = []
  173. self.draw_app.apertures_table.clearSelection()
  174. self.draw_app.plot_all()
  175. class FCPadArray(FCShapeTool):
  176. """
  177. Resulting type: MultiPolygon
  178. """
  179. def __init__(self, draw_app):
  180. DrawTool.__init__(self, draw_app)
  181. self.name = 'array'
  182. self.draw_app = draw_app
  183. try:
  184. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  185. except KeyError:
  186. self.draw_app.app.inform.emit(_(
  187. "[WARNING_NOTCL] To add an Pad Array first select a aperture in Aperture Table"))
  188. self.complete = True
  189. self.draw_app.in_action = False
  190. self.draw_app.array_frame.hide()
  191. return
  192. if self.radius == 0:
  193. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Aperture size is zero. It needs to be greater than zero."))
  194. self.dont_execute = True
  195. return
  196. else:
  197. self.dont_execute = False
  198. try:
  199. QtGui.QGuiApplication.restoreOverrideCursor()
  200. except:
  201. pass
  202. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_array.png'))
  203. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  204. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  205. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  206. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  207. try:
  208. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  209. except KeyError:
  210. pass
  211. try:
  212. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  213. except KeyError:
  214. pass
  215. self.draw_app.array_frame.show()
  216. self.selected_size = None
  217. self.pad_axis = 'X'
  218. self.pad_array = 'linear'
  219. self.pad_array_size = None
  220. self.pad_pitch = None
  221. self.pad_linear_angle = None
  222. self.pad_angle = None
  223. self.pad_direction = None
  224. self.pad_radius = None
  225. self.origin = None
  226. self.destination = None
  227. self.flag_for_circ_array = None
  228. self.last_dx = 0
  229. self.last_dy = 0
  230. self.pt = []
  231. self.draw_app.app.inform.emit(self.start_msg)
  232. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  233. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  234. self.draw_app.draw_utility_geometry(geo=geo)
  235. self.draw_app.app.inform.emit(_("Click on target location ..."))
  236. # Switch notebook to Selected page
  237. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  238. def click(self, point):
  239. if self.pad_array == 'Linear':
  240. self.make()
  241. return
  242. else:
  243. if self.flag_for_circ_array is None:
  244. self.draw_app.in_action = True
  245. self.pt.append(point)
  246. self.flag_for_circ_array = True
  247. self.set_origin(point)
  248. self.draw_app.app.inform.emit(_("Click on the Pad Circular Array Start position"))
  249. else:
  250. self.destination = point
  251. self.make()
  252. self.flag_for_circ_array = None
  253. return
  254. def set_origin(self, origin):
  255. self.origin = origin
  256. def utility_geometry(self, data=None, static=None):
  257. if self.dont_execute is True:
  258. self.draw_app.select_tool('select')
  259. return
  260. self.pad_axis = self.draw_app.pad_axis_radio.get_value()
  261. self.pad_direction = self.draw_app.pad_direction_radio.get_value()
  262. self.pad_array = self.draw_app.array_type_combo.get_value()
  263. try:
  264. self.pad_array_size = int(self.draw_app.pad_array_size_entry.get_value())
  265. try:
  266. self.pad_pitch = float(self.draw_app.pad_pitch_entry.get_value())
  267. self.pad_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  268. self.pad_angle = float(self.draw_app.pad_angle_entry.get_value())
  269. except TypeError:
  270. self.draw_app.app.inform.emit(
  271. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  272. return
  273. except Exception as e:
  274. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  275. return
  276. if self.pad_array == 'Linear':
  277. if data[0] is None and data[1] is None:
  278. dx = self.draw_app.x
  279. dy = self.draw_app.y
  280. else:
  281. dx = data[0]
  282. dy = data[1]
  283. geo_list = []
  284. geo = None
  285. self.points = [dx, dy]
  286. for item in range(self.pad_array_size):
  287. if self.pad_axis == 'X':
  288. geo = self.util_shape(((dx + (self.pad_pitch * item)), dy))
  289. if self.pad_axis == 'Y':
  290. geo = self.util_shape((dx, (dy + (self.pad_pitch * item))))
  291. if self.pad_axis == 'A':
  292. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  293. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  294. geo = self.util_shape(
  295. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  296. )
  297. if static is None or static is False:
  298. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  299. else:
  300. geo_list.append(geo)
  301. # self.origin = data
  302. self.last_dx = dx
  303. self.last_dy = dy
  304. return DrawToolUtilityShape(geo_list)
  305. else:
  306. if data[0] is None and data[1] is None:
  307. cdx = self.draw_app.x
  308. cdy = self.draw_app.y
  309. else:
  310. cdx = data[0]
  311. cdy = data[1]
  312. if len(self.pt) > 0:
  313. temp_points = [x for x in self.pt]
  314. temp_points.append([cdx, cdy])
  315. return DrawToolUtilityShape(LineString(temp_points))
  316. def util_shape(self, point):
  317. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  318. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  319. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  320. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  321. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  322. try:
  323. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  324. except KeyError:
  325. pass
  326. try:
  327. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  328. except KeyError:
  329. pass
  330. if point[0] is None and point[1] is None:
  331. point_x = self.draw_app.x
  332. point_y = self.draw_app.y
  333. else:
  334. point_x = point[0]
  335. point_y = point[1]
  336. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  337. if ap_type == 'C':
  338. center = Point([point_x, point_y])
  339. return center.buffer(self.radius)
  340. elif ap_type == 'R':
  341. p1 = (point_x - self.half_width, point_y - self.half_height)
  342. p2 = (point_x + self.half_width, point_y - self.half_height)
  343. p3 = (point_x + self.half_width, point_y + self.half_height)
  344. p4 = (point_x - self.half_width, point_y + self.half_height)
  345. return Polygon([p1, p2, p3, p4, p1])
  346. elif ap_type == 'O':
  347. geo = []
  348. if self.half_height > self.half_width:
  349. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  350. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  351. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  352. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  353. down_center = (point_x, point_y - self.half_height + self.half_width)
  354. d_start_angle = math.pi
  355. d_stop_angle = 0.0
  356. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  357. up_center = (point_x, point_y + self.half_height - self.half_width)
  358. u_start_angle = 0.0
  359. u_stop_angle = math.pi
  360. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  361. geo.append(p1)
  362. for pt in down_arc:
  363. geo.append(pt)
  364. geo.append(p2)
  365. geo.append(p3)
  366. for pt in up_arc:
  367. geo.append(pt)
  368. geo.append(p4)
  369. return Polygon(geo)
  370. else:
  371. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  372. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  373. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  374. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  375. left_center = (point_x - self.half_width + self.half_height, point_y)
  376. d_start_angle = math.pi / 2
  377. d_stop_angle = 1.5 * math.pi
  378. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  379. right_center = (point_x + self.half_width - self.half_height, point_y)
  380. u_start_angle = 1.5 * math.pi
  381. u_stop_angle = math.pi / 2
  382. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  383. geo.append(p1)
  384. geo.append(p2)
  385. for pt in right_arc:
  386. geo.append(pt)
  387. geo.append(p3)
  388. geo.append(p4)
  389. for pt in left_arc:
  390. geo.append(pt)
  391. return Polygon(geo)
  392. else:
  393. self.draw_app.app.inform.emit(_(
  394. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  395. return None
  396. def make(self):
  397. self.geometry = []
  398. geo = None
  399. self.draw_app.current_storage = self.storage_obj
  400. if self.pad_array == 'Linear':
  401. for item in range(self.pad_array_size):
  402. if self.pad_axis == 'X':
  403. geo = self.util_shape(((self.points[0] + (self.pad_pitch * item)), self.points[1]))
  404. if self.pad_axis == 'Y':
  405. geo = self.util_shape((self.points[0], (self.points[1] + (self.pad_pitch * item))))
  406. if self.pad_axis == 'A':
  407. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  408. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  409. geo = self.util_shape(
  410. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  411. )
  412. self.geometry.append(DrawToolShape(geo))
  413. else:
  414. if (self.pad_angle * self.pad_array_size) > 360:
  415. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many Pads for the selected spacing angle."))
  416. return
  417. radius = distance(self.destination, self.origin)
  418. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  419. for i in range(self.pad_array_size):
  420. angle_radians = math.radians(self.pad_angle * i)
  421. if self.pad_direction == 'CW':
  422. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  423. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  424. else:
  425. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  426. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  427. geo = self.util_shape((x, y))
  428. if self.pad_direction == 'CW':
  429. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  430. else:
  431. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  432. self.geometry.append(DrawToolShape(geo))
  433. self.complete = True
  434. self.draw_app.app.inform.emit(_("[success] Done. Pad Array added."))
  435. self.draw_app.in_action = False
  436. self.draw_app.array_frame.hide()
  437. return
  438. def clean_up(self):
  439. self.draw_app.selected = []
  440. self.draw_app.apertures_table.clearSelection()
  441. self.draw_app.plot_all()
  442. class FCPoligonize(FCShapeTool):
  443. """
  444. Resulting type: Polygon
  445. """
  446. def __init__(self, draw_app):
  447. DrawTool.__init__(self, draw_app)
  448. self.name = 'poligonize'
  449. self.draw_app = draw_app
  450. self.start_msg = _("Select shape(s) and then click ...")
  451. self.draw_app.in_action = True
  452. self.make()
  453. def click(self, point):
  454. return ""
  455. def make(self):
  456. if not self.draw_app.selected:
  457. self.draw_app.in_action = False
  458. self.complete = True
  459. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] Failed. Nothing selected."))
  460. self.draw_app.select_tool("select")
  461. return
  462. exterior_geo = [Polygon(sh.geo.exterior) for sh in self.draw_app.selected]
  463. fused_geo = MultiPolygon(exterior_geo)
  464. fused_geo = fused_geo.buffer(0.0000001)
  465. current_storage = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  466. if isinstance(fused_geo, MultiPolygon):
  467. for geo in fused_geo:
  468. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(geo))
  469. else:
  470. if len(fused_geo.interiors) == 0 and len(exterior_geo) == 1:
  471. try:
  472. current_storage = self.draw_app.storage_dict['0']['solid_geometry']
  473. except KeyError:
  474. self.draw_app.on_aperture_add(apid='0')
  475. current_storage = self.draw_app.storage_dict['0']['solid_geometry']
  476. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(fused_geo))
  477. self.draw_app.delete_selected()
  478. self.draw_app.plot_all()
  479. self.draw_app.in_action = False
  480. self.complete = True
  481. self.draw_app.app.inform.emit(_("[success] Done. Poligonize completed."))
  482. # MS: always return to the Select Tool if modifier key is not pressed
  483. # else return to the current tool
  484. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  485. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  486. modifier_to_use = Qt.ControlModifier
  487. else:
  488. modifier_to_use = Qt.ShiftModifier
  489. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  490. # in the selected list, we removed it. Therefore first click selects, second deselects.
  491. if key_modifier == modifier_to_use:
  492. self.draw_app.select_tool(self.draw_app.active_tool.name)
  493. else:
  494. self.draw_app.select_tool("select")
  495. return
  496. def clean_up(self):
  497. self.draw_app.selected = []
  498. self.draw_app.apertures_table.clearSelection()
  499. self.draw_app.plot_all()
  500. class FCRegion(FCShapeTool):
  501. """
  502. Resulting type: Polygon
  503. """
  504. def __init__(self, draw_app):
  505. DrawTool.__init__(self, draw_app)
  506. self.name = 'region'
  507. self.draw_app = draw_app
  508. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  509. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  510. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  511. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  512. self.temp_points = []
  513. # this will store the inflexion point in the geometry
  514. self.inter_point = None
  515. try:
  516. QtGui.QGuiApplication.restoreOverrideCursor()
  517. except:
  518. pass
  519. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  520. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  521. self.draw_app.app.inform.emit(_('Corner Mode 1: 45 degrees ...'))
  522. self.start_msg = _("Click on 1st point ...")
  523. def click(self, point):
  524. self.draw_app.in_action = True
  525. if self.inter_point is not None:
  526. self.points.append(self.inter_point)
  527. self.points.append(point)
  528. if len(self.points) > 0:
  529. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  530. return "Click on next point or hit ENTER to complete ..."
  531. return ""
  532. def update_grid_info(self):
  533. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  534. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  535. def utility_geometry(self, data=None):
  536. x = data[0]
  537. y = data[1]
  538. if len(self.points) == 0:
  539. return DrawToolUtilityShape(Point(data).buffer(self.buf_val))
  540. if len(self.points) == 1:
  541. self.temp_points = [x for x in self.points]
  542. old_x = self.points[0][0]
  543. old_y = self.points[0][1]
  544. mx = abs(round((x - old_x) / self.gridx_size))
  545. my = abs(round((y - old_y) / self.gridy_size))
  546. if mx and my:
  547. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  548. if self.draw_app.bend_mode != 5:
  549. if self.draw_app.bend_mode == 1:
  550. if x > old_x:
  551. if mx > my:
  552. self.inter_point = (old_x + self.gridx_size * (mx - my), old_y)
  553. if mx < my:
  554. if y < old_y:
  555. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  556. else:
  557. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  558. if x < old_x:
  559. if mx > my:
  560. self.inter_point = (old_x - self.gridx_size * (mx - my), old_y)
  561. if mx < my:
  562. if y < old_y:
  563. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  564. else:
  565. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  566. elif self.draw_app.bend_mode == 2:
  567. if x > old_x:
  568. if mx > my:
  569. self.inter_point = (old_x + self.gridx_size * my, y)
  570. if mx < my:
  571. if y < old_y:
  572. self.inter_point = (x, old_y - self.gridy_size * mx)
  573. else:
  574. self.inter_point = (x, old_y + self.gridy_size * mx)
  575. if x < old_x:
  576. if mx > my:
  577. self.inter_point = (old_x - self.gridx_size * my, y)
  578. if mx < my:
  579. if y < old_y:
  580. self.inter_point = (x, old_y - self.gridy_size * mx)
  581. else:
  582. self.inter_point = (x, old_y + self.gridy_size * mx)
  583. elif self.draw_app.bend_mode == 3:
  584. self.inter_point = (x, old_y)
  585. elif self.draw_app.bend_mode == 4:
  586. self.inter_point = (old_x, y)
  587. if self.inter_point is not None:
  588. self.temp_points.append(self.inter_point)
  589. else:
  590. self.inter_point = data
  591. else:
  592. self.inter_point = data
  593. self.temp_points.append(data)
  594. if len(self.temp_points) > 1:
  595. try:
  596. return DrawToolUtilityShape(LineString(self.temp_points).buffer(self.buf_val, join_style=1))
  597. except:
  598. pass
  599. else:
  600. return DrawToolUtilityShape(Point(self.temp_points).buffer(self.buf_val))
  601. if len(self.points) > 2:
  602. self.temp_points = [x for x in self.points]
  603. old_x = self.points[-1][0]
  604. old_y = self.points[-1][1]
  605. mx = abs(round((x - old_x) / self.gridx_size))
  606. my = abs(round((y - old_y) / self.gridy_size))
  607. if mx and my:
  608. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  609. if self.draw_app.bend_mode != 5:
  610. if self.draw_app.bend_mode == 1:
  611. if x > old_x:
  612. if mx > my:
  613. self.inter_point = (old_x + self.gridx_size * (mx - my), old_y)
  614. if mx < my:
  615. if y < old_y:
  616. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  617. else:
  618. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  619. if x < old_x:
  620. if mx > my:
  621. self.inter_point = (old_x - self.gridx_size * (mx - my), old_y)
  622. if mx < my:
  623. if y < old_y:
  624. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  625. else:
  626. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  627. elif self.draw_app.bend_mode == 2:
  628. if x > old_x:
  629. if mx > my:
  630. self.inter_point = (old_x + self.gridx_size * my, y)
  631. if mx < my:
  632. if y < old_y:
  633. self.inter_point = (x, old_y - self.gridy_size * mx)
  634. else:
  635. self.inter_point = (x, old_y + self.gridy_size * mx)
  636. if x < old_x:
  637. if mx > my:
  638. self.inter_point = (old_x - self.gridx_size * my, y)
  639. if mx < my:
  640. if y < old_y:
  641. self.inter_point = (x, old_y - self.gridy_size * mx)
  642. else:
  643. self.inter_point = (x, old_y + self.gridy_size * mx)
  644. elif self.draw_app.bend_mode == 3:
  645. self.inter_point = (x, old_y)
  646. elif self.draw_app.bend_mode == 4:
  647. self.inter_point = (old_x, y)
  648. self.temp_points.append(self.inter_point)
  649. self.temp_points.append(data)
  650. return DrawToolUtilityShape(LinearRing(self.temp_points).buffer(self.buf_val, join_style=1))
  651. return None
  652. def make(self):
  653. # self.geometry = LinearRing(self.points)
  654. if len(self.points) > 2:
  655. # regions are added always in the '0' aperture
  656. if '0' not in self.draw_app.storage_dict:
  657. self.draw_app.on_aperture_add(apid='0')
  658. else:
  659. self.draw_app.last_aperture_selected = '0'
  660. self.geometry = DrawToolShape(Polygon(self.points).buffer(self.buf_val, join_style=2))
  661. self.draw_app.in_action = False
  662. self.complete = True
  663. self.draw_app.app.inform.emit(_("[success] Done."))
  664. def clean_up(self):
  665. self.draw_app.selected = []
  666. self.draw_app.apertures_table.clearSelection()
  667. self.draw_app.plot_all()
  668. def on_key(self, key):
  669. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  670. if len(self.points) > 0:
  671. if self.draw_app.bend_mode == 5:
  672. self.points = self.points[0:-1]
  673. else:
  674. self.points = self.points[0:-2]
  675. # Remove any previous utility shape
  676. self.draw_app.tool_shape.clear(update=False)
  677. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  678. self.draw_app.draw_utility_geometry(geo=geo)
  679. return _("Backtracked one point ...")
  680. if key == 'T' or key == QtCore.Qt.Key_T:
  681. if self.draw_app.bend_mode == 1:
  682. self.draw_app.bend_mode = 2
  683. msg = _('Corner Mode 2: Reverse 45 degrees ...')
  684. elif self.draw_app.bend_mode == 2:
  685. self.draw_app.bend_mode = 3
  686. msg = _('Corner Mode 3: 90 degrees ...')
  687. elif self.draw_app.bend_mode == 3:
  688. self.draw_app.bend_mode = 4
  689. msg = _('Corner Mode 4: Reverse 90 degrees ...')
  690. elif self.draw_app.bend_mode == 4:
  691. self.draw_app.bend_mode = 5
  692. msg = _('Corner Mode 5: Free angle ...')
  693. else:
  694. self.draw_app.bend_mode = 1
  695. msg = _('Corner Mode 1: 45 degrees ...')
  696. # Remove any previous utility shape
  697. self.draw_app.tool_shape.clear(update=False)
  698. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  699. self.draw_app.draw_utility_geometry(geo=geo)
  700. return msg
  701. if key == 'R' or key == QtCore.Qt.Key_R:
  702. if self.draw_app.bend_mode == 1:
  703. self.draw_app.bend_mode = 5
  704. msg = _('Corner Mode 5: Free angle ...')
  705. elif self.draw_app.bend_mode == 5:
  706. self.draw_app.bend_mode = 4
  707. msg = _('Corner Mode 4: Reverse 90 degrees ...')
  708. elif self.draw_app.bend_mode == 4:
  709. self.draw_app.bend_mode = 3
  710. msg = _('Corner Mode 3: 90 degrees ...')
  711. elif self.draw_app.bend_mode == 3:
  712. self.draw_app.bend_mode = 2
  713. msg = _('Corner Mode 2: Reverse 45 degrees ...')
  714. else:
  715. self.draw_app.bend_mode = 1
  716. msg = _('Corner Mode 1: 45 degrees ...')
  717. # Remove any previous utility shape
  718. self.draw_app.tool_shape.clear(update=False)
  719. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  720. self.draw_app.draw_utility_geometry(geo=geo)
  721. return msg
  722. class FCTrack(FCRegion):
  723. """
  724. Resulting type: Polygon
  725. """
  726. def __init__(self, draw_app):
  727. FCRegion.__init__(self, draw_app)
  728. self.name = 'track'
  729. self.draw_app = draw_app
  730. try:
  731. QtGui.QGuiApplication.restoreOverrideCursor()
  732. except:
  733. pass
  734. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path%s.png' % self.draw_app.bend_mode))
  735. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  736. self.draw_app.app.inform.emit(_('Track Mode 1: 45 degrees ...'))
  737. def make(self):
  738. if len(self.temp_points) == 1:
  739. self.geometry = DrawToolShape(Point(self.temp_points).buffer(self.buf_val))
  740. else:
  741. self.geometry = DrawToolShape(LineString(self.temp_points).buffer(self.buf_val))
  742. self.draw_app.in_action = False
  743. self.complete = True
  744. self.draw_app.app.inform.emit(_("[success] Done."))
  745. def clean_up(self):
  746. self.draw_app.selected = []
  747. self.draw_app.apertures_table.clearSelection()
  748. self.draw_app.plot_all()
  749. def click(self, point):
  750. self.draw_app.in_action = True
  751. self.points.append(point)
  752. if len(self.temp_points) == 1:
  753. g = DrawToolShape(Point(self.temp_points).buffer(self.buf_val))
  754. else:
  755. g = DrawToolShape(LineString(self.temp_points).buffer(self.buf_val))
  756. self.draw_app.add_gerber_shape(g, self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry'])
  757. self.draw_app.plot_all()
  758. if len(self.points) > 0:
  759. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  760. return "Click on next point or hit ENTER to complete ..."
  761. return ""
  762. def utility_geometry(self, data=None):
  763. self.update_grid_info()
  764. if len(self.points) == 0:
  765. return DrawToolUtilityShape(Point(data).buffer(self.buf_val))
  766. elif len(self.points) > 0:
  767. self.temp_points = [self.points[-1]]
  768. old_x = self.points[-1][0]
  769. old_y = self.points[-1][1]
  770. x = data[0]
  771. y = data[1]
  772. mx = abs(round((x - old_x) / self.gridx_size))
  773. my = abs(round((y - old_y) / self.gridy_size))
  774. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  775. if self.draw_app.bend_mode == 1:
  776. if x > old_x:
  777. if mx > my:
  778. self.temp_points.append((old_x + self.gridx_size*(mx-my), old_y))
  779. if mx < my:
  780. if y < old_y:
  781. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  782. else:
  783. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  784. if x < old_x:
  785. if mx > my:
  786. self.temp_points.append((old_x - self.gridx_size*(mx-my), old_y))
  787. if mx < my:
  788. if y < old_y:
  789. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  790. else:
  791. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  792. elif self.draw_app.bend_mode == 2:
  793. if x > old_x:
  794. if mx > my:
  795. self.temp_points.append((old_x + self.gridx_size*my, y))
  796. if mx < my:
  797. if y < old_y:
  798. self.temp_points.append((x, old_y - self.gridy_size * mx))
  799. else:
  800. self.temp_points.append((x, old_y + self.gridy_size * mx))
  801. if x < old_x:
  802. if mx > my:
  803. self.temp_points.append((old_x - self.gridx_size * my, y))
  804. if mx < my:
  805. if y < old_y:
  806. self.temp_points.append((x, old_y - self.gridy_size * mx))
  807. else:
  808. self.temp_points.append((x, old_y + self.gridy_size * mx))
  809. elif self.draw_app.bend_mode == 3:
  810. self.temp_points.append((x, old_y))
  811. elif self.draw_app.bend_mode == 4:
  812. self.temp_points.append((old_x, y))
  813. else:
  814. pass
  815. self.temp_points.append(data)
  816. if len(self.temp_points) == 1:
  817. return DrawToolUtilityShape(Point(self.temp_points).buffer(self.buf_val))
  818. return DrawToolUtilityShape(LineString(self.temp_points).buffer(self.buf_val))
  819. def on_key(self, key):
  820. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  821. if len(self.points) > 0:
  822. self.temp_points = self.points[0:-1]
  823. # Remove any previous utility shape
  824. self.draw_app.tool_shape.clear(update=False)
  825. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  826. self.draw_app.draw_utility_geometry(geo=geo)
  827. return _("Backtracked one point ...")
  828. if key == 'T' or key == QtCore.Qt.Key_T:
  829. try:
  830. QtGui.QGuiApplication.restoreOverrideCursor()
  831. except:
  832. pass
  833. if self.draw_app.bend_mode == 1:
  834. self.draw_app.bend_mode = 2
  835. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path2.png'))
  836. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  837. msg = _('Track Mode 2: Reverse 45 degrees ...')
  838. elif self.draw_app.bend_mode == 2:
  839. self.draw_app.bend_mode = 3
  840. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path3.png'))
  841. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  842. msg = _('Track Mode 3: 90 degrees ...')
  843. elif self.draw_app.bend_mode == 3:
  844. self.draw_app.bend_mode = 4
  845. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path4.png'))
  846. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  847. msg = _('Track Mode 4: Reverse 90 degrees ...')
  848. elif self.draw_app.bend_mode == 4:
  849. self.draw_app.bend_mode = 5
  850. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path5.png'))
  851. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  852. msg = _('Track Mode 5: Free angle ...')
  853. else:
  854. self.draw_app.bend_mode = 1
  855. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path1.png'))
  856. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  857. msg = _('Track Mode 1: 45 degrees ...')
  858. # Remove any previous utility shape
  859. self.draw_app.tool_shape.clear(update=False)
  860. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  861. self.draw_app.draw_utility_geometry(geo=geo)
  862. return msg
  863. if key == 'R' or key == QtCore.Qt.Key_R:
  864. try:
  865. QtGui.QGuiApplication.restoreOverrideCursor()
  866. except:
  867. pass
  868. if self.draw_app.bend_mode == 1:
  869. self.draw_app.bend_mode = 5
  870. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path5.png'))
  871. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  872. msg = _('Track Mode 5: Free angle ...')
  873. elif self.draw_app.bend_mode == 5:
  874. self.draw_app.bend_mode = 4
  875. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path4.png'))
  876. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  877. msg = _('Track Mode 4: Reverse 90 degrees ...')
  878. elif self.draw_app.bend_mode == 4:
  879. self.draw_app.bend_mode = 3
  880. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path3.png'))
  881. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  882. msg = _('Track Mode 3: 90 degrees ...')
  883. elif self.draw_app.bend_mode == 3:
  884. self.draw_app.bend_mode = 2
  885. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path2.png'))
  886. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  887. msg = _('Track Mode 2: Reverse 45 degrees ...')
  888. else:
  889. self.draw_app.bend_mode = 1
  890. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path1.png'))
  891. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  892. msg = _('Track Mode 1: 45 degrees ...')
  893. # Remove any previous utility shape
  894. self.draw_app.tool_shape.clear(update=False)
  895. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  896. self.draw_app.draw_utility_geometry(geo=geo)
  897. return msg
  898. class FCDisc(FCShapeTool):
  899. """
  900. Resulting type: Polygon
  901. """
  902. def __init__(self, draw_app):
  903. DrawTool.__init__(self, draw_app)
  904. self.name = 'disc'
  905. try:
  906. QtGui.QGuiApplication.restoreOverrideCursor()
  907. except:
  908. pass
  909. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_disc.png'))
  910. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  911. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  912. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  913. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  914. self.start_msg = _("Click on Center point ...")
  915. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  916. self.steps_per_circ = self.draw_app.app.defaults["gerber_circle_steps"]
  917. def click(self, point):
  918. self.points.append(point)
  919. if len(self.points) == 1:
  920. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  921. return "Click on Perimeter to complete ..."
  922. if len(self.points) == 2:
  923. self.make()
  924. return "Done."
  925. return ""
  926. def utility_geometry(self, data=None):
  927. if len(self.points) == 1:
  928. p1 = self.points[0]
  929. p2 = data
  930. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  931. return DrawToolUtilityShape(Point(p1).buffer((radius + self.buf_val / 2), int(self.steps_per_circ / 4)))
  932. return None
  933. def make(self):
  934. try:
  935. QtGui.QGuiApplication.restoreOverrideCursor()
  936. except:
  937. pass
  938. self.draw_app.current_storage = self.storage_obj
  939. p1 = self.points[0]
  940. p2 = self.points[1]
  941. radius = distance(p1, p2)
  942. self.geometry = DrawToolShape(Point(p1).buffer((radius + self.buf_val / 2), int(self.steps_per_circ / 4)))
  943. self.draw_app.in_action = False
  944. self.complete = True
  945. self.draw_app.app.inform.emit(_("[success] Done."))
  946. def clean_up(self):
  947. self.draw_app.selected = []
  948. self.draw_app.apertures_table.clearSelection()
  949. self.draw_app.plot_all()
  950. class FCSemiDisc(FCShapeTool):
  951. def __init__(self, draw_app):
  952. DrawTool.__init__(self, draw_app)
  953. self.name = 'semidisc'
  954. try:
  955. QtGui.QGuiApplication.restoreOverrideCursor()
  956. except:
  957. pass
  958. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_semidisc.png'))
  959. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  960. self.start_msg = _("Click on Center point ...")
  961. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  962. # Direction of rotation between point 1 and 2.
  963. # 'cw' or 'ccw'. Switch direction by hitting the
  964. # 'o' key.
  965. self.direction = "cw"
  966. # Mode
  967. # C12 = Center, p1, p2
  968. # 12C = p1, p2, Center
  969. # 132 = p1, p3, p2
  970. self.mode = "c12" # Center, p1, p2
  971. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  972. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  973. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['solid_geometry']
  974. self.steps_per_circ = self.draw_app.app.defaults["gerber_circle_steps"]
  975. def click(self, point):
  976. self.points.append(point)
  977. if len(self.points) == 1:
  978. if self.mode == 'c12':
  979. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  980. elif self.mode == '132':
  981. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  982. else:
  983. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  984. return "Click on 1st point ..."
  985. if len(self.points) == 2:
  986. if self.mode == 'c12':
  987. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  988. elif self.mode == '132':
  989. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  990. else:
  991. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  992. return "Click on 2nd point to complete ..."
  993. if len(self.points) == 3:
  994. self.make()
  995. return "Done."
  996. return ""
  997. def on_key(self, key):
  998. if key == 'D' or key == QtCore.Qt.Key_D:
  999. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1000. return _('Direction: %s') % self.direction.upper()
  1001. if key == 'M' or key == QtCore.Qt.Key_M:
  1002. # delete the possible points made before this action; we want to start anew
  1003. self.points = []
  1004. # and delete the utility geometry made up until this point
  1005. self.draw_app.delete_utility_geometry()
  1006. if self.mode == 'c12':
  1007. self.mode = '12c'
  1008. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1009. elif self.mode == '12c':
  1010. self.mode = '132'
  1011. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1012. else:
  1013. self.mode = 'c12'
  1014. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1015. def utility_geometry(self, data=None):
  1016. if len(self.points) == 1: # Show the radius
  1017. center = self.points[0]
  1018. p1 = data
  1019. return DrawToolUtilityShape(LineString([center, p1]))
  1020. if len(self.points) == 2: # Show the arc
  1021. if self.mode == 'c12':
  1022. center = self.points[0]
  1023. p1 = self.points[1]
  1024. p2 = data
  1025. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2) + (self.buf_val / 2)
  1026. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1027. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1028. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1029. self.direction, self.steps_per_circ)),
  1030. Point(center)])
  1031. elif self.mode == '132':
  1032. p1 = array(self.points[0])
  1033. p3 = array(self.points[1])
  1034. p2 = array(data)
  1035. try:
  1036. center, radius, t = three_point_circle(p1, p2, p3)
  1037. except TypeError:
  1038. return
  1039. direction = 'cw' if sign(t) > 0 else 'ccw'
  1040. radius += (self.buf_val / 2)
  1041. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1042. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1043. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1044. direction, self.steps_per_circ)),
  1045. Point(center), Point(p1), Point(p3)])
  1046. else: # '12c'
  1047. p1 = array(self.points[0])
  1048. p2 = array(self.points[1])
  1049. # Midpoint
  1050. a = (p1 + p2) / 2.0
  1051. # Parallel vector
  1052. c = p2 - p1
  1053. # Perpendicular vector
  1054. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1055. b /= numpy_norm(b)
  1056. # Distance
  1057. t = distance(data, a)
  1058. # Which side? Cross product with c.
  1059. # cross(M-A, B-A), where line is AB and M is test point.
  1060. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1061. t *= sign(side)
  1062. # Center = a + bt
  1063. center = a + b * t
  1064. radius = numpy_norm(center - p1) + (self.buf_val / 2)
  1065. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1066. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1067. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1068. self.direction, self.steps_per_circ)),
  1069. Point(center)])
  1070. return None
  1071. def make(self):
  1072. self.draw_app.current_storage = self.storage_obj
  1073. if self.mode == 'c12':
  1074. center = self.points[0]
  1075. p1 = self.points[1]
  1076. p2 = self.points[2]
  1077. radius = distance(center, p1) + (self.buf_val / 2)
  1078. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1079. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1080. self.geometry = DrawToolShape(Polygon(arc(center, radius, startangle, stopangle,
  1081. self.direction, self.steps_per_circ)))
  1082. elif self.mode == '132':
  1083. p1 = array(self.points[0])
  1084. p3 = array(self.points[1])
  1085. p2 = array(self.points[2])
  1086. center, radius, t = three_point_circle(p1, p2, p3)
  1087. direction = 'cw' if sign(t) > 0 else 'ccw'
  1088. radius += (self.buf_val / 2)
  1089. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1090. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1091. self.geometry = DrawToolShape(Polygon(arc(center, radius, startangle, stopangle,
  1092. direction, self.steps_per_circ)))
  1093. else: # self.mode == '12c'
  1094. p1 = array(self.points[0])
  1095. p2 = array(self.points[1])
  1096. pc = array(self.points[2])
  1097. # Midpoint
  1098. a = (p1 + p2) / 2.0
  1099. # Parallel vector
  1100. c = p2 - p1
  1101. # Perpendicular vector
  1102. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1103. b /= numpy_norm(b)
  1104. # Distance
  1105. t = distance(pc, a)
  1106. # Which side? Cross product with c.
  1107. # cross(M-A, B-A), where line is AB and M is test point.
  1108. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1109. t *= sign(side)
  1110. # Center = a + bt
  1111. center = a + b * t
  1112. radius = numpy_norm(center - p1) + (self.buf_val / 2)
  1113. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1114. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1115. self.geometry = DrawToolShape(Polygon(arc(center, radius, startangle, stopangle,
  1116. self.direction, self.steps_per_circ)))
  1117. self.draw_app.in_action = False
  1118. self.complete = True
  1119. self.draw_app.app.inform.emit(_("[success] Done."))
  1120. def clean_up(self):
  1121. self.draw_app.selected = []
  1122. self.draw_app.apertures_table.clearSelection()
  1123. self.draw_app.plot_all()
  1124. class FCScale(FCShapeTool):
  1125. def __init__(self, draw_app):
  1126. FCShapeTool.__init__(self, draw_app)
  1127. self.name = 'scale'
  1128. # self.shape_buffer = self.draw_app.shape_buffer
  1129. self.draw_app = draw_app
  1130. self.app = draw_app.app
  1131. self.start_msg = _("Scale the selected Gerber apertures ...")
  1132. self.origin = (0, 0)
  1133. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  1134. self.draw_app.app.ui.splitter.setSizes([1, 1])
  1135. self.activate_scale()
  1136. def activate_scale(self):
  1137. self.draw_app.hide_tool('all')
  1138. self.draw_app.scale_tool_frame.show()
  1139. try:
  1140. self.draw_app.scale_button.clicked.disconnect()
  1141. except TypeError:
  1142. pass
  1143. self.draw_app.scale_button.clicked.connect(self.on_scale_click)
  1144. def deactivate_scale(self):
  1145. self.draw_app.scale_button.clicked.disconnect()
  1146. self.complete = True
  1147. self.draw_app.select_tool("select")
  1148. self.draw_app.hide_tool(self.name)
  1149. def on_scale_click(self):
  1150. self.draw_app.on_scale()
  1151. self.deactivate_scale()
  1152. def clean_up(self):
  1153. self.draw_app.selected = []
  1154. self.draw_app.apertures_table.clearSelection()
  1155. self.draw_app.plot_all()
  1156. class FCBuffer(FCShapeTool):
  1157. def __init__(self, draw_app):
  1158. FCShapeTool.__init__(self, draw_app)
  1159. self.name = 'buffer'
  1160. # self.shape_buffer = self.draw_app.shape_buffer
  1161. self.draw_app = draw_app
  1162. self.app = draw_app.app
  1163. self.start_msg = _("Buffer the selected apertures ...")
  1164. self.origin = (0, 0)
  1165. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  1166. self.draw_app.app.ui.splitter.setSizes([1, 1])
  1167. self.activate_buffer()
  1168. def activate_buffer(self):
  1169. self.draw_app.hide_tool('all')
  1170. self.draw_app.buffer_tool_frame.show()
  1171. try:
  1172. self.draw_app.buffer_button.clicked.disconnect()
  1173. except TypeError:
  1174. pass
  1175. self.draw_app.buffer_button.clicked.connect(self.on_buffer_click)
  1176. def deactivate_buffer(self):
  1177. self.draw_app.buffer_button.clicked.disconnect()
  1178. self.complete = True
  1179. self.draw_app.select_tool("select")
  1180. self.draw_app.hide_tool(self.name)
  1181. def on_buffer_click(self):
  1182. self.draw_app.on_buffer()
  1183. self.deactivate_buffer()
  1184. def clean_up(self):
  1185. self.draw_app.selected = []
  1186. self.draw_app.apertures_table.clearSelection()
  1187. self.draw_app.plot_all()
  1188. class FCApertureMove(FCShapeTool):
  1189. def __init__(self, draw_app):
  1190. DrawTool.__init__(self, draw_app)
  1191. self.name = 'move'
  1192. # self.shape_buffer = self.draw_app.shape_buffer
  1193. self.origin = None
  1194. self.destination = None
  1195. self.selected_apertures = []
  1196. if self.draw_app.launched_from_shortcuts is True:
  1197. self.draw_app.launched_from_shortcuts = False
  1198. self.draw_app.app.inform.emit(_("Click on target location ..."))
  1199. else:
  1200. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  1201. self.current_storage = None
  1202. self.geometry = []
  1203. for index in self.draw_app.apertures_table.selectedIndexes():
  1204. row = index.row()
  1205. # on column 1 in tool tables we hold the aperture codes, and we retrieve them as strings
  1206. aperture_on_row = self.draw_app.apertures_table.item(row, 1).text()
  1207. self.selected_apertures.append(aperture_on_row)
  1208. # Switch notebook to Selected page
  1209. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  1210. def set_origin(self, origin):
  1211. self.origin = origin
  1212. def click(self, point):
  1213. if len(self.draw_app.get_selected()) == 0:
  1214. return "Nothing to move."
  1215. if self.origin is None:
  1216. self.set_origin(point)
  1217. self.draw_app.app.inform.emit(_("Click on target location ..."))
  1218. return
  1219. else:
  1220. self.destination = point
  1221. self.make()
  1222. # MS: always return to the Select Tool
  1223. self.draw_app.select_tool("select")
  1224. return
  1225. def make(self):
  1226. # Create new geometry
  1227. dx = self.destination[0] - self.origin[0]
  1228. dy = self.destination[1] - self.origin[1]
  1229. sel_shapes_to_be_deleted = []
  1230. for sel_dia in self.selected_apertures:
  1231. self.current_storage = self.draw_app.storage_dict[sel_dia]['solid_geometry']
  1232. for select_shape in self.draw_app.get_selected():
  1233. if select_shape in self.current_storage:
  1234. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  1235. self.current_storage.remove(select_shape)
  1236. sel_shapes_to_be_deleted.append(select_shape)
  1237. self.draw_app.on_grb_shape_complete(self.current_storage)
  1238. self.geometry = []
  1239. for shp in sel_shapes_to_be_deleted:
  1240. self.draw_app.selected.remove(shp)
  1241. sel_shapes_to_be_deleted = []
  1242. self.draw_app.build_ui()
  1243. self.draw_app.app.inform.emit(_("[success] Done. Apertures Move completed."))
  1244. def clean_up(self):
  1245. self.draw_app.selected = []
  1246. self.draw_app.apertures_table.clearSelection()
  1247. self.draw_app.plot_all()
  1248. def utility_geometry(self, data=None):
  1249. """
  1250. Temporary geometry on screen while using this tool.
  1251. :param data:
  1252. :return:
  1253. """
  1254. geo_list = []
  1255. if self.origin is None:
  1256. return None
  1257. if len(self.draw_app.get_selected()) == 0:
  1258. return None
  1259. dx = data[0] - self.origin[0]
  1260. dy = data[1] - self.origin[1]
  1261. for geom in self.draw_app.get_selected():
  1262. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  1263. return DrawToolUtilityShape(geo_list)
  1264. class FCApertureCopy(FCApertureMove):
  1265. def __init__(self, draw_app):
  1266. FCApertureMove.__init__(self, draw_app)
  1267. self.name = 'copy'
  1268. def make(self):
  1269. # Create new geometry
  1270. dx = self.destination[0] - self.origin[0]
  1271. dy = self.destination[1] - self.origin[1]
  1272. sel_shapes_to_be_deleted = []
  1273. for sel_dia in self.selected_apertures:
  1274. self.current_storage = self.draw_app.storage_dict[sel_dia]['solid_geometry']
  1275. for select_shape in self.draw_app.get_selected():
  1276. if select_shape in self.current_storage:
  1277. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  1278. sel_shapes_to_be_deleted.append(select_shape)
  1279. self.draw_app.on_grb_shape_complete(self.current_storage)
  1280. self.geometry = []
  1281. for shp in sel_shapes_to_be_deleted:
  1282. self.draw_app.selected.remove(shp)
  1283. sel_shapes_to_be_deleted = []
  1284. self.draw_app.build_ui()
  1285. self.draw_app.app.inform.emit(_("[success] Done. Apertures copied."))
  1286. class FCApertureSelect(DrawTool):
  1287. def __init__(self, grb_editor_app):
  1288. DrawTool.__init__(self, grb_editor_app)
  1289. self.name = 'select'
  1290. self.origin = None
  1291. self.grb_editor_app = grb_editor_app
  1292. self.storage = self.grb_editor_app.storage_dict
  1293. # self.selected = self.grb_editor_app.selected
  1294. # here we store all shapes that were selected
  1295. self.sel_storage = []
  1296. # since FCApertureSelect tool is activated whenever a tool is exited I place here the reinitialization of the
  1297. # bending modes using in FCRegion and FCTrack
  1298. self.draw_app.bend_mode = 1
  1299. try:
  1300. self.grb_editor_app.apertures_table.clearSelection()
  1301. except Exception as e:
  1302. log.error("FlatCAMGerbEditor.FCApertureSelect.__init__() --> %s" % str(e))
  1303. self.grb_editor_app.hide_tool('all')
  1304. self.grb_editor_app.hide_tool('select')
  1305. try:
  1306. QtGui.QGuiApplication.restoreOverrideCursor()
  1307. except:
  1308. pass
  1309. def set_origin(self, origin):
  1310. self.origin = origin
  1311. def click(self, point):
  1312. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1313. if self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1314. if key_modifier == Qt.ControlModifier:
  1315. pass
  1316. else:
  1317. self.grb_editor_app.selected = []
  1318. else:
  1319. if key_modifier == Qt.ShiftModifier:
  1320. pass
  1321. else:
  1322. self.grb_editor_app.selected = []
  1323. def click_release(self, point):
  1324. self.grb_editor_app.apertures_table.clearSelection()
  1325. sel_aperture = set()
  1326. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1327. for storage in self.grb_editor_app.storage_dict:
  1328. try:
  1329. for shape in self.grb_editor_app.storage_dict[storage]['solid_geometry']:
  1330. if Point(point).within(shape.geo):
  1331. if (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control' and
  1332. key_modifier == Qt.ControlModifier) or \
  1333. (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Shift' and
  1334. key_modifier == Qt.ShiftModifier):
  1335. if shape in self.draw_app.selected:
  1336. self.draw_app.selected.remove(shape)
  1337. else:
  1338. # add the object to the selected shapes
  1339. self.draw_app.selected.append(shape)
  1340. sel_aperture.add(storage)
  1341. else:
  1342. self.draw_app.selected.append(shape)
  1343. sel_aperture.add(storage)
  1344. except KeyError:
  1345. pass
  1346. # select the aperture in the Apertures Table that is associated with the selected shape
  1347. try:
  1348. self.draw_app.apertures_table.cellPressed.disconnect()
  1349. except:
  1350. pass
  1351. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1352. for aper in sel_aperture:
  1353. for row in range(self.grb_editor_app.apertures_table.rowCount()):
  1354. if str(aper) == self.grb_editor_app.apertures_table.item(row, 1).text():
  1355. self.grb_editor_app.apertures_table.selectRow(row)
  1356. self.draw_app.last_aperture_selected = aper
  1357. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1358. self.draw_app.apertures_table.cellPressed.connect(self.draw_app.on_row_selected)
  1359. return ""
  1360. def clean_up(self):
  1361. self.draw_app.plot_all()
  1362. class FCTransform(FCShapeTool):
  1363. def __init__(self, draw_app):
  1364. FCShapeTool.__init__(self, draw_app)
  1365. self.name = 'transformation'
  1366. # self.shape_buffer = self.draw_app.shape_buffer
  1367. self.draw_app = draw_app
  1368. self.app = draw_app.app
  1369. self.start_msg = _("Shape transformations ...")
  1370. self.origin = (0, 0)
  1371. self.draw_app.transform_tool.run()
  1372. def clean_up(self):
  1373. self.draw_app.selected = []
  1374. self.draw_app.apertures_table.clearSelection()
  1375. self.draw_app.plot_all()
  1376. class FlatCAMGrbEditor(QtCore.QObject):
  1377. draw_shape_idx = -1
  1378. def __init__(self, app):
  1379. assert isinstance(app, FlatCAMApp.App), \
  1380. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1381. super(FlatCAMGrbEditor, self).__init__()
  1382. self.app = app
  1383. self.canvas = self.app.plotcanvas
  1384. ## Current application units in Upper Case
  1385. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1386. self.grb_edit_widget = QtWidgets.QWidget()
  1387. layout = QtWidgets.QVBoxLayout()
  1388. self.grb_edit_widget.setLayout(layout)
  1389. ## Page Title box (spacing between children)
  1390. self.title_box = QtWidgets.QHBoxLayout()
  1391. layout.addLayout(self.title_box)
  1392. ## Page Title icon
  1393. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1394. self.icon = QtWidgets.QLabel()
  1395. self.icon.setPixmap(pixmap)
  1396. self.title_box.addWidget(self.icon, stretch=0)
  1397. ## Title label
  1398. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Gerber Editor'))
  1399. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1400. self.title_box.addWidget(self.title_label, stretch=1)
  1401. ## Object name
  1402. self.name_box = QtWidgets.QHBoxLayout()
  1403. layout.addLayout(self.name_box)
  1404. name_label = QtWidgets.QLabel(_("Name:"))
  1405. self.name_box.addWidget(name_label)
  1406. self.name_entry = FCEntry()
  1407. self.name_box.addWidget(self.name_entry)
  1408. ## Box for custom widgets
  1409. # This gets populated in offspring implementations.
  1410. self.custom_box = QtWidgets.QVBoxLayout()
  1411. layout.addLayout(self.custom_box)
  1412. #### Gerber Apertures ####
  1413. self.apertures_table_label = QtWidgets.QLabel(_('<b>Apertures:</b>'))
  1414. self.apertures_table_label.setToolTip(
  1415. _("Apertures Table for the Gerber Object.")
  1416. )
  1417. self.custom_box.addWidget(self.apertures_table_label)
  1418. self.apertures_table = FCTable()
  1419. # delegate = SpinBoxDelegate(units=self.units)
  1420. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  1421. self.custom_box.addWidget(self.apertures_table)
  1422. self.apertures_table.setColumnCount(5)
  1423. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  1424. self.apertures_table.setSortingEnabled(False)
  1425. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  1426. _("Index"))
  1427. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  1428. _("Aperture Code"))
  1429. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  1430. _("Type of aperture: circular, rectangle, macros etc"))
  1431. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  1432. _("Aperture Size:"))
  1433. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  1434. _("Aperture Dimensions:\n"
  1435. " - (width, height) for R, O type.\n"
  1436. " - (dia, nVertices) for P type"))
  1437. self.empty_label = QtWidgets.QLabel('')
  1438. self.custom_box.addWidget(self.empty_label)
  1439. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Apertures widgets
  1440. # this way I can hide/show the frame
  1441. self.apertures_frame = QtWidgets.QFrame()
  1442. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  1443. self.custom_box.addWidget(self.apertures_frame)
  1444. self.apertures_box = QtWidgets.QVBoxLayout()
  1445. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  1446. self.apertures_frame.setLayout(self.apertures_box)
  1447. #### Add/Delete an new Aperture ####
  1448. grid1 = QtWidgets.QGridLayout()
  1449. self.apertures_box.addLayout(grid1)
  1450. apcode_lbl = QtWidgets.QLabel(_('Aperture Code:'))
  1451. apcode_lbl.setToolTip(
  1452. _("Code for the new aperture")
  1453. )
  1454. grid1.addWidget(apcode_lbl, 1, 0)
  1455. self.apcode_entry = FCEntry()
  1456. self.apcode_entry.setValidator(QtGui.QIntValidator(0, 999))
  1457. grid1.addWidget(self.apcode_entry, 1, 1)
  1458. apsize_lbl = QtWidgets.QLabel(_('Aperture Size:'))
  1459. apsize_lbl.setToolTip(
  1460. _("Size for the new aperture.\n"
  1461. "If aperture type is 'R' or 'O' then\n"
  1462. "this value is automatically\n"
  1463. "calculated as:\n"
  1464. "sqrt(width**2 + height**2)")
  1465. )
  1466. grid1.addWidget(apsize_lbl, 2, 0)
  1467. self.apsize_entry = FCEntry()
  1468. self.apsize_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1469. grid1.addWidget(self.apsize_entry, 2, 1)
  1470. aptype_lbl = QtWidgets.QLabel(_('Aperture Type:'))
  1471. aptype_lbl.setToolTip(
  1472. _("Select the type of new aperture. Can be:\n"
  1473. "C = circular\n"
  1474. "R = rectangular\n"
  1475. "O = oblong")
  1476. )
  1477. grid1.addWidget(aptype_lbl, 3, 0)
  1478. self.aptype_cb = FCComboBox()
  1479. self.aptype_cb.addItems(['C', 'R', 'O'])
  1480. grid1.addWidget(self.aptype_cb, 3, 1)
  1481. self.apdim_lbl = QtWidgets.QLabel(_('Aperture Dim:'))
  1482. self.apdim_lbl.setToolTip(
  1483. _("Dimensions for the new aperture.\n"
  1484. "Active only for rectangular apertures (type R).\n"
  1485. "The format is (width, height)")
  1486. )
  1487. grid1.addWidget(self.apdim_lbl, 4, 0)
  1488. self.apdim_entry = EvalEntry2()
  1489. grid1.addWidget(self.apdim_entry, 4, 1)
  1490. apadd_del_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Aperture:'))
  1491. apadd_del_lbl.setToolTip(
  1492. _("Add/Delete an aperture in the aperture table")
  1493. )
  1494. self.apertures_box.addWidget(apadd_del_lbl)
  1495. hlay_ad = QtWidgets.QHBoxLayout()
  1496. self.apertures_box.addLayout(hlay_ad)
  1497. self.addaperture_btn = QtWidgets.QPushButton(_('Add'))
  1498. self.addaperture_btn.setToolTip(
  1499. _( "Add a new aperture to the aperture list.")
  1500. )
  1501. self.delaperture_btn = QtWidgets.QPushButton(_('Delete'))
  1502. self.delaperture_btn.setToolTip(
  1503. _( "Delete a aperture in the aperture list")
  1504. )
  1505. hlay_ad.addWidget(self.addaperture_btn)
  1506. hlay_ad.addWidget(self.delaperture_btn)
  1507. ### BUFFER TOOL ###
  1508. self.buffer_tool_frame = QtWidgets.QFrame()
  1509. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  1510. self.custom_box.addWidget(self.buffer_tool_frame)
  1511. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  1512. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  1513. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  1514. self.buffer_tool_frame.hide()
  1515. # Title
  1516. buf_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Buffer Aperture:'))
  1517. buf_title_lbl.setToolTip(
  1518. _("Buffer a aperture in the aperture list")
  1519. )
  1520. self.buffer_tools_box.addWidget(buf_title_lbl)
  1521. # Form Layout
  1522. buf_form_layout = QtWidgets.QFormLayout()
  1523. self.buffer_tools_box.addLayout(buf_form_layout)
  1524. # Buffer distance
  1525. self.buffer_distance_entry = FCEntry()
  1526. buf_form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  1527. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  1528. self.buffer_corner_lbl.setToolTip(
  1529. _("There are 3 types of corners:\n"
  1530. " - 'Round': the corner is rounded.\n"
  1531. " - 'Square:' the corner is met in a sharp angle.\n"
  1532. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  1533. )
  1534. self.buffer_corner_cb = FCComboBox()
  1535. self.buffer_corner_cb.addItem(_("Round"))
  1536. self.buffer_corner_cb.addItem(_("Square"))
  1537. self.buffer_corner_cb.addItem(_("Beveled"))
  1538. buf_form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  1539. # Buttons
  1540. hlay_buf = QtWidgets.QHBoxLayout()
  1541. self.buffer_tools_box.addLayout(hlay_buf)
  1542. self.buffer_button = QtWidgets.QPushButton(_("Buffer"))
  1543. hlay_buf.addWidget(self.buffer_button)
  1544. ### SCALE TOOL ###
  1545. self.scale_tool_frame = QtWidgets.QFrame()
  1546. self.scale_tool_frame.setContentsMargins(0, 0, 0, 0)
  1547. self.custom_box.addWidget(self.scale_tool_frame)
  1548. self.scale_tools_box = QtWidgets.QVBoxLayout()
  1549. self.scale_tools_box.setContentsMargins(0, 0, 0, 0)
  1550. self.scale_tool_frame.setLayout(self.scale_tools_box)
  1551. self.scale_tool_frame.hide()
  1552. # Title
  1553. scale_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Scale Aperture:'))
  1554. scale_title_lbl.setToolTip(
  1555. _("Scale a aperture in the aperture list")
  1556. )
  1557. self.scale_tools_box.addWidget(scale_title_lbl)
  1558. # Form Layout
  1559. scale_form_layout = QtWidgets.QFormLayout()
  1560. self.scale_tools_box.addLayout(scale_form_layout)
  1561. self.scale_factor_lbl = QtWidgets.QLabel(_("Scale factor:"))
  1562. self.scale_factor_lbl.setToolTip(
  1563. _("The factor by which to scale the selected aperture.\n"
  1564. "Values can be between 0.0000 and 999.9999")
  1565. )
  1566. self.scale_factor_entry = FCEntry()
  1567. self.scale_factor_entry.setValidator(QtGui.QDoubleValidator(0.0000, 999.9999, 4))
  1568. scale_form_layout.addRow(self.scale_factor_lbl, self.scale_factor_entry)
  1569. # Buttons
  1570. hlay_scale = QtWidgets.QHBoxLayout()
  1571. self.scale_tools_box.addLayout(hlay_scale)
  1572. self.scale_button = QtWidgets.QPushButton(_("Scale"))
  1573. hlay_scale.addWidget(self.scale_button)
  1574. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1575. # all the add Pad array widgets
  1576. # this way I can hide/show the frame
  1577. self.array_frame = QtWidgets.QFrame()
  1578. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1579. self.custom_box.addWidget(self.array_frame)
  1580. self.array_box = QtWidgets.QVBoxLayout()
  1581. self.array_box.setContentsMargins(0, 0, 0, 0)
  1582. self.array_frame.setLayout(self.array_box)
  1583. #### Add Pad Array ####
  1584. self.emptyarray_label = QtWidgets.QLabel('')
  1585. self.array_box.addWidget(self.emptyarray_label)
  1586. self.padarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Pad Array"))
  1587. self.padarray_label.setToolTip(
  1588. _("Add an array of pads (linear or circular array)")
  1589. )
  1590. self.array_box.addWidget(self.padarray_label)
  1591. self.array_type_combo = FCComboBox()
  1592. self.array_type_combo.setToolTip(
  1593. _( "Select the type of pads array to create.\n"
  1594. "It can be Linear X(Y) or Circular")
  1595. )
  1596. self.array_type_combo.addItem(_("Linear"))
  1597. self.array_type_combo.addItem(_("Circular"))
  1598. self.array_box.addWidget(self.array_type_combo)
  1599. self.array_form = QtWidgets.QFormLayout()
  1600. self.array_box.addLayout(self.array_form)
  1601. self.pad_array_size_label = QtWidgets.QLabel(_('Nr of pads:'))
  1602. self.pad_array_size_label.setToolTip(
  1603. _("Specify how many pads to be in the array.")
  1604. )
  1605. self.pad_array_size_label.setFixedWidth(100)
  1606. self.pad_array_size_entry = LengthEntry()
  1607. self.array_form.addRow(self.pad_array_size_label, self.pad_array_size_entry)
  1608. self.array_linear_frame = QtWidgets.QFrame()
  1609. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1610. self.array_box.addWidget(self.array_linear_frame)
  1611. self.linear_box = QtWidgets.QVBoxLayout()
  1612. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1613. self.array_linear_frame.setLayout(self.linear_box)
  1614. self.linear_form = QtWidgets.QFormLayout()
  1615. self.linear_box.addLayout(self.linear_form)
  1616. self.pad_axis_label = QtWidgets.QLabel(_('Direction:'))
  1617. self.pad_axis_label.setToolTip(
  1618. _("Direction on which the linear array is oriented:\n"
  1619. "- 'X' - horizontal axis \n"
  1620. "- 'Y' - vertical axis or \n"
  1621. "- 'Angle' - a custom angle for the array inclination")
  1622. )
  1623. self.pad_axis_label.setFixedWidth(100)
  1624. self.pad_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  1625. {'label': 'Y', 'value': 'Y'},
  1626. {'label': 'Angle', 'value': 'A'}])
  1627. self.pad_axis_radio.set_value('X')
  1628. self.linear_form.addRow(self.pad_axis_label, self.pad_axis_radio)
  1629. self.pad_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1630. self.pad_pitch_label.setToolTip(
  1631. _("Pitch = Distance between elements of the array.")
  1632. )
  1633. self.pad_pitch_label.setFixedWidth(100)
  1634. self.pad_pitch_entry = LengthEntry()
  1635. self.linear_form.addRow(self.pad_pitch_label, self.pad_pitch_entry)
  1636. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1637. self.linear_angle_label.setToolTip(
  1638. _( "Angle at which the linear array is placed.\n"
  1639. "The precision is of max 2 decimals.\n"
  1640. "Min value is: -359.99 degrees.\n"
  1641. "Max value is: 360.00 degrees.")
  1642. )
  1643. self.linear_angle_label.setFixedWidth(100)
  1644. self.linear_angle_spinner = FCDoubleSpinner()
  1645. self.linear_angle_spinner.set_precision(2)
  1646. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1647. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1648. self.array_circular_frame = QtWidgets.QFrame()
  1649. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1650. self.array_box.addWidget(self.array_circular_frame)
  1651. self.circular_box = QtWidgets.QVBoxLayout()
  1652. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1653. self.array_circular_frame.setLayout(self.circular_box)
  1654. self.pad_direction_label = QtWidgets.QLabel(_('Direction:'))
  1655. self.pad_direction_label.setToolTip(
  1656. _( "Direction for circular array."
  1657. "Can be CW = clockwise or CCW = counter clockwise.")
  1658. )
  1659. self.pad_direction_label.setFixedWidth(100)
  1660. self.circular_form = QtWidgets.QFormLayout()
  1661. self.circular_box.addLayout(self.circular_form)
  1662. self.pad_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  1663. {'label': 'CCW.', 'value': 'CCW'}])
  1664. self.pad_direction_radio.set_value('CW')
  1665. self.circular_form.addRow(self.pad_direction_label, self.pad_direction_radio)
  1666. self.pad_angle_label = QtWidgets.QLabel(_('Angle:'))
  1667. self.pad_angle_label.setToolTip(
  1668. _("Angle at which each element in circular array is placed.")
  1669. )
  1670. self.pad_angle_label.setFixedWidth(100)
  1671. self.pad_angle_entry = LengthEntry()
  1672. self.circular_form.addRow(self.pad_angle_label, self.pad_angle_entry)
  1673. self.array_circular_frame.hide()
  1674. self.linear_angle_spinner.hide()
  1675. self.linear_angle_label.hide()
  1676. self.array_frame.hide()
  1677. self.custom_box.addStretch()
  1678. ## Toolbar events and properties
  1679. self.tools_gerber = {
  1680. "select": {"button": self.app.ui.grb_select_btn,
  1681. "constructor": FCApertureSelect},
  1682. "pad": {"button": self.app.ui.grb_add_pad_btn,
  1683. "constructor": FCPad},
  1684. "array": {"button": self.app.ui.add_pad_ar_btn,
  1685. "constructor": FCPadArray},
  1686. "track": {"button": self.app.ui.grb_add_track_btn,
  1687. "constructor": FCTrack},
  1688. "region": {"button": self.app.ui.grb_add_region_btn,
  1689. "constructor": FCRegion},
  1690. "poligonize": {"button": self.app.ui.grb_convert_poly_btn,
  1691. "constructor": FCPoligonize},
  1692. "semidisc": {"button": self.app.ui.grb_add_semidisc_btn,
  1693. "constructor": FCSemiDisc},
  1694. "disc": {"button": self.app.ui.grb_add_disc_btn,
  1695. "constructor": FCDisc},
  1696. "buffer": {"button": self.app.ui.aperture_buffer_btn,
  1697. "constructor": FCBuffer},
  1698. "scale": {"button": self.app.ui.aperture_scale_btn,
  1699. "constructor": FCScale},
  1700. "copy": {"button": self.app.ui.aperture_copy_btn,
  1701. "constructor": FCApertureCopy},
  1702. "transform": {"button": self.app.ui.grb_transform_btn,
  1703. "constructor": FCTransform},
  1704. "move": {"button": self.app.ui.aperture_move_btn,
  1705. "constructor": FCApertureMove},
  1706. }
  1707. ### Data
  1708. self.active_tool = None
  1709. self.storage_dict = {}
  1710. self.current_storage = []
  1711. self.sorted_apid =[]
  1712. self.new_apertures = {}
  1713. self.new_aperture_macros = {}
  1714. # store here the plot promises, if empty the delayed plot will be activated
  1715. self.grb_plot_promises = []
  1716. # dictionary to store the tool_row and aperture codes in Tool_table
  1717. # it will be updated everytime self.build_ui() is called
  1718. self.olddia_newdia = {}
  1719. self.tool2tooldia = {}
  1720. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1721. # is cleared but as a side effect also the selected tool is cleared
  1722. self.last_aperture_selected = None
  1723. self.utility = []
  1724. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1725. self.launched_from_shortcuts = False
  1726. # this var will store the state of the toolbar before starting the editor
  1727. self.toolbar_old_state = False
  1728. # holds flattened geometry
  1729. self.flat_geometry = []
  1730. # Init GUI
  1731. self.apdim_lbl.hide()
  1732. self.apdim_entry.hide()
  1733. self.gerber_obj = None
  1734. self.gerber_obj_options = {}
  1735. self.buffer_distance_entry.set_value(0.01)
  1736. self.scale_factor_entry.set_value(1.0)
  1737. # VisPy Visuals
  1738. self.shapes = self.canvas.new_shape_collection(layers=1)
  1739. self.tool_shape = self.canvas.new_shape_collection(layers=1)
  1740. self.app.pool_recreated.connect(self.pool_recreated)
  1741. # Remove from scene
  1742. self.shapes.enabled = False
  1743. self.tool_shape.enabled = False
  1744. ## List of selected shapes.
  1745. self.selected = []
  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. # used in FCRegion and FCTrack. Will store the bending mode
  1755. self.bend_mode = 1
  1756. # signal that there is an action active like polygon or path
  1757. self.in_action = False
  1758. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1759. self.launched_from_shortcuts = False
  1760. def make_callback(thetool):
  1761. def f():
  1762. self.on_tool_select(thetool)
  1763. return f
  1764. for tool in self.tools_gerber:
  1765. self.tools_gerber[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1766. self.tools_gerber[tool]["button"].setCheckable(True) # Checkable
  1767. self.options = {
  1768. "global_gridx": 0.1,
  1769. "global_gridy": 0.1,
  1770. "snap_max": 0.05,
  1771. "grid_snap": True,
  1772. "corner_snap": False,
  1773. "grid_gap_link": True
  1774. }
  1775. self.app.options_read_form()
  1776. for option in self.options:
  1777. if option in self.app.options:
  1778. self.options[option] = self.app.options[option]
  1779. # flag to show if the object was modified
  1780. self.is_modified = False
  1781. self.edited_obj_name = ""
  1782. self.tool_row = 0
  1783. # A QTimer
  1784. self.plot_thread = None
  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. self.transform_tool = TransformEditorTool(self.app, self)
  1790. # Signals
  1791. self.buffer_button.clicked.connect(self.on_buffer)
  1792. self.scale_button.clicked.connect(self.on_scale)
  1793. self.app.ui.aperture_delete_btn.triggered.connect(self.on_delete_btn)
  1794. self.name_entry.returnPressed.connect(self.on_name_activate)
  1795. self.aptype_cb.currentIndexChanged[str].connect(self.on_aptype_changed)
  1796. self.addaperture_btn.clicked.connect(self.on_aperture_add)
  1797. self.apsize_entry.returnPressed.connect(self.on_aperture_add)
  1798. self.apdim_entry.returnPressed.connect(self.on_aperture_add)
  1799. self.delaperture_btn.clicked.connect(self.on_aperture_delete)
  1800. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1801. self.app.ui.grb_add_pad_menuitem.triggered.connect(self.on_pad_add)
  1802. self.app.ui.grb_add_pad_array_menuitem.triggered.connect(self.on_pad_add_array)
  1803. self.app.ui.grb_add_track_menuitem.triggered.connect(self.on_track_add)
  1804. self.app.ui.grb_add_region_menuitem.triggered.connect(self.on_region_add)
  1805. self.app.ui.grb_convert_poly_menuitem.triggered.connect(self.on_poligonize)
  1806. self.app.ui.grb_add_semidisc_menuitem.triggered.connect(self.on_add_semidisc)
  1807. self.app.ui.grb_add_disc_menuitem.triggered.connect(self.on_disc_add)
  1808. self.app.ui.grb_add_buffer_menuitem.triggered.connect(self.on_buffer)
  1809. self.app.ui.grb_add_scale_menuitem.triggered.connect(self.on_scale)
  1810. self.app.ui.grb_transform_menuitem.triggered.connect(self.transform_tool.run)
  1811. self.app.ui.grb_copy_menuitem.triggered.connect(self.on_copy_button)
  1812. self.app.ui.grb_delete_menuitem.triggered.connect(self.on_delete_btn)
  1813. self.app.ui.grb_move_menuitem.triggered.connect(self.on_move_button)
  1814. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1815. self.pad_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1816. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1817. self.editor_active = False
  1818. def pool_recreated(self, pool):
  1819. self.shapes.pool = pool
  1820. self.tool_shape.pool = pool
  1821. def set_ui(self):
  1822. # updated units
  1823. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1824. self.olddia_newdia.clear()
  1825. self.tool2tooldia.clear()
  1826. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1827. for key in self.storage_dict:
  1828. self.olddia_newdia[key] = key
  1829. sort_temp = []
  1830. for aperture in self.olddia_newdia:
  1831. sort_temp.append(int(aperture))
  1832. self.sorted_apid = sorted(sort_temp)
  1833. # populate self.intial_table_rows dict with the tool number as keys and aperture codes as values
  1834. for i in range(len(self.sorted_apid)):
  1835. tt_aperture = self.sorted_apid[i]
  1836. self.tool2tooldia[i + 1] = tt_aperture
  1837. if self.units == "IN":
  1838. self.apsize_entry.set_value(0.039)
  1839. else:
  1840. self.apsize_entry.set_value(1.00)
  1841. # Init GUI
  1842. self.pad_array_size_entry.set_value(5)
  1843. self.pad_pitch_entry.set_value(2.54)
  1844. self.pad_angle_entry.set_value(12)
  1845. self.pad_direction_radio.set_value('CW')
  1846. self.pad_axis_radio.set_value('X')
  1847. def build_ui(self, first_run=None):
  1848. try:
  1849. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1850. self.apertures_table.itemChanged.disconnect()
  1851. except:
  1852. pass
  1853. try:
  1854. self.apertures_table.cellPressed.disconnect()
  1855. except:
  1856. pass
  1857. # updated units
  1858. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1859. # make a new name for the new Excellon object (the one with edited content)
  1860. self.edited_obj_name = self.gerber_obj.options['name']
  1861. self.name_entry.set_value(self.edited_obj_name)
  1862. self.apertures_row = 0
  1863. aper_no = self.apertures_row + 1
  1864. sort = []
  1865. for k, v in list(self.storage_dict.items()):
  1866. sort.append(int(k))
  1867. sorted_apertures = sorted(sort)
  1868. # sort = []
  1869. # for k, v in list(self.gerber_obj.aperture_macros.items()):
  1870. # sort.append(k)
  1871. # sorted_macros = sorted(sort)
  1872. # n = len(sorted_apertures) + len(sorted_macros)
  1873. n = len(sorted_apertures)
  1874. self.apertures_table.setRowCount(n)
  1875. for ap_code in sorted_apertures:
  1876. ap_code = str(ap_code)
  1877. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1878. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1879. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1880. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1881. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1882. ap_type_item = QtWidgets.QTableWidgetItem(str(self.storage_dict[ap_code]['type']))
  1883. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1884. if str(self.storage_dict[ap_code]['type']) == 'R' or str(self.storage_dict[ap_code]['type']) == 'O':
  1885. ap_dim_item = QtWidgets.QTableWidgetItem(
  1886. '%.4f, %.4f' % (self.storage_dict[ap_code]['width'],
  1887. self.storage_dict[ap_code]['height']
  1888. )
  1889. )
  1890. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1891. elif str(self.storage_dict[ap_code]['type']) == 'P':
  1892. ap_dim_item = QtWidgets.QTableWidgetItem(
  1893. '%.4f, %.4f' % (self.storage_dict[ap_code]['diam'],
  1894. self.storage_dict[ap_code]['nVertices'])
  1895. )
  1896. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1897. else:
  1898. ap_dim_item = QtWidgets.QTableWidgetItem('')
  1899. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1900. try:
  1901. if self.storage_dict[ap_code]['size'] is not None:
  1902. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  1903. float(self.storage_dict[ap_code]['size']))
  1904. else:
  1905. ap_size_item = QtWidgets.QTableWidgetItem('')
  1906. except KeyError:
  1907. ap_size_item = QtWidgets.QTableWidgetItem('')
  1908. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1909. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1910. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1911. self.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  1912. self.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  1913. self.apertures_row += 1
  1914. if first_run is True:
  1915. # set now the last aperture selected
  1916. self.last_aperture_selected = ap_code
  1917. # for ap_code in sorted_macros:
  1918. # ap_code = str(ap_code)
  1919. #
  1920. # ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1921. # ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1922. # self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1923. #
  1924. # ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1925. #
  1926. # ap_type_item = QtWidgets.QTableWidgetItem('AM')
  1927. # ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1928. #
  1929. # self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1930. # self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1931. #
  1932. # self.apertures_row += 1
  1933. # if first_run is True:
  1934. # # set now the last aperture selected
  1935. # self.last_aperture_selected = ap_code
  1936. self.apertures_table.selectColumn(0)
  1937. self.apertures_table.resizeColumnsToContents()
  1938. self.apertures_table.resizeRowsToContents()
  1939. vertical_header = self.apertures_table.verticalHeader()
  1940. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1941. vertical_header.hide()
  1942. self.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1943. horizontal_header = self.apertures_table.horizontalHeader()
  1944. horizontal_header.setMinimumSectionSize(10)
  1945. horizontal_header.setDefaultSectionSize(70)
  1946. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1947. horizontal_header.resizeSection(0, 20)
  1948. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  1949. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1950. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1951. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  1952. self.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1953. self.apertures_table.setSortingEnabled(False)
  1954. self.apertures_table.setMinimumHeight(self.apertures_table.getHeight())
  1955. self.apertures_table.setMaximumHeight(self.apertures_table.getHeight())
  1956. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1957. self.apertures_table.clearSelection()
  1958. # Remove anything else in the GUI Selected Tab
  1959. self.app.ui.selected_scroll_area.takeWidget()
  1960. # Put ourself in the GUI Selected Tab
  1961. self.app.ui.selected_scroll_area.setWidget(self.grb_edit_widget)
  1962. # Switch notebook to Selected page
  1963. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1964. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1965. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1966. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1967. # for convenience set the next aperture code in the apcode field
  1968. try:
  1969. self.apcode_entry.set_value(max(self.tool2tooldia.values()) + 1)
  1970. except ValueError:
  1971. # this means that the edited object has no apertures so we start with 10 (Gerber specifications)
  1972. self.apcode_entry.set_value(10)
  1973. def on_aperture_add(self, apid=None):
  1974. self.is_modified = True
  1975. if apid:
  1976. ap_id = apid
  1977. else:
  1978. try:
  1979. ap_id = str(self.apcode_entry.get_value())
  1980. except ValueError:
  1981. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1982. "Add it and retry."))
  1983. return
  1984. if ap_id == '':
  1985. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1986. "Add it and retry."))
  1987. return
  1988. if ap_id == '0':
  1989. if ap_id not in self.tool2tooldia:
  1990. self.storage_dict[ap_id] = {}
  1991. self.storage_dict[ap_id]['type'] = 'REG'
  1992. size_val = 0
  1993. self.apsize_entry.set_value(size_val)
  1994. self.storage_dict[ap_id]['size'] = size_val
  1995. self.storage_dict[ap_id]['solid_geometry'] = []
  1996. self.storage_dict[ap_id]['follow_geometry'] = []
  1997. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1998. # each time a aperture code is edited or added
  1999. self.olddia_newdia[ap_id] = ap_id
  2000. else:
  2001. if ap_id not in self.olddia_newdia:
  2002. self.storage_dict[ap_id] = {}
  2003. type_val = self.aptype_cb.currentText()
  2004. self.storage_dict[ap_id]['type'] = type_val
  2005. if type_val == 'R' or type_val == 'O':
  2006. try:
  2007. dims = self.apdim_entry.get_value()
  2008. self.storage_dict[ap_id]['width'] = dims[0]
  2009. self.storage_dict[ap_id]['height'] = dims[1]
  2010. size_val = math.sqrt((dims[0] ** 2) + (dims[1] ** 2))
  2011. self.apsize_entry.set_value(size_val)
  2012. except Exception as e:
  2013. log.error("FlatCAMGrbEditor.on_aperture_add() --> the R or O aperture dims has to be in a "
  2014. "tuple format (x,y)\nError: %s" % str(e))
  2015. self.app.inform.emit(_("[WARNING_NOTCL] Aperture dimensions value is missing or wrong format. "
  2016. "Add it in format (width, height) and retry."))
  2017. return
  2018. else:
  2019. try:
  2020. size_val = float(self.apsize_entry.get_value())
  2021. except ValueError:
  2022. # try to convert comma to decimal point. if it's still not working error message and return
  2023. try:
  2024. size_val = float(self.apsize_entry.get_value().replace(',', '.'))
  2025. self.apsize_entry.set_value(size_val)
  2026. except ValueError:
  2027. self.app.inform.emit(_("[WARNING_NOTCL] Aperture size value is missing or wrong format. "
  2028. "Add it and retry."))
  2029. return
  2030. self.storage_dict[ap_id]['size'] = size_val
  2031. self.storage_dict[ap_id]['solid_geometry'] = []
  2032. self.storage_dict[ap_id]['follow_geometry'] = []
  2033. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  2034. # each time a aperture code is edited or added
  2035. self.olddia_newdia[ap_id] = ap_id
  2036. else:
  2037. self.app.inform.emit(_("[WARNING_NOTCL] Aperture already in the aperture table."))
  2038. return
  2039. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  2040. # we add a new entry in the tool2tooldia dict
  2041. self.tool2tooldia[len(self.olddia_newdia)] = int(ap_id)
  2042. self.app.inform.emit(_("[success] Added new aperture with code: {apid}").format(apid=str(ap_id)))
  2043. self.build_ui()
  2044. self.last_aperture_selected = ap_id
  2045. # make a quick sort through the tool2tooldia dict so we find which row to select
  2046. row_to_be_selected = None
  2047. for key in sorted(self.tool2tooldia):
  2048. if self.tool2tooldia[key] == int(ap_id):
  2049. row_to_be_selected = int(key) - 1
  2050. break
  2051. self.apertures_table.selectRow(row_to_be_selected)
  2052. def on_aperture_delete(self, apid=None):
  2053. self.is_modified = True
  2054. deleted_apcode_list = []
  2055. deleted_tool_offset_list = []
  2056. try:
  2057. if apid:
  2058. if isinstance(apid, list):
  2059. for dd in apid:
  2060. deleted_apcode_list.append(dd)
  2061. else:
  2062. deleted_apcode_list.append(apid)
  2063. else:
  2064. # deleted_tool_dia = float(self.apertures_table.item(self.apertures_table.currentRow(), 1).text())
  2065. if len(self.apertures_table.selectionModel().selectedRows()) == 0:
  2066. self.app.inform.emit(_("[WARNING_NOTCL] Select an aperture in Aperture Table"))
  2067. return
  2068. for index in self.apertures_table.selectionModel().selectedRows():
  2069. row = index.row()
  2070. deleted_apcode_list.append(self.apertures_table.item(row, 1).text())
  2071. except:
  2072. self.app.inform.emit(_("[WARNING_NOTCL] Select an aperture in Aperture Table"))
  2073. return
  2074. if deleted_apcode_list:
  2075. for deleted_aperture in deleted_apcode_list:
  2076. # delete the storage used for that tool
  2077. self.storage_dict.pop(deleted_aperture, None)
  2078. # I've added this flag_del variable because dictionary don't like
  2079. # having keys deleted while iterating through them
  2080. flag_del = []
  2081. for deleted_tool in self.tool2tooldia:
  2082. if self.tool2tooldia[deleted_tool] == deleted_aperture:
  2083. flag_del.append(deleted_tool)
  2084. if flag_del:
  2085. for aperture_to_be_deleted in flag_del:
  2086. # delete the tool
  2087. self.tool2tooldia.pop(aperture_to_be_deleted, None)
  2088. flag_del = []
  2089. self.olddia_newdia.pop(deleted_aperture, None)
  2090. self.app.inform.emit(_("[success] Deleted aperture with code: {del_dia}").format(
  2091. del_dia=str(deleted_aperture)))
  2092. self.plot_all()
  2093. self.build_ui()
  2094. # if last aperture selected was in the apertures deleted than make sure to select a 'new' last aperture selected
  2095. # because there are tools who depend on it.
  2096. # if there is no aperture left, then add a default one :)
  2097. if self.last_aperture_selected in deleted_apcode_list:
  2098. if self.apertures_table.rowCount() == 0:
  2099. self.on_aperture_add('10')
  2100. else:
  2101. self.last_aperture_selected = self.apertures_table.item(0, 1).text()
  2102. def on_tool_edit(self, item_changed):
  2103. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2104. self.apertures_table.itemChanged.disconnect()
  2105. # self.apertures_table.cellPressed.disconnect()
  2106. self.is_modified = True
  2107. geometry = []
  2108. current_table_dia_edited = None
  2109. if self.apertures_table.currentItem() is not None:
  2110. try:
  2111. current_table_dia_edited = float(self.apertures_table.currentItem().text())
  2112. except ValueError as e:
  2113. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  2114. self.apertures_table.setCurrentItem(None)
  2115. return
  2116. row_of_item_changed = self.apertures_table.currentRow()
  2117. # rows start with 0, tools start with 1 so we adjust the value by 1
  2118. key_in_tool2tooldia = row_of_item_changed + 1
  2119. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  2120. # aperture code is not used so we create a new tool with the desired diameter
  2121. if current_table_dia_edited not in self.olddia_newdia.values():
  2122. # update the dict that holds as keys our initial diameters and as values the edited diameters
  2123. self.olddia_newdia[dia_changed] = current_table_dia_edited
  2124. # update the dict that holds tool_no as key and tool_dia as value
  2125. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  2126. # update the tool offset
  2127. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  2128. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  2129. self.plot_all()
  2130. else:
  2131. # aperture code is already in use so we move the pads from the prior tool to the new tool
  2132. factor = current_table_dia_edited / dia_changed
  2133. for shape in self.storage_dict[dia_changed].get_objects():
  2134. geometry.append(DrawToolShape(
  2135. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  2136. self.points_edit[current_table_dia_edited].append((0, 0))
  2137. self.add_gerber_shape(geometry, self.storage_dict[current_table_dia_edited])
  2138. self.on_aperture_delete(apid=dia_changed)
  2139. # delete the tool offset
  2140. self.gerber_obj.tool_offset.pop(dia_changed, None)
  2141. # we reactivate the signals after the after the tool editing
  2142. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  2143. # self.apertures_table.cellPressed.connect(self.on_row_selected)
  2144. def on_name_activate(self):
  2145. self.edited_obj_name = self.name_entry.get_value()
  2146. def on_aptype_changed(self, current_text):
  2147. # 'O' is letter O not zero.
  2148. if current_text == 'R' or current_text == 'O':
  2149. self.apdim_lbl.show()
  2150. self.apdim_entry.show()
  2151. self.apsize_entry.setDisabled(True)
  2152. else:
  2153. self.apdim_lbl.hide()
  2154. self.apdim_entry.hide()
  2155. self.apsize_entry.setDisabled(False)
  2156. def activate_grb_editor(self):
  2157. # adjust the status of the menu entries related to the editor
  2158. self.app.ui.menueditedit.setDisabled(True)
  2159. self.app.ui.menueditok.setDisabled(False)
  2160. # adjust the visibility of some of the canvas context menu
  2161. self.app.ui.popmenu_edit.setVisible(False)
  2162. self.app.ui.popmenu_save.setVisible(True)
  2163. self.connect_canvas_event_handlers()
  2164. # init working objects
  2165. self.storage_dict = {}
  2166. self.current_storage = []
  2167. self.sorted_apid = []
  2168. self.new_apertures = {}
  2169. self.new_aperture_macros = {}
  2170. self.grb_plot_promises = []
  2171. self.olddia_newdia = {}
  2172. self.tool2tooldia = {}
  2173. self.shapes.enabled = True
  2174. self.tool_shape.enabled = True
  2175. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2176. self.app.ui.corner_snap_btn.setEnabled(True)
  2177. self.app.ui.snap_magnet.setVisible(True)
  2178. self.app.ui.corner_snap_btn.setVisible(True)
  2179. self.app.ui.grb_editor_menu.setDisabled(False)
  2180. self.app.ui.grb_editor_menu.menuAction().setVisible(True)
  2181. self.app.ui.update_obj_btn.setEnabled(True)
  2182. self.app.ui.grb_editor_cmenu.setEnabled(True)
  2183. self.app.ui.grb_edit_toolbar.setDisabled(False)
  2184. self.app.ui.grb_edit_toolbar.setVisible(True)
  2185. # self.app.ui.snap_toolbar.setDisabled(False)
  2186. # start with GRID toolbar activated
  2187. if self.app.ui.grid_snap_btn.isChecked() is False:
  2188. self.app.ui.grid_snap_btn.trigger()
  2189. # adjust the visibility of some of the canvas context menu
  2190. self.app.ui.popmenu_edit.setVisible(False)
  2191. self.app.ui.popmenu_save.setVisible(True)
  2192. self.app.ui.popmenu_disable.setVisible(False)
  2193. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2194. self.app.ui.popmenu_properties.setVisible(False)
  2195. self.app.ui.grb_editor_cmenu.menuAction().setVisible(True)
  2196. # Tell the App that the editor is active
  2197. self.editor_active = True
  2198. def deactivate_grb_editor(self):
  2199. try:
  2200. QtGui.QGuiApplication.restoreOverrideCursor()
  2201. except:
  2202. pass
  2203. # adjust the status of the menu entries related to the editor
  2204. self.app.ui.menueditedit.setDisabled(False)
  2205. self.app.ui.menueditok.setDisabled(True)
  2206. # adjust the visibility of some of the canvas context menu
  2207. self.app.ui.popmenu_edit.setVisible(True)
  2208. self.app.ui.popmenu_save.setVisible(False)
  2209. self.disconnect_canvas_event_handlers()
  2210. self.clear()
  2211. self.app.ui.grb_edit_toolbar.setDisabled(True)
  2212. settings = QSettings("Open Source", "FlatCAM")
  2213. if settings.contains("layout"):
  2214. layout = settings.value('layout', type=str)
  2215. if layout == 'standard':
  2216. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2217. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2218. self.app.ui.corner_snap_btn.setEnabled(False)
  2219. self.app.ui.snap_magnet.setVisible(False)
  2220. self.app.ui.corner_snap_btn.setVisible(False)
  2221. elif layout == 'compact':
  2222. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2223. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2224. self.app.ui.corner_snap_btn.setEnabled(False)
  2225. self.app.ui.snap_magnet.setVisible(True)
  2226. self.app.ui.corner_snap_btn.setVisible(True)
  2227. else:
  2228. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2229. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2230. self.app.ui.corner_snap_btn.setEnabled(False)
  2231. self.app.ui.snap_magnet.setVisible(False)
  2232. self.app.ui.corner_snap_btn.setVisible(False)
  2233. # set the Editor Toolbar visibility to what was before entering in the Editor
  2234. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2235. else self.app.ui.grb_edit_toolbar.setVisible(True)
  2236. # Disable visuals
  2237. self.shapes.enabled = False
  2238. self.tool_shape.enabled = False
  2239. # self.app.app_cursor.enabled = False
  2240. # Tell the app that the editor is no longer active
  2241. self.editor_active = False
  2242. self.app.ui.grb_editor_menu.setDisabled(True)
  2243. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  2244. self.app.ui.update_obj_btn.setEnabled(False)
  2245. # adjust the visibility of some of the canvas context menu
  2246. self.app.ui.popmenu_edit.setVisible(True)
  2247. self.app.ui.popmenu_save.setVisible(False)
  2248. self.app.ui.popmenu_disable.setVisible(True)
  2249. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2250. self.app.ui.popmenu_properties.setVisible(True)
  2251. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2252. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2253. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2254. # Show original geometry
  2255. if self.gerber_obj:
  2256. self.gerber_obj.visible = True
  2257. def connect_canvas_event_handlers(self):
  2258. ## Canvas events
  2259. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2260. # but those from FlatCAMGeoEditor
  2261. # first connect to new, then disconnect the old handlers
  2262. # don't ask why but if there is nothing connected I've seen issues
  2263. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2264. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2265. self.canvas.vis_connect('mouse_release', self.on_grb_click_release)
  2266. self.canvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2267. self.canvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2268. self.canvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2269. self.canvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2270. self.app.collection.view.clicked.disconnect()
  2271. self.app.ui.popmenu_copy.triggered.disconnect()
  2272. self.app.ui.popmenu_delete.triggered.disconnect()
  2273. self.app.ui.popmenu_move.triggered.disconnect()
  2274. self.app.ui.popmenu_copy.triggered.connect(self.on_copy_button)
  2275. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2276. self.app.ui.popmenu_move.triggered.connect(self.on_move_button)
  2277. # Gerber Editor
  2278. self.app.ui.grb_draw_pad.triggered.connect(self.on_pad_add)
  2279. self.app.ui.grb_draw_pad_array.triggered.connect(self.on_pad_add_array)
  2280. self.app.ui.grb_draw_track.triggered.connect(self.on_track_add)
  2281. self.app.ui.grb_draw_region.triggered.connect(self.on_region_add)
  2282. def disconnect_canvas_event_handlers(self):
  2283. # we restore the key and mouse control to FlatCAMApp method
  2284. # first connect to new, then disconnect the old handlers
  2285. # don't ask why but if there is nothing connected I've seen issues
  2286. self.canvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2287. self.canvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2288. self.canvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2289. self.canvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2290. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2291. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2292. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2293. self.canvas.vis_disconnect('mouse_release', self.on_grb_click_release)
  2294. try:
  2295. self.app.ui.popmenu_copy.triggered.disconnect(self.on_copy_button)
  2296. except TypeError:
  2297. pass
  2298. try:
  2299. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2300. except TypeError:
  2301. pass
  2302. try:
  2303. self.app.ui.popmenu_move.triggered.disconnect(self.on_move_button)
  2304. except TypeError:
  2305. pass
  2306. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2307. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2308. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2309. # Gerber Editor
  2310. try:
  2311. self.app.ui.grb_draw_pad.triggered.disconnect(self.on_pad_add)
  2312. except TypeError:
  2313. pass
  2314. try:
  2315. self.app.ui.grb_draw_pad_array.triggered.disconnect(self.on_pad_add_array)
  2316. except TypeError:
  2317. pass
  2318. try:
  2319. self.app.ui.grb_draw_track.triggered.disconnect(self.on_track_add)
  2320. except TypeError:
  2321. pass
  2322. try:
  2323. self.app.ui.grb_draw_region.triggered.disconnect(self.on_region_add)
  2324. except TypeError:
  2325. pass
  2326. def clear(self):
  2327. self.active_tool = None
  2328. # self.shape_buffer = []
  2329. self.selected = []
  2330. self.shapes.clear(update=True)
  2331. self.tool_shape.clear(update=True)
  2332. def flatten(self, geometry=None, reset=True, pathonly=False):
  2333. """
  2334. Creates a list of non-iterable linear geometry objects.
  2335. Polygons are expanded into its exterior pathonly param if specified.
  2336. Results are placed in flat_geometry
  2337. :param geometry: Shapely type or list or list of list of such.
  2338. :param reset: Clears the contents of self.flat_geometry.
  2339. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  2340. """
  2341. if reset:
  2342. self.flat_geometry = []
  2343. ## If iterable, expand recursively.
  2344. try:
  2345. for geo in geometry:
  2346. if geo is not None:
  2347. self.flatten(geometry=geo, reset=False, pathonly=pathonly)
  2348. ## Not iterable, do the actual indexing and add.
  2349. except TypeError:
  2350. if pathonly and type(geometry) == Polygon:
  2351. self.flat_geometry.append(geometry.exterior)
  2352. self.flatten(geometry=geometry.interiors,
  2353. reset=False,
  2354. pathonly=True)
  2355. else:
  2356. self.flat_geometry.append(geometry)
  2357. return self.flat_geometry
  2358. def edit_fcgerber(self, orig_grb_obj):
  2359. """
  2360. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  2361. into the editor.
  2362. :param fcgeometry: FlatCAMExcellon
  2363. :return: None
  2364. """
  2365. self.deactivate_grb_editor()
  2366. self.activate_grb_editor()
  2367. # create a reference to the source object
  2368. self.gerber_obj = orig_grb_obj
  2369. self.gerber_obj_options = orig_grb_obj.options
  2370. # Hide original geometry
  2371. orig_grb_obj.visible = False
  2372. # Set selection tolerance
  2373. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2374. self.select_tool("select")
  2375. # we activate this after the initial build as we don't need to see the tool been populated
  2376. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  2377. # and then add it to the storage elements (each storage elements is a member of a list
  2378. def job_thread(self, apid):
  2379. with self.app.proc_container.new(_("Adding aperture: %s geo ...") % str(apid)):
  2380. solid_storage_elem = []
  2381. follow_storage_elem = []
  2382. self.storage_dict[apid] = {}
  2383. # add the Gerber geometry to editor storage
  2384. for k, v in self.gerber_obj.apertures[apid].items():
  2385. try:
  2386. if k == 'solid_geometry':
  2387. for geo in v:
  2388. if geo:
  2389. self.add_gerber_shape(DrawToolShape(geo), solid_storage_elem)
  2390. self.storage_dict[apid][k] = solid_storage_elem
  2391. elif k == 'follow_geometry':
  2392. for geo in v:
  2393. if geo is not None:
  2394. self.add_gerber_shape(DrawToolShape(geo), follow_storage_elem)
  2395. self.storage_dict[apid][k] = follow_storage_elem
  2396. elif k == 'clear_geometry':
  2397. continue
  2398. else:
  2399. self.storage_dict[apid][k] = v
  2400. except Exception as e:
  2401. log.debug("FlatCAMGrbEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  2402. # Check promises and clear if exists
  2403. while True:
  2404. try:
  2405. self.grb_plot_promises.remove(apid)
  2406. time.sleep(0.5)
  2407. except ValueError:
  2408. break
  2409. for apid in self.gerber_obj.apertures:
  2410. self.grb_plot_promises.append(apid)
  2411. self.app.worker_task.emit({'fcn': job_thread, 'params': [self, apid]})
  2412. # do the delayed plot only if there is something to plot (the gerber is not empty)
  2413. if bool(self.gerber_obj.apertures):
  2414. self.start_delayed_plot(check_period=1000)
  2415. else:
  2416. self.set_ui()
  2417. # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  2418. self.build_ui(first_run=True)
  2419. # and add the first aperture to have something to play with
  2420. self.on_aperture_add('10')
  2421. def update_fcgerber(self, grb_obj):
  2422. """
  2423. Create a new Gerber object that contain the edited content of the source Gerber object
  2424. :param grb_obj: FlatCAMGerber
  2425. :return: None
  2426. """
  2427. new_grb_name = self.edited_obj_name
  2428. # if the 'delayed plot' malfunctioned stop the QTimer
  2429. try:
  2430. self.plot_thread.stop()
  2431. except:
  2432. pass
  2433. if "_edit" in self.edited_obj_name:
  2434. try:
  2435. id = int(self.edited_obj_name[-1]) + 1
  2436. new_grb_name= self.edited_obj_name[:-1] + str(id)
  2437. except ValueError:
  2438. new_grb_name += "_1"
  2439. else:
  2440. new_grb_name = self.edited_obj_name + "_edit"
  2441. self.app.worker_task.emit({'fcn': self.new_edited_gerber,
  2442. 'params': [new_grb_name]})
  2443. # reset the tool table
  2444. self.apertures_table.clear()
  2445. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  2446. self.last_aperture_selected = None
  2447. # restore GUI to the Selected TAB
  2448. # Remove anything else in the GUI
  2449. self.app.ui.selected_scroll_area.takeWidget()
  2450. # Switch notebook to Selected page
  2451. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2452. def update_options(self, obj):
  2453. try:
  2454. if not obj.options:
  2455. obj.options = {}
  2456. obj.options['xmin'] = 0
  2457. obj.options['ymin'] = 0
  2458. obj.options['xmax'] = 0
  2459. obj.options['ymax'] = 0
  2460. return True
  2461. else:
  2462. return False
  2463. except AttributeError:
  2464. obj.options = {}
  2465. return True
  2466. def new_edited_gerber(self, outname):
  2467. """
  2468. Creates a new Gerber object for the edited Gerber. Thread-safe.
  2469. :param outname: Name of the resulting object. None causes the name to be that of the file.
  2470. :type outname: str
  2471. :return: None
  2472. """
  2473. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  2474. self.gerber_obj.options['name'].upper())
  2475. out_name = outname
  2476. local_storage_dict = deepcopy(self.storage_dict)
  2477. # How the object should be initialized
  2478. def obj_init(grb_obj, app_obj):
  2479. poly_buffer = []
  2480. follow_buffer = []
  2481. for storage_apid, storage_val in local_storage_dict.items():
  2482. grb_obj.apertures[storage_apid] = {}
  2483. for k, v in storage_val.items():
  2484. if k == 'solid_geometry':
  2485. grb_obj.apertures[storage_apid][k] = []
  2486. for geo in v:
  2487. new_geo = deepcopy(geo.geo)
  2488. grb_obj.apertures[storage_apid][k].append(new_geo)
  2489. poly_buffer.append(new_geo)
  2490. elif k == 'follow_geometry':
  2491. grb_obj.apertures[storage_apid][k] = []
  2492. for geo in v:
  2493. new_geo = deepcopy(geo.geo)
  2494. grb_obj.apertures[storage_apid][k].append(new_geo)
  2495. follow_buffer.append(new_geo)
  2496. else:
  2497. grb_obj.apertures[storage_apid][k] = deepcopy(v)
  2498. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  2499. new_poly = MultiPolygon(poly_buffer)
  2500. new_poly = new_poly.buffer(0.00000001)
  2501. new_poly = new_poly.buffer(-0.00000001)
  2502. grb_obj.solid_geometry = new_poly
  2503. grb_obj.follow_geometry = deepcopy(follow_buffer)
  2504. for k, v in self.gerber_obj_options.items():
  2505. if k == 'name':
  2506. grb_obj.options[k] = out_name
  2507. else:
  2508. grb_obj.options[k] = deepcopy(v)
  2509. grb_obj.source_file = []
  2510. grb_obj.multigeo = False
  2511. grb_obj.follow = False
  2512. try:
  2513. grb_obj.create_geometry()
  2514. except KeyError:
  2515. self.app.inform.emit(
  2516. _( "[ERROR_NOTCL] There are no Aperture definitions in the file. Aborting Gerber creation.")
  2517. )
  2518. except:
  2519. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2520. msg += traceback.format_exc()
  2521. app_obj.inform.emit(msg)
  2522. raise
  2523. # raise
  2524. with self.app.proc_container.new(_("Creating Gerber.")):
  2525. try:
  2526. self.app.new_object("gerber", outname, obj_init)
  2527. except Exception as e:
  2528. log.error("Error on object creation: %s" % str(e))
  2529. self.app.progress.emit(100)
  2530. return
  2531. self.app.inform.emit(_("[success] Gerber editing finished."))
  2532. # self.progress.emit(100)
  2533. def on_tool_select(self, tool):
  2534. """
  2535. Behavior of the toolbar. Tool initialization.
  2536. :rtype : None
  2537. """
  2538. current_tool = tool
  2539. self.app.log.debug("on_tool_select('%s')" % tool)
  2540. if self.last_aperture_selected is None and current_tool is not 'select':
  2541. # self.draw_app.select_tool('select')
  2542. self.complete = True
  2543. current_tool = 'select'
  2544. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No aperture is selected"))
  2545. # This is to make the group behave as radio group
  2546. if current_tool in self.tools_gerber:
  2547. if self.tools_gerber[current_tool]["button"].isChecked():
  2548. self.app.log.debug("%s is checked." % current_tool)
  2549. for t in self.tools_gerber:
  2550. if t != current_tool:
  2551. self.tools_gerber[t]["button"].setChecked(False)
  2552. # this is where the Editor toolbar classes (button's) are instantiated
  2553. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  2554. # self.app.inform.emit(self.active_tool.start_msg)
  2555. else:
  2556. self.app.log.debug("%s is NOT checked." % current_tool)
  2557. for t in self.tools_gerber:
  2558. self.tools_gerber[t]["button"].setChecked(False)
  2559. self.select_tool('select')
  2560. self.active_tool = FCApertureSelect(self)
  2561. def on_row_selected(self, row, col):
  2562. if col == 0:
  2563. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2564. if self.app.defaults["global_mselect_key"] == 'Control':
  2565. modifier_to_use = Qt.ControlModifier
  2566. else:
  2567. modifier_to_use = Qt.ShiftModifier
  2568. if key_modifier == modifier_to_use:
  2569. pass
  2570. else:
  2571. self.selected = []
  2572. try:
  2573. # selected_apid = str(self.tool2tooldia[row + 1])
  2574. selected_apid = self.apertures_table.item(row, 1).text()
  2575. self.last_aperture_selected = copy(selected_apid)
  2576. for obj in self.storage_dict[selected_apid]['solid_geometry']:
  2577. self.selected.append(obj)
  2578. except Exception as e:
  2579. self.app.log.debug(str(e))
  2580. self.plot_all()
  2581. def toolbar_tool_toggle(self, key):
  2582. self.options[key] = self.sender().isChecked()
  2583. return self.options[key]
  2584. def on_grb_shape_complete(self, storage=None, specific_shape=None):
  2585. self.app.log.debug("on_shape_complete()")
  2586. if specific_shape:
  2587. geo = specific_shape
  2588. else:
  2589. geo = self.active_tool.geometry
  2590. if geo is None:
  2591. return
  2592. if storage is not None:
  2593. # Add shape
  2594. self.add_gerber_shape(geo, storage)
  2595. else:
  2596. stora = self.storage_dict[self.last_aperture_selected]['solid_geometry']
  2597. self.add_gerber_shape(geo, storage=stora)
  2598. # Remove any utility shapes
  2599. self.delete_utility_geometry()
  2600. self.tool_shape.clear(update=True)
  2601. # Replot and reset tool.
  2602. self.plot_all()
  2603. def add_gerber_shape(self, shape, storage):
  2604. """
  2605. Adds a shape to the shape storage.
  2606. :param shape: Shape to be added.
  2607. :type shape: DrawToolShape
  2608. :return: None
  2609. """
  2610. # List of DrawToolShape?
  2611. if isinstance(shape, list):
  2612. for subshape in shape:
  2613. self.add_gerber_shape(subshape, storage)
  2614. return
  2615. assert isinstance(shape, DrawToolShape), \
  2616. "Expected a DrawToolShape, got %s" % str(type(shape))
  2617. assert shape.geo is not None, \
  2618. "Shape object has empty geometry (None)"
  2619. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2620. not isinstance(shape.geo, list), \
  2621. "Shape objects has empty geometry ([])"
  2622. if isinstance(shape, DrawToolUtilityShape):
  2623. self.utility.append(shape)
  2624. else:
  2625. storage.append(shape) # TODO: Check performance
  2626. def on_canvas_click(self, event):
  2627. """
  2628. event.x and .y have canvas coordinates
  2629. event.xdata and .ydata have plot coordinates
  2630. :param event: Event object dispatched by VisPy
  2631. :return: None
  2632. """
  2633. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2634. if self.app.grid_status():
  2635. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2636. self.app.app_cursor.enabled = True
  2637. # Update cursor
  2638. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2639. size=20)
  2640. else:
  2641. self.pos = (self.pos[0], self.pos[1])
  2642. self.app.app_cursor.enabled = False
  2643. if event.button is 1:
  2644. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2645. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2646. # Selection with left mouse button
  2647. if self.active_tool is not None and event.button is 1:
  2648. # Dispatch event to active_tool
  2649. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2650. # If it is a shape generating tool
  2651. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2652. if self.current_storage is not None:
  2653. self.on_grb_shape_complete(self.current_storage)
  2654. self.build_ui()
  2655. # MS: always return to the Select Tool if modifier key is not pressed
  2656. # else return to the current tool
  2657. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2658. if self.app.defaults["global_mselect_key"] == 'Control':
  2659. modifier_to_use = Qt.ControlModifier
  2660. else:
  2661. modifier_to_use = Qt.ShiftModifier
  2662. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2663. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2664. if key_modifier == modifier_to_use:
  2665. self.select_tool(self.active_tool.name)
  2666. else:
  2667. # return to Select tool but not for FCPad
  2668. if isinstance(self.active_tool, FCPad):
  2669. self.select_tool(self.active_tool.name)
  2670. else:
  2671. self.select_tool("select")
  2672. return
  2673. if isinstance(self.active_tool, FCApertureSelect):
  2674. # self.app.log.debug("Replotting after click.")
  2675. self.plot_all()
  2676. else:
  2677. self.app.log.debug("No active tool to respond to click!")
  2678. def on_grb_click_release(self, event):
  2679. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2680. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2681. if self.app.grid_status():
  2682. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2683. else:
  2684. pos = (pos_canvas[0], pos_canvas[1])
  2685. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2686. # canvas menu
  2687. try:
  2688. if event.button == 2: # right click
  2689. if self.app.ui.popMenu.mouse_is_panning is False:
  2690. if self.in_action is False:
  2691. try:
  2692. QtGui.QGuiApplication.restoreOverrideCursor()
  2693. except:
  2694. pass
  2695. if self.active_tool.complete is False and not isinstance(self.active_tool, FCApertureSelect):
  2696. self.active_tool.complete = True
  2697. self.in_action = False
  2698. self.delete_utility_geometry()
  2699. self.app.inform.emit(_("[success] Done."))
  2700. self.select_tool('select')
  2701. else:
  2702. self.app.cursor = QtGui.QCursor()
  2703. self.app.populate_cmenu_grids()
  2704. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2705. else:
  2706. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2707. # right mouse click will finish the action
  2708. if isinstance(self.active_tool, FCShapeTool):
  2709. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  2710. self.active_tool.make()
  2711. if self.active_tool.complete:
  2712. self.on_grb_shape_complete()
  2713. self.app.inform.emit(_("[success] Done."))
  2714. # MS: always return to the Select Tool if modifier key is not pressed
  2715. # else return to the current tool but not for FCTrack
  2716. if isinstance(self.active_tool, FCTrack):
  2717. self.select_tool(self.active_tool.name)
  2718. else:
  2719. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2720. if (self.app.defaults["global_mselect_key"] == 'Control' and
  2721. key_modifier == Qt.ControlModifier) or \
  2722. (self.app.defaults["global_mselect_key"] == 'Shift' and
  2723. key_modifier == Qt.ShiftModifier):
  2724. self.select_tool(self.active_tool.name)
  2725. else:
  2726. self.select_tool("select")
  2727. except Exception as e:
  2728. log.warning("Error: %s" % str(e))
  2729. raise
  2730. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2731. # selection and then select a type of selection ("enclosing" or "touching")
  2732. try:
  2733. if event.button == 1: # left click
  2734. if self.app.selection_type is not None:
  2735. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2736. self.app.selection_type = None
  2737. elif isinstance(self.active_tool, FCApertureSelect):
  2738. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2739. # if there are selected objects then plot them
  2740. if self.selected:
  2741. self.plot_all()
  2742. except Exception as e:
  2743. log.warning("Error: %s" % str(e))
  2744. raise
  2745. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2746. """
  2747. :param start_pos: mouse position when the selection LMB click was done
  2748. :param end_pos: mouse position when the left mouse button is released
  2749. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2750. :type Bool
  2751. :return:
  2752. """
  2753. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2754. sel_aperture = set()
  2755. self.apertures_table.clearSelection()
  2756. self.app.delete_selection_shape()
  2757. for storage in self.storage_dict:
  2758. try:
  2759. for obj in self.storage_dict[storage]['solid_geometry']:
  2760. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2761. (sel_type is False and poly_selection.intersects(obj.geo)):
  2762. if self.key == self.app.defaults["global_mselect_key"]:
  2763. if obj in self.selected:
  2764. self.selected.remove(obj)
  2765. else:
  2766. # add the object to the selected shapes
  2767. self.selected.append(obj)
  2768. sel_aperture.add(storage)
  2769. else:
  2770. self.selected.append(obj)
  2771. sel_aperture.add(storage)
  2772. except KeyError:
  2773. pass
  2774. try:
  2775. self.apertures_table.cellPressed.disconnect()
  2776. except:
  2777. pass
  2778. # select the aperture code of the selected geometry, in the tool table
  2779. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2780. for aper in sel_aperture:
  2781. for row in range(self.apertures_table.rowCount()):
  2782. if str(aper) == self.apertures_table.item(row, 1).text():
  2783. self.apertures_table.selectRow(row)
  2784. self.last_aperture_selected = aper
  2785. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2786. self.apertures_table.cellPressed.connect(self.on_row_selected)
  2787. self.plot_all()
  2788. def on_canvas_move(self, event):
  2789. """
  2790. Called on 'mouse_move' event
  2791. event.pos have canvas screen coordinates
  2792. :param event: Event object dispatched by VisPy SceneCavas
  2793. :return: None
  2794. """
  2795. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2796. event.xdata, event.ydata = pos_canvas[0], pos_canvas[1]
  2797. self.x = event.xdata
  2798. self.y = event.ydata
  2799. self.app.ui.popMenu.mouse_is_panning = False
  2800. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2801. if event.button == 2 and event.is_dragging == 1:
  2802. self.app.ui.popMenu.mouse_is_panning = True
  2803. return
  2804. try:
  2805. x = float(event.xdata)
  2806. y = float(event.ydata)
  2807. except TypeError:
  2808. return
  2809. if self.active_tool is None:
  2810. return
  2811. ### Snap coordinates
  2812. if self.app.grid_status():
  2813. x, y = self.app.geo_editor.snap(x, y)
  2814. self.app.app_cursor.enabled = True
  2815. # Update cursor
  2816. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2817. else:
  2818. self.app.app_cursor.enabled = False
  2819. self.snap_x = x
  2820. self.snap_y = y
  2821. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2822. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2823. "<b>Y</b>: %.4f" % (x, y))
  2824. if self.pos is None:
  2825. self.pos = (0, 0)
  2826. dx = x - self.pos[0]
  2827. dy = y - self.pos[1]
  2828. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2829. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2830. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2831. ### Utility geometry (animated)
  2832. geo = self.active_tool.utility_geometry(data=(x, y))
  2833. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2834. # Remove any previous utility shape
  2835. self.tool_shape.clear(update=True)
  2836. self.draw_utility_geometry(geo=geo)
  2837. ### Selection area on canvas section ###
  2838. if event.is_dragging == 1 and event.button == 1:
  2839. # I make an exception for FCRegion and FCTrack because clicking and dragging while making regions can
  2840. # create strange issues like missing a point in a track/region
  2841. if isinstance(self.active_tool, FCRegion) or isinstance(self.active_tool, FCTrack):
  2842. pass
  2843. else:
  2844. dx = pos_canvas[0] - self.pos[0]
  2845. self.app.delete_selection_shape()
  2846. if dx < 0:
  2847. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2848. color=self.app.defaults["global_alt_sel_line"],
  2849. face_color=self.app.defaults['global_alt_sel_fill'])
  2850. self.app.selection_type = False
  2851. else:
  2852. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2853. self.app.selection_type = True
  2854. else:
  2855. self.app.selection_type = None
  2856. def on_canvas_key_release(self, event):
  2857. self.key = None
  2858. def draw_utility_geometry(self, geo):
  2859. if type(geo.geo) == list:
  2860. for el in geo.geo:
  2861. # Add the new utility shape
  2862. self.tool_shape.add(
  2863. shape=el, color=(self.app.defaults["global_draw_color"] + '80'),
  2864. # face_color=self.app.defaults['global_alt_sel_fill'],
  2865. update=False, layer=0, tolerance=None)
  2866. else:
  2867. # Add the new utility shape
  2868. self.tool_shape.add(
  2869. shape=geo.geo,
  2870. color=(self.app.defaults["global_draw_color"] + '80'),
  2871. # face_color=self.app.defaults['global_alt_sel_fill'],
  2872. update=False, layer=0, tolerance=None)
  2873. self.tool_shape.redraw()
  2874. def plot_all(self):
  2875. """
  2876. Plots all shapes in the editor.
  2877. :return: None
  2878. :rtype: None
  2879. """
  2880. with self.app.proc_container.new("Plotting"):
  2881. # self.app.log.debug("plot_all()")
  2882. self.shapes.clear(update=True)
  2883. for storage in self.storage_dict:
  2884. try:
  2885. for shape in self.storage_dict[storage]['solid_geometry']:
  2886. if shape.geo is None:
  2887. continue
  2888. if shape in self.selected:
  2889. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'],
  2890. linewidth=2)
  2891. continue
  2892. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2893. except KeyError:
  2894. pass
  2895. for shape in self.utility:
  2896. self.plot_shape(geometry=shape.geo, linewidth=1)
  2897. continue
  2898. self.shapes.redraw()
  2899. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2900. """
  2901. Plots a geometric object or list of objects without rendering. Plotted objects
  2902. are returned as a list. This allows for efficient/animated rendering.
  2903. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2904. :param color: Shape color
  2905. :param linewidth: Width of lines in # of pixels.
  2906. :return: List of plotted elements.
  2907. """
  2908. # plot_elements = []
  2909. if geometry is None:
  2910. geometry = self.active_tool.geometry
  2911. try:
  2912. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0)
  2913. except AttributeError:
  2914. if type(geometry) == Point:
  2915. return
  2916. self.shapes.add(shape=geometry, color=color, face_color=color+'AF', layer=0)
  2917. def start_delayed_plot(self, check_period):
  2918. """
  2919. This function starts an QTImer and it will periodically check if all the workers finish the plotting functions
  2920. :param check_period: time at which to check periodically if all plots finished to be plotted
  2921. :return:
  2922. """
  2923. # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  2924. # self.plot_thread.start()
  2925. log.debug("FlatCAMGrbEditor --> Delayed Plot started.")
  2926. self.plot_thread = QtCore.QTimer()
  2927. self.plot_thread.setInterval(check_period)
  2928. self.plot_thread.timeout.connect(self.check_plot_finished)
  2929. self.plot_thread.start()
  2930. def check_plot_finished(self):
  2931. """
  2932. If all the promises made are finished then all the shapes are in shapes_storage and can be plotted safely and
  2933. then the UI is rebuilt accordingly.
  2934. :return:
  2935. """
  2936. try:
  2937. if not self.grb_plot_promises:
  2938. self.plot_thread.stop()
  2939. self.set_ui()
  2940. # now that we have data, create the GUI interface and add it to the Tool Tab
  2941. self.build_ui(first_run=True)
  2942. self.plot_all()
  2943. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  2944. # - perhaps is a bug in VisPy implementation
  2945. self.app.app_cursor.enabled = False
  2946. self.app.app_cursor.enabled = True
  2947. log.debug("FlatCAMGrbEditor --> delayed_plot finished")
  2948. except Exception:
  2949. traceback.print_exc()
  2950. def on_shape_complete(self):
  2951. self.app.log.debug("on_shape_complete()")
  2952. # Add shape
  2953. self.add_gerber_shape(self.active_tool.geometry)
  2954. # Remove any utility shapes
  2955. self.delete_utility_geometry()
  2956. self.tool_shape.clear(update=True)
  2957. # Replot and reset tool.
  2958. self.plot_all()
  2959. # self.active_tool = type(self.active_tool)(self)
  2960. def get_selected(self):
  2961. """
  2962. Returns list of shapes that are selected in the editor.
  2963. :return: List of shapes.
  2964. """
  2965. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2966. return self.selected
  2967. def delete_selected(self):
  2968. temp_ref = [s for s in self.selected]
  2969. if len(temp_ref) == 0:
  2970. self.app.inform.emit(_("[ERROR_NOTCL] Failed. No aperture geometry is selected."))
  2971. return
  2972. for shape_sel in temp_ref:
  2973. self.delete_shape(shape_sel)
  2974. self.selected = []
  2975. self.build_ui()
  2976. self.app.inform.emit(_("[success] Done. Apertures geometry deleted."))
  2977. def delete_shape(self, shape):
  2978. self.is_modified = True
  2979. if shape in self.utility:
  2980. self.utility.remove(shape)
  2981. return
  2982. for storage in self.storage_dict:
  2983. try:
  2984. if shape in self.storage_dict[storage]['solid_geometry']:
  2985. self.storage_dict[storage]['solid_geometry'].remove(shape)
  2986. except KeyError:
  2987. pass
  2988. if shape in self.selected:
  2989. self.selected.remove(shape) # TODO: Check performance
  2990. def delete_utility_geometry(self):
  2991. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2992. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2993. for_deletion = [shape for shape in self.utility]
  2994. for shape in for_deletion:
  2995. self.delete_shape(shape)
  2996. self.tool_shape.clear(update=True)
  2997. self.tool_shape.redraw()
  2998. def on_delete_btn(self):
  2999. self.delete_selected()
  3000. self.plot_all()
  3001. def select_tool(self, toolname):
  3002. """
  3003. Selects a drawing tool. Impacts the object and GUI.
  3004. :param toolname: Name of the tool.
  3005. :return: None
  3006. """
  3007. self.tools_gerber[toolname]["button"].setChecked(True)
  3008. self.on_tool_select(toolname)
  3009. def set_selected(self, shape):
  3010. # Remove and add to the end.
  3011. if shape in self.selected:
  3012. self.selected.remove(shape)
  3013. self.selected.append(shape)
  3014. def set_unselected(self, shape):
  3015. if shape in self.selected:
  3016. self.selected.remove(shape)
  3017. def on_array_type_combo(self):
  3018. if self.array_type_combo.currentIndex() == 0:
  3019. self.array_circular_frame.hide()
  3020. self.array_linear_frame.show()
  3021. else:
  3022. self.delete_utility_geometry()
  3023. self.array_circular_frame.show()
  3024. self.array_linear_frame.hide()
  3025. self.app.inform.emit(_("Click on the circular array Center position"))
  3026. def on_linear_angle_radio(self):
  3027. val = self.pad_axis_radio.get_value()
  3028. if val == 'A':
  3029. self.linear_angle_spinner.show()
  3030. self.linear_angle_label.show()
  3031. else:
  3032. self.linear_angle_spinner.hide()
  3033. self.linear_angle_label.hide()
  3034. def on_copy_button(self):
  3035. self.select_tool('copy')
  3036. return
  3037. def on_move_button(self):
  3038. self.select_tool('move')
  3039. return
  3040. def on_pad_add(self):
  3041. self.select_tool('pad')
  3042. def on_pad_add_array(self):
  3043. self.select_tool('array')
  3044. def on_track_add(self):
  3045. self.select_tool('track')
  3046. def on_region_add(self):
  3047. self.select_tool('region')
  3048. def on_poligonize(self):
  3049. self.select_tool('poligonize')
  3050. def on_disc_add(self):
  3051. self.select_tool('disc')
  3052. def on_add_semidisc(self):
  3053. self.select_tool('semidisc')
  3054. def on_buffer(self):
  3055. buff_value = 0.01
  3056. log.debug("FlatCAMGrbEditor.on_buffer()")
  3057. try:
  3058. buff_value = float(self.buffer_distance_entry.get_value())
  3059. except ValueError:
  3060. # try to convert comma to decimal point. if it's still not working error message and return
  3061. try:
  3062. buff_value = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  3063. self.buffer_distance_entry.set_value(buff_value)
  3064. except ValueError:
  3065. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  3066. "Add it and retry."))
  3067. return
  3068. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  3069. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  3070. join_style = self.buffer_corner_cb.currentIndex() + 1
  3071. def buffer_recursion(geom, selection):
  3072. if type(geom) == list or type(geom) is MultiPolygon:
  3073. geoms = list()
  3074. for local_geom in geom:
  3075. geoms.append(buffer_recursion(local_geom, selection=selection))
  3076. return geoms
  3077. else:
  3078. if geom in selection:
  3079. return DrawToolShape(geom.geo.buffer(buff_value, join_style=join_style))
  3080. else:
  3081. return geom
  3082. if not self.apertures_table.selectedItems():
  3083. self.app.inform.emit(_(
  3084. "[WARNING_NOTCL] No aperture to buffer. Select at least one aperture and try again."
  3085. ))
  3086. return
  3087. for x in self.apertures_table.selectedItems():
  3088. try:
  3089. apid = self.apertures_table.item(x.row(), 1).text()
  3090. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3091. self.storage_dict[apid]['solid_geometry'] = []
  3092. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3093. except Exception as e:
  3094. log.debug("FlatCAMGrbEditor.buffer() --> %s" % str(e))
  3095. self.plot_all()
  3096. self.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  3097. def on_scale(self):
  3098. scale_factor = 1.0
  3099. log.debug("FlatCAMGrbEditor.on_scale()")
  3100. try:
  3101. scale_factor = float(self.scale_factor_entry.get_value())
  3102. except ValueError:
  3103. # try to convert comma to decimal point. if it's still not working error message and return
  3104. try:
  3105. scale_factor = float(self.scale_factor_entry.get_value().replace(',', '.'))
  3106. self.scale_factor_entry.set_value(scale_factor)
  3107. except ValueError:
  3108. self.app.inform.emit(_("[WARNING_NOTCL] Scale factor value is missing or wrong format. "
  3109. "Add it and retry."))
  3110. return
  3111. def scale_recursion(geom, selection):
  3112. if type(geom) == list or type(geom) is MultiPolygon:
  3113. geoms = list()
  3114. for local_geom in geom:
  3115. geoms.append(scale_recursion(local_geom, selection=selection))
  3116. return geoms
  3117. else:
  3118. if geom in selection:
  3119. return DrawToolShape(affinity.scale(geom.geo, scale_factor, scale_factor, origin='center'))
  3120. else:
  3121. return geom
  3122. if not self.apertures_table.selectedItems():
  3123. self.app.inform.emit(_(
  3124. "[WARNING_NOTCL] No aperture to scale. Select at least one aperture and try again."
  3125. ))
  3126. return
  3127. for x in self.apertures_table.selectedItems():
  3128. try:
  3129. apid = self.apertures_table.item(x.row(), 1).text()
  3130. temp_storage = deepcopy(scale_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3131. self.storage_dict[apid]['solid_geometry'] = []
  3132. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3133. except Exception as e:
  3134. log.debug("FlatCAMGrbEditor.on_scale() --> %s" % str(e))
  3135. self.plot_all()
  3136. self.app.inform.emit(_("[success] Done. Scale Tool completed."))
  3137. def on_transform(self):
  3138. if type(self.active_tool) == FCTransform:
  3139. self.select_tool('select')
  3140. else:
  3141. self.select_tool('transform')
  3142. def hide_tool(self, tool_name):
  3143. # self.app.ui.notebook.setTabText(2, _("Tools"))
  3144. if tool_name == 'all':
  3145. self.apertures_frame.hide()
  3146. if tool_name == 'select':
  3147. self.apertures_frame.show()
  3148. if tool_name == 'buffer' or tool_name == 'all':
  3149. self.buffer_tool_frame.hide()
  3150. if tool_name == 'scale' or tool_name == 'all':
  3151. self.scale_tool_frame.hide()
  3152. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3153. class TransformEditorTool(FlatCAMTool):
  3154. """
  3155. Inputs to specify how to paint the selected polygons.
  3156. """
  3157. toolName = _("Transform Tool")
  3158. rotateName = _("Rotate")
  3159. skewName = _("Skew/Shear")
  3160. scaleName = _("Scale")
  3161. flipName = _("Mirror (Flip)")
  3162. offsetName = _("Offset")
  3163. def __init__(self, app, draw_app):
  3164. FlatCAMTool.__init__(self, app)
  3165. self.app = app
  3166. self.draw_app = draw_app
  3167. self.transform_lay = QtWidgets.QVBoxLayout()
  3168. self.layout.addLayout(self.transform_lay)
  3169. ## Title
  3170. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  3171. title_label.setStyleSheet("""
  3172. QLabel
  3173. {
  3174. font-size: 16px;
  3175. font-weight: bold;
  3176. }
  3177. """)
  3178. self.transform_lay.addWidget(title_label)
  3179. self.empty_label = QtWidgets.QLabel("")
  3180. self.empty_label.setFixedWidth(50)
  3181. self.empty_label1 = QtWidgets.QLabel("")
  3182. self.empty_label1.setFixedWidth(70)
  3183. self.empty_label2 = QtWidgets.QLabel("")
  3184. self.empty_label2.setFixedWidth(70)
  3185. self.empty_label3 = QtWidgets.QLabel("")
  3186. self.empty_label3.setFixedWidth(70)
  3187. self.empty_label4 = QtWidgets.QLabel("")
  3188. self.empty_label4.setFixedWidth(70)
  3189. self.transform_lay.addWidget(self.empty_label)
  3190. ## Rotate Title
  3191. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  3192. self.transform_lay.addWidget(rotate_title_label)
  3193. ## Layout
  3194. form_layout = QtWidgets.QFormLayout()
  3195. self.transform_lay.addLayout(form_layout)
  3196. form_child = QtWidgets.QHBoxLayout()
  3197. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  3198. self.rotate_label.setToolTip(
  3199. _("Angle for Rotation action, in degrees.\n"
  3200. "Float number between -360 and 359.\n"
  3201. "Positive numbers for CW motion.\n"
  3202. "Negative numbers for CCW motion.")
  3203. )
  3204. self.rotate_label.setFixedWidth(50)
  3205. self.rotate_entry = FCEntry()
  3206. # self.rotate_entry.setFixedWidth(60)
  3207. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3208. self.rotate_button = FCButton()
  3209. self.rotate_button.set_value(_("Rotate"))
  3210. self.rotate_button.setToolTip(
  3211. _("Rotate the selected shape(s).\n"
  3212. "The point of reference is the middle of\n"
  3213. "the bounding box for all selected shapes.")
  3214. )
  3215. self.rotate_button.setFixedWidth(60)
  3216. form_child.addWidget(self.rotate_entry)
  3217. form_child.addWidget(self.rotate_button)
  3218. form_layout.addRow(self.rotate_label, form_child)
  3219. self.transform_lay.addWidget(self.empty_label1)
  3220. ## Skew Title
  3221. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  3222. self.transform_lay.addWidget(skew_title_label)
  3223. ## Form Layout
  3224. form1_layout = QtWidgets.QFormLayout()
  3225. self.transform_lay.addLayout(form1_layout)
  3226. form1_child_1 = QtWidgets.QHBoxLayout()
  3227. form1_child_2 = QtWidgets.QHBoxLayout()
  3228. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  3229. self.skewx_label.setToolTip(
  3230. _("Angle for Skew action, in degrees.\n"
  3231. "Float number between -360 and 359.")
  3232. )
  3233. self.skewx_label.setFixedWidth(50)
  3234. self.skewx_entry = FCEntry()
  3235. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3236. # self.skewx_entry.setFixedWidth(60)
  3237. self.skewx_button = FCButton()
  3238. self.skewx_button.set_value(_("Skew X"))
  3239. self.skewx_button.setToolTip(
  3240. _("Skew/shear the selected shape(s).\n"
  3241. "The point of reference is the middle of\n"
  3242. "the bounding box for all selected shapes."))
  3243. self.skewx_button.setFixedWidth(60)
  3244. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  3245. self.skewy_label.setToolTip(
  3246. _("Angle for Skew action, in degrees.\n"
  3247. "Float number between -360 and 359.")
  3248. )
  3249. self.skewy_label.setFixedWidth(50)
  3250. self.skewy_entry = FCEntry()
  3251. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3252. # self.skewy_entry.setFixedWidth(60)
  3253. self.skewy_button = FCButton()
  3254. self.skewy_button.set_value(_("Skew Y"))
  3255. self.skewy_button.setToolTip(
  3256. _("Skew/shear the selected shape(s).\n"
  3257. "The point of reference is the middle of\n"
  3258. "the bounding box for all selected shapes."))
  3259. self.skewy_button.setFixedWidth(60)
  3260. form1_child_1.addWidget(self.skewx_entry)
  3261. form1_child_1.addWidget(self.skewx_button)
  3262. form1_child_2.addWidget(self.skewy_entry)
  3263. form1_child_2.addWidget(self.skewy_button)
  3264. form1_layout.addRow(self.skewx_label, form1_child_1)
  3265. form1_layout.addRow(self.skewy_label, form1_child_2)
  3266. self.transform_lay.addWidget(self.empty_label2)
  3267. ## Scale Title
  3268. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  3269. self.transform_lay.addWidget(scale_title_label)
  3270. ## Form Layout
  3271. form2_layout = QtWidgets.QFormLayout()
  3272. self.transform_lay.addLayout(form2_layout)
  3273. form2_child_1 = QtWidgets.QHBoxLayout()
  3274. form2_child_2 = QtWidgets.QHBoxLayout()
  3275. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  3276. self.scalex_label.setToolTip(
  3277. _("Factor for Scale action over X axis.")
  3278. )
  3279. self.scalex_label.setFixedWidth(50)
  3280. self.scalex_entry = FCEntry()
  3281. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3282. # self.scalex_entry.setFixedWidth(60)
  3283. self.scalex_button = FCButton()
  3284. self.scalex_button.set_value(_("Scale X"))
  3285. self.scalex_button.setToolTip(
  3286. _("Scale the selected shape(s).\n"
  3287. "The point of reference depends on \n"
  3288. "the Scale reference checkbox state."))
  3289. self.scalex_button.setFixedWidth(60)
  3290. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  3291. self.scaley_label.setToolTip(
  3292. _("Factor for Scale action over Y axis.")
  3293. )
  3294. self.scaley_label.setFixedWidth(50)
  3295. self.scaley_entry = FCEntry()
  3296. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3297. # self.scaley_entry.setFixedWidth(60)
  3298. self.scaley_button = FCButton()
  3299. self.scaley_button.set_value(_("Scale Y"))
  3300. self.scaley_button.setToolTip(
  3301. _("Scale the selected shape(s).\n"
  3302. "The point of reference depends on \n"
  3303. "the Scale reference checkbox state."))
  3304. self.scaley_button.setFixedWidth(60)
  3305. self.scale_link_cb = FCCheckBox()
  3306. self.scale_link_cb.set_value(True)
  3307. self.scale_link_cb.setText(_("Link"))
  3308. self.scale_link_cb.setToolTip(
  3309. _("Scale the selected shape(s)\n"
  3310. "using the Scale Factor X for both axis."))
  3311. self.scale_link_cb.setFixedWidth(50)
  3312. self.scale_zero_ref_cb = FCCheckBox()
  3313. self.scale_zero_ref_cb.set_value(True)
  3314. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  3315. self.scale_zero_ref_cb.setToolTip(
  3316. _("Scale the selected shape(s)\n"
  3317. "using the origin reference when checked,\n"
  3318. "and the center of the biggest bounding box\n"
  3319. "of the selected shapes when unchecked."))
  3320. form2_child_1.addWidget(self.scalex_entry)
  3321. form2_child_1.addWidget(self.scalex_button)
  3322. form2_child_2.addWidget(self.scaley_entry)
  3323. form2_child_2.addWidget(self.scaley_button)
  3324. form2_layout.addRow(self.scalex_label, form2_child_1)
  3325. form2_layout.addRow(self.scaley_label, form2_child_2)
  3326. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  3327. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button],
  3328. logic=False)
  3329. self.transform_lay.addWidget(self.empty_label3)
  3330. ## Offset Title
  3331. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  3332. self.transform_lay.addWidget(offset_title_label)
  3333. ## Form Layout
  3334. form3_layout = QtWidgets.QFormLayout()
  3335. self.transform_lay.addLayout(form3_layout)
  3336. form3_child_1 = QtWidgets.QHBoxLayout()
  3337. form3_child_2 = QtWidgets.QHBoxLayout()
  3338. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  3339. self.offx_label.setToolTip(
  3340. _("Value for Offset action on X axis.")
  3341. )
  3342. self.offx_label.setFixedWidth(50)
  3343. self.offx_entry = FCEntry()
  3344. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3345. # self.offx_entry.setFixedWidth(60)
  3346. self.offx_button = FCButton()
  3347. self.offx_button.set_value(_("Offset X"))
  3348. self.offx_button.setToolTip(
  3349. _("Offset the selected shape(s).\n"
  3350. "The point of reference is the middle of\n"
  3351. "the bounding box for all selected shapes.\n")
  3352. )
  3353. self.offx_button.setFixedWidth(60)
  3354. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  3355. self.offy_label.setToolTip(
  3356. _("Value for Offset action on Y axis.")
  3357. )
  3358. self.offy_label.setFixedWidth(50)
  3359. self.offy_entry = FCEntry()
  3360. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3361. # self.offy_entry.setFixedWidth(60)
  3362. self.offy_button = FCButton()
  3363. self.offy_button.set_value(_("Offset Y"))
  3364. self.offy_button.setToolTip(
  3365. _("Offset the selected shape(s).\n"
  3366. "The point of reference is the middle of\n"
  3367. "the bounding box for all selected shapes.\n")
  3368. )
  3369. self.offy_button.setFixedWidth(60)
  3370. form3_child_1.addWidget(self.offx_entry)
  3371. form3_child_1.addWidget(self.offx_button)
  3372. form3_child_2.addWidget(self.offy_entry)
  3373. form3_child_2.addWidget(self.offy_button)
  3374. form3_layout.addRow(self.offx_label, form3_child_1)
  3375. form3_layout.addRow(self.offy_label, form3_child_2)
  3376. self.transform_lay.addWidget(self.empty_label4)
  3377. ## Flip Title
  3378. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  3379. self.transform_lay.addWidget(flip_title_label)
  3380. ## Form Layout
  3381. form4_layout = QtWidgets.QFormLayout()
  3382. form4_child_hlay = QtWidgets.QHBoxLayout()
  3383. self.transform_lay.addLayout(form4_child_hlay)
  3384. self.transform_lay.addLayout(form4_layout)
  3385. form4_child_1 = QtWidgets.QHBoxLayout()
  3386. self.flipx_button = FCButton()
  3387. self.flipx_button.set_value(_("Flip on X"))
  3388. self.flipx_button.setToolTip(
  3389. _("Flip the selected shape(s) over the X axis.\n"
  3390. "Does not create a new shape.")
  3391. )
  3392. self.flipx_button.setFixedWidth(60)
  3393. self.flipy_button = FCButton()
  3394. self.flipy_button.set_value(_("Flip on Y"))
  3395. self.flipy_button.setToolTip(
  3396. _("Flip the selected shape(s) over the X axis.\n"
  3397. "Does not create a new shape.")
  3398. )
  3399. self.flipy_button.setFixedWidth(60)
  3400. self.flip_ref_cb = FCCheckBox()
  3401. self.flip_ref_cb.set_value(True)
  3402. self.flip_ref_cb.setText(_("Ref Pt"))
  3403. self.flip_ref_cb.setToolTip(
  3404. _("Flip the selected shape(s)\n"
  3405. "around the point in Point Entry Field.\n"
  3406. "\n"
  3407. "The point coordinates can be captured by\n"
  3408. "left click on canvas together with pressing\n"
  3409. "SHIFT key. \n"
  3410. "Then click Add button to insert coordinates.\n"
  3411. "Or enter the coords in format (x, y) in the\n"
  3412. "Point Entry field and click Flip on X(Y)")
  3413. )
  3414. self.flip_ref_cb.setFixedWidth(50)
  3415. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  3416. self.flip_ref_label.setToolTip(
  3417. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  3418. "The 'x' in (x, y) will be used when using Flip on X and\n"
  3419. "the 'y' in (x, y) will be used when using Flip on Y.")
  3420. )
  3421. self.flip_ref_label.setFixedWidth(50)
  3422. self.flip_ref_entry = EvalEntry2("(0, 0)")
  3423. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3424. # self.flip_ref_entry.setFixedWidth(60)
  3425. self.flip_ref_button = FCButton()
  3426. self.flip_ref_button.set_value(_("Add"))
  3427. self.flip_ref_button.setToolTip(
  3428. _("The point coordinates can be captured by\n"
  3429. "left click on canvas together with pressing\n"
  3430. "SHIFT key. Then click Add button to insert.")
  3431. )
  3432. self.flip_ref_button.setFixedWidth(60)
  3433. form4_child_hlay.addStretch()
  3434. form4_child_hlay.addWidget(self.flipx_button)
  3435. form4_child_hlay.addWidget(self.flipy_button)
  3436. form4_child_1.addWidget(self.flip_ref_entry)
  3437. form4_child_1.addWidget(self.flip_ref_button)
  3438. form4_layout.addRow(self.flip_ref_cb)
  3439. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  3440. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  3441. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  3442. self.transform_lay.addStretch()
  3443. ## Signals
  3444. self.rotate_button.clicked.connect(self.on_rotate)
  3445. self.skewx_button.clicked.connect(self.on_skewx)
  3446. self.skewy_button.clicked.connect(self.on_skewy)
  3447. self.scalex_button.clicked.connect(self.on_scalex)
  3448. self.scaley_button.clicked.connect(self.on_scaley)
  3449. self.offx_button.clicked.connect(self.on_offx)
  3450. self.offy_button.clicked.connect(self.on_offy)
  3451. self.flipx_button.clicked.connect(self.on_flipx)
  3452. self.flipy_button.clicked.connect(self.on_flipy)
  3453. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  3454. self.rotate_entry.returnPressed.connect(self.on_rotate)
  3455. self.skewx_entry.returnPressed.connect(self.on_skewx)
  3456. self.skewy_entry.returnPressed.connect(self.on_skewy)
  3457. self.scalex_entry.returnPressed.connect(self.on_scalex)
  3458. self.scaley_entry.returnPressed.connect(self.on_scaley)
  3459. self.offx_entry.returnPressed.connect(self.on_offx)
  3460. self.offy_entry.returnPressed.connect(self.on_offy)
  3461. self.set_tool_ui()
  3462. def run(self, toggle=True):
  3463. self.app.report_usage("Geo Editor Transform Tool()")
  3464. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3465. if self.app.ui.splitter.sizes()[0] == 0:
  3466. self.app.ui.splitter.setSizes([1, 1])
  3467. if toggle:
  3468. try:
  3469. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  3470. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3471. else:
  3472. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  3473. except AttributeError:
  3474. pass
  3475. FlatCAMTool.run(self)
  3476. self.set_tool_ui()
  3477. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  3478. def install(self, icon=None, separator=None, **kwargs):
  3479. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  3480. def set_tool_ui(self):
  3481. ## Initialize form
  3482. if self.app.defaults["tools_transform_rotate"]:
  3483. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  3484. else:
  3485. self.rotate_entry.set_value(0.0)
  3486. if self.app.defaults["tools_transform_skew_x"]:
  3487. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  3488. else:
  3489. self.skewx_entry.set_value(0.0)
  3490. if self.app.defaults["tools_transform_skew_y"]:
  3491. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  3492. else:
  3493. self.skewy_entry.set_value(0.0)
  3494. if self.app.defaults["tools_transform_scale_x"]:
  3495. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  3496. else:
  3497. self.scalex_entry.set_value(1.0)
  3498. if self.app.defaults["tools_transform_scale_y"]:
  3499. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  3500. else:
  3501. self.scaley_entry.set_value(1.0)
  3502. if self.app.defaults["tools_transform_scale_link"]:
  3503. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  3504. else:
  3505. self.scale_link_cb.set_value(True)
  3506. if self.app.defaults["tools_transform_scale_reference"]:
  3507. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  3508. else:
  3509. self.scale_zero_ref_cb.set_value(True)
  3510. if self.app.defaults["tools_transform_offset_x"]:
  3511. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  3512. else:
  3513. self.offx_entry.set_value(0.0)
  3514. if self.app.defaults["tools_transform_offset_y"]:
  3515. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  3516. else:
  3517. self.offy_entry.set_value(0.0)
  3518. if self.app.defaults["tools_transform_mirror_reference"]:
  3519. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  3520. else:
  3521. self.flip_ref_cb.set_value(False)
  3522. if self.app.defaults["tools_transform_mirror_point"]:
  3523. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  3524. else:
  3525. self.flip_ref_entry.set_value((0, 0))
  3526. def template(self):
  3527. if not self.fcdraw.selected:
  3528. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  3529. return
  3530. self.draw_app.select_tool("select")
  3531. self.app.ui.notebook.setTabText(2, "Tools")
  3532. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  3533. self.app.ui.splitter.setSizes([0, 1])
  3534. def on_rotate(self, sig=None, val=None):
  3535. if val:
  3536. value = val
  3537. else:
  3538. try:
  3539. value = float(self.rotate_entry.get_value())
  3540. except ValueError:
  3541. # try to convert comma to decimal point. if it's still not working error message and return
  3542. try:
  3543. value = float(self.rotate_entry.get_value().replace(',', '.'))
  3544. except ValueError:
  3545. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  3546. "use a number."))
  3547. return
  3548. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  3549. 'params': [value]})
  3550. # self.on_rotate_action(value)
  3551. return
  3552. def on_flipx(self):
  3553. # self.on_flip("Y")
  3554. axis = 'Y'
  3555. self.app.worker_task.emit({'fcn': self.on_flip,
  3556. 'params': [axis]})
  3557. return
  3558. def on_flipy(self):
  3559. # self.on_flip("X")
  3560. axis = 'X'
  3561. self.app.worker_task.emit({'fcn': self.on_flip,
  3562. 'params': [axis]})
  3563. return
  3564. def on_flip_add_coords(self):
  3565. val = self.app.clipboard.text()
  3566. self.flip_ref_entry.set_value(val)
  3567. def on_skewx(self, sig=None, val=None):
  3568. if val:
  3569. value = val
  3570. else:
  3571. try:
  3572. value = float(self.skewx_entry.get_value())
  3573. except ValueError:
  3574. # try to convert comma to decimal point. if it's still not working error message and return
  3575. try:
  3576. value = float(self.skewx_entry.get_value().replace(',', '.'))
  3577. except ValueError:
  3578. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  3579. "use a number."))
  3580. return
  3581. # self.on_skew("X", value)
  3582. axis = 'X'
  3583. self.app.worker_task.emit({'fcn': self.on_skew,
  3584. 'params': [axis, value]})
  3585. return
  3586. def on_skewy(self, sig=None, val=None):
  3587. if val:
  3588. value = val
  3589. else:
  3590. try:
  3591. value = float(self.skewy_entry.get_value())
  3592. except ValueError:
  3593. # try to convert comma to decimal point. if it's still not working error message and return
  3594. try:
  3595. value = float(self.skewy_entry.get_value().replace(',', '.'))
  3596. except ValueError:
  3597. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  3598. "use a number."))
  3599. return
  3600. # self.on_skew("Y", value)
  3601. axis = 'Y'
  3602. self.app.worker_task.emit({'fcn': self.on_skew,
  3603. 'params': [axis, value]})
  3604. return
  3605. def on_scalex(self, sig=None, val=None):
  3606. if val:
  3607. xvalue = val
  3608. else:
  3609. try:
  3610. xvalue = float(self.scalex_entry.get_value())
  3611. except ValueError:
  3612. # try to convert comma to decimal point. if it's still not working error message and return
  3613. try:
  3614. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  3615. except ValueError:
  3616. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  3617. "use a number."))
  3618. return
  3619. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3620. if xvalue == 0:
  3621. xvalue = 1
  3622. if self.scale_link_cb.get_value():
  3623. yvalue = xvalue
  3624. else:
  3625. yvalue = 1
  3626. axis = 'X'
  3627. point = (0, 0)
  3628. if self.scale_zero_ref_cb.get_value():
  3629. self.app.worker_task.emit({'fcn': self.on_scale,
  3630. 'params': [axis, xvalue, yvalue, point]})
  3631. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  3632. else:
  3633. # self.on_scale("X", xvalue, yvalue)
  3634. self.app.worker_task.emit({'fcn': self.on_scale,
  3635. 'params': [axis, xvalue, yvalue]})
  3636. return
  3637. def on_scaley(self, sig=None, val=None):
  3638. xvalue = 1
  3639. if val:
  3640. yvalue = val
  3641. else:
  3642. try:
  3643. yvalue = float(self.scaley_entry.get_value())
  3644. except ValueError:
  3645. # try to convert comma to decimal point. if it's still not working error message and return
  3646. try:
  3647. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  3648. except ValueError:
  3649. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  3650. "use a number."))
  3651. return
  3652. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3653. if yvalue == 0:
  3654. yvalue = 1
  3655. axis = 'Y'
  3656. point = (0, 0)
  3657. if self.scale_zero_ref_cb.get_value():
  3658. self.app.worker_task.emit({'fcn': self.on_scale,
  3659. 'params': [axis, xvalue, yvalue, point]})
  3660. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  3661. else:
  3662. # self.on_scale("Y", xvalue, yvalue)
  3663. self.app.worker_task.emit({'fcn': self.on_scale,
  3664. 'params': [axis, xvalue, yvalue]})
  3665. return
  3666. def on_offx(self, sig=None, val=None):
  3667. if val:
  3668. value = val
  3669. else:
  3670. try:
  3671. value = float(self.offx_entry.get_value())
  3672. except ValueError:
  3673. # try to convert comma to decimal point. if it's still not working error message and return
  3674. try:
  3675. value = float(self.offx_entry.get_value().replace(',', '.'))
  3676. except ValueError:
  3677. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  3678. "use a number."))
  3679. return
  3680. # self.on_offset("X", value)
  3681. axis = 'X'
  3682. self.app.worker_task.emit({'fcn': self.on_offset,
  3683. 'params': [axis, value]})
  3684. return
  3685. def on_offy(self, sig=None, val=None):
  3686. if val:
  3687. value = val
  3688. else:
  3689. try:
  3690. value = float(self.offy_entry.get_value())
  3691. except ValueError:
  3692. # try to convert comma to decimal point. if it's still not working error message and return
  3693. try:
  3694. value = float(self.offy_entry.get_value().replace(',', '.'))
  3695. except ValueError:
  3696. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  3697. "use a number."))
  3698. return
  3699. # self.on_offset("Y", value)
  3700. axis = 'Y'
  3701. self.app.worker_task.emit({'fcn': self.on_offset,
  3702. 'params': [axis, value]})
  3703. return
  3704. def on_rotate_action(self, num):
  3705. shape_list = self.draw_app.selected
  3706. xminlist = []
  3707. yminlist = []
  3708. xmaxlist = []
  3709. ymaxlist = []
  3710. if not shape_list:
  3711. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  3712. return
  3713. else:
  3714. with self.app.proc_container.new(_("Appying Rotate")):
  3715. try:
  3716. # first get a bounding box to fit all
  3717. for sha in shape_list:
  3718. xmin, ymin, xmax, ymax = sha.bounds()
  3719. xminlist.append(xmin)
  3720. yminlist.append(ymin)
  3721. xmaxlist.append(xmax)
  3722. ymaxlist.append(ymax)
  3723. # get the minimum x,y and maximum x,y for all objects selected
  3724. xminimal = min(xminlist)
  3725. yminimal = min(yminlist)
  3726. xmaximal = max(xmaxlist)
  3727. ymaximal = max(ymaxlist)
  3728. self.app.progress.emit(20)
  3729. for sel_sha in shape_list:
  3730. px = 0.5 * (xminimal + xmaximal)
  3731. py = 0.5 * (yminimal + ymaximal)
  3732. sel_sha.rotate(-num, point=(px, py))
  3733. self.draw_app.plot_all()
  3734. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  3735. # self.draw_app.transform_complete.emit()
  3736. self.app.inform.emit(_("[success] Done. Rotate completed."))
  3737. self.app.progress.emit(100)
  3738. except Exception as e:
  3739. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3740. return
  3741. def on_flip(self, axis):
  3742. shape_list = self.draw_app.selected
  3743. xminlist = []
  3744. yminlist = []
  3745. xmaxlist = []
  3746. ymaxlist = []
  3747. if not shape_list:
  3748. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  3749. return
  3750. else:
  3751. with self.app.proc_container.new(_("Applying Flip")):
  3752. try:
  3753. # get mirroring coords from the point entry
  3754. if self.flip_ref_cb.isChecked():
  3755. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  3756. # get mirroing coords from the center of an all-enclosing bounding box
  3757. else:
  3758. # first get a bounding box to fit all
  3759. for sha in shape_list:
  3760. xmin, ymin, xmax, ymax = sha.bounds()
  3761. xminlist.append(xmin)
  3762. yminlist.append(ymin)
  3763. xmaxlist.append(xmax)
  3764. ymaxlist.append(ymax)
  3765. # get the minimum x,y and maximum x,y for all objects selected
  3766. xminimal = min(xminlist)
  3767. yminimal = min(yminlist)
  3768. xmaximal = max(xmaxlist)
  3769. ymaximal = max(ymaxlist)
  3770. px = 0.5 * (xminimal + xmaximal)
  3771. py = 0.5 * (yminimal + ymaximal)
  3772. self.app.progress.emit(20)
  3773. # execute mirroring
  3774. for sha in shape_list:
  3775. if axis is 'X':
  3776. sha.mirror('X', (px, py))
  3777. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  3778. elif axis is 'Y':
  3779. sha.mirror('Y', (px, py))
  3780. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  3781. self.draw_app.plot_all()
  3782. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3783. #
  3784. # self.draw_app.transform_complete.emit()
  3785. self.app.progress.emit(100)
  3786. except Exception as e:
  3787. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3788. return
  3789. def on_skew(self, axis, num):
  3790. shape_list = self.draw_app.selected
  3791. xminlist = []
  3792. yminlist = []
  3793. if not shape_list:
  3794. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  3795. return
  3796. else:
  3797. with self.app.proc_container.new(_("Applying Skew")):
  3798. try:
  3799. # first get a bounding box to fit all
  3800. for sha in shape_list:
  3801. xmin, ymin, xmax, ymax = sha.bounds()
  3802. xminlist.append(xmin)
  3803. yminlist.append(ymin)
  3804. # get the minimum x,y and maximum x,y for all objects selected
  3805. xminimal = min(xminlist)
  3806. yminimal = min(yminlist)
  3807. self.app.progress.emit(20)
  3808. for sha in shape_list:
  3809. if axis is 'X':
  3810. sha.skew(num, 0, point=(xminimal, yminimal))
  3811. elif axis is 'Y':
  3812. sha.skew(0, num, point=(xminimal, yminimal))
  3813. self.draw_app.plot_all()
  3814. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3815. #
  3816. # self.draw_app.transform_complete.emit()
  3817. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  3818. self.app.progress.emit(100)
  3819. except Exception as e:
  3820. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  3821. return
  3822. def on_scale(self, axis, xfactor, yfactor, point=None):
  3823. shape_list = self.draw_app.selected
  3824. xminlist = []
  3825. yminlist = []
  3826. xmaxlist = []
  3827. ymaxlist = []
  3828. if not shape_list:
  3829. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  3830. return
  3831. else:
  3832. with self.app.proc_container.new(_("Applying Scale")):
  3833. try:
  3834. # first get a bounding box to fit all
  3835. for sha in shape_list:
  3836. xmin, ymin, xmax, ymax = sha.bounds()
  3837. xminlist.append(xmin)
  3838. yminlist.append(ymin)
  3839. xmaxlist.append(xmax)
  3840. ymaxlist.append(ymax)
  3841. # get the minimum x,y and maximum x,y for all objects selected
  3842. xminimal = min(xminlist)
  3843. yminimal = min(yminlist)
  3844. xmaximal = max(xmaxlist)
  3845. ymaximal = max(ymaxlist)
  3846. self.app.progress.emit(20)
  3847. if point is None:
  3848. px = 0.5 * (xminimal + xmaximal)
  3849. py = 0.5 * (yminimal + ymaximal)
  3850. else:
  3851. px = 0
  3852. py = 0
  3853. for sha in shape_list:
  3854. sha.scale(xfactor, yfactor, point=(px, py))
  3855. self.draw_app.plot_all()
  3856. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3857. #
  3858. # self.draw_app.transform_complete.emit()
  3859. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  3860. self.app.progress.emit(100)
  3861. except Exception as e:
  3862. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  3863. return
  3864. def on_offset(self, axis, num):
  3865. shape_list = self.draw_app.selected
  3866. xminlist = []
  3867. yminlist = []
  3868. if not shape_list:
  3869. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  3870. return
  3871. else:
  3872. with self.app.proc_container.new(_("Applying Offset")):
  3873. try:
  3874. # first get a bounding box to fit all
  3875. for sha in shape_list:
  3876. xmin, ymin, xmax, ymax = sha.bounds()
  3877. xminlist.append(xmin)
  3878. yminlist.append(ymin)
  3879. # get the minimum x,y and maximum x,y for all objects selected
  3880. xminimal = min(xminlist)
  3881. yminimal = min(yminlist)
  3882. self.app.progress.emit(20)
  3883. for sha in shape_list:
  3884. if axis is 'X':
  3885. sha.offset((num, 0))
  3886. elif axis is 'Y':
  3887. sha.offset((0, num))
  3888. self.draw_app.plot_all()
  3889. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3890. #
  3891. # self.draw_app.transform_complete.emit()
  3892. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  3893. self.app.progress.emit(100)
  3894. except Exception as e:
  3895. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  3896. return
  3897. def on_rotate_key(self):
  3898. val_box = FCInputDialog(title=_("Rotate ..."),
  3899. text=_('Enter an Angle Value (degrees):'),
  3900. min=-359.9999, max=360.0000, decimals=4,
  3901. init_val=float(self.app.defaults['tools_transform_rotate']))
  3902. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  3903. val, ok = val_box.get_value()
  3904. if ok:
  3905. self.on_rotate(val=val)
  3906. self.app.inform.emit(
  3907. _("[success] Geometry shape rotate done...")
  3908. )
  3909. return
  3910. else:
  3911. self.app.inform.emit(
  3912. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  3913. )
  3914. def on_offx_key(self):
  3915. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3916. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  3917. text=(_('Enter a distance Value (%s):') % str(units)),
  3918. min=-9999.9999, max=10000.0000, decimals=4,
  3919. init_val=float(self.app.defaults['tools_transform_offset_x']))
  3920. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  3921. val, ok = val_box.get_value()
  3922. if ok:
  3923. self.on_offx(val=val)
  3924. self.app.inform.emit(
  3925. _("[success] Geometry shape offset on X axis done..."))
  3926. return
  3927. else:
  3928. self.app.inform.emit(
  3929. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  3930. def on_offy_key(self):
  3931. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3932. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  3933. text=(_('Enter a distance Value (%s):') % str(units)),
  3934. min=-9999.9999, max=10000.0000, decimals=4,
  3935. init_val=float(self.app.defaults['tools_transform_offset_y']))
  3936. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  3937. val, ok = val_box.get_value()
  3938. if ok:
  3939. self.on_offx(val=val)
  3940. self.app.inform.emit(
  3941. _("[success] Geometry shape offset on Y axis done..."))
  3942. return
  3943. else:
  3944. self.app.inform.emit(
  3945. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  3946. def on_skewx_key(self):
  3947. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  3948. text=_('Enter an Angle Value (degrees):'),
  3949. min=-359.9999, max=360.0000, decimals=4,
  3950. init_val=float(self.app.defaults['tools_transform_skew_x']))
  3951. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  3952. val, ok = val_box.get_value()
  3953. if ok:
  3954. self.on_skewx(val=val)
  3955. self.app.inform.emit(
  3956. _("[success] Geometry shape skew on X axis done..."))
  3957. return
  3958. else:
  3959. self.app.inform.emit(
  3960. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  3961. def on_skewy_key(self):
  3962. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  3963. text=_('Enter an Angle Value (degrees):'),
  3964. min=-359.9999, max=360.0000, decimals=4,
  3965. init_val=float(self.app.defaults['tools_transform_skew_y']))
  3966. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  3967. val, ok = val_box.get_value()
  3968. if ok:
  3969. self.on_skewx(val=val)
  3970. self.app.inform.emit(
  3971. _("[success] Geometry shape skew on Y axis done..."))
  3972. return
  3973. else:
  3974. self.app.inform.emit(
  3975. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))