FlatCAMGrbEditor.py 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850
  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. self.grb_editor_app.apertures_table.clearSelection()
  1300. self.grb_editor_app.hide_tool('all')
  1301. self.grb_editor_app.hide_tool('select')
  1302. try:
  1303. QtGui.QGuiApplication.restoreOverrideCursor()
  1304. except:
  1305. pass
  1306. def set_origin(self, origin):
  1307. self.origin = origin
  1308. def click(self, point):
  1309. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1310. if self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1311. if key_modifier == Qt.ControlModifier:
  1312. pass
  1313. else:
  1314. self.grb_editor_app.selected = []
  1315. else:
  1316. if key_modifier == Qt.ShiftModifier:
  1317. pass
  1318. else:
  1319. self.grb_editor_app.selected = []
  1320. def click_release(self, point):
  1321. self.grb_editor_app.apertures_table.clearSelection()
  1322. sel_aperture = set()
  1323. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1324. for storage in self.grb_editor_app.storage_dict:
  1325. try:
  1326. for shape in self.grb_editor_app.storage_dict[storage]['solid_geometry']:
  1327. if Point(point).within(shape.geo):
  1328. if (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Control' and
  1329. key_modifier == Qt.ControlModifier) or \
  1330. (self.grb_editor_app.app.defaults["global_mselect_key"] == 'Shift' and
  1331. key_modifier == Qt.ShiftModifier):
  1332. if shape in self.draw_app.selected:
  1333. self.draw_app.selected.remove(shape)
  1334. else:
  1335. # add the object to the selected shapes
  1336. self.draw_app.selected.append(shape)
  1337. sel_aperture.add(storage)
  1338. else:
  1339. self.draw_app.selected.append(shape)
  1340. sel_aperture.add(storage)
  1341. except KeyError:
  1342. pass
  1343. # select the aperture in the Apertures Table that is associated with the selected shape
  1344. try:
  1345. self.draw_app.apertures_table.cellPressed.disconnect()
  1346. except:
  1347. pass
  1348. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1349. for aper in sel_aperture:
  1350. for row in range(self.grb_editor_app.apertures_table.rowCount()):
  1351. if str(aper) == self.grb_editor_app.apertures_table.item(row, 1).text():
  1352. self.grb_editor_app.apertures_table.selectRow(row)
  1353. self.draw_app.last_aperture_selected = aper
  1354. self.grb_editor_app.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1355. self.draw_app.apertures_table.cellPressed.connect(self.draw_app.on_row_selected)
  1356. return ""
  1357. def clean_up(self):
  1358. self.draw_app.plot_all()
  1359. class FCTransform(FCShapeTool):
  1360. def __init__(self, draw_app):
  1361. FCShapeTool.__init__(self, draw_app)
  1362. self.name = 'transformation'
  1363. # self.shape_buffer = self.draw_app.shape_buffer
  1364. self.draw_app = draw_app
  1365. self.app = draw_app.app
  1366. self.start_msg = _("Shape transformations ...")
  1367. self.origin = (0, 0)
  1368. self.draw_app.transform_tool.run()
  1369. def clean_up(self):
  1370. self.draw_app.selected = []
  1371. self.draw_app.apertures_table.clearSelection()
  1372. self.draw_app.plot_all()
  1373. class FlatCAMGrbEditor(QtCore.QObject):
  1374. draw_shape_idx = -1
  1375. def __init__(self, app):
  1376. assert isinstance(app, FlatCAMApp.App), \
  1377. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1378. super(FlatCAMGrbEditor, self).__init__()
  1379. self.app = app
  1380. self.canvas = self.app.plotcanvas
  1381. ## Current application units in Upper Case
  1382. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1383. self.grb_edit_widget = QtWidgets.QWidget()
  1384. layout = QtWidgets.QVBoxLayout()
  1385. self.grb_edit_widget.setLayout(layout)
  1386. ## Page Title box (spacing between children)
  1387. self.title_box = QtWidgets.QHBoxLayout()
  1388. layout.addLayout(self.title_box)
  1389. ## Page Title icon
  1390. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1391. self.icon = QtWidgets.QLabel()
  1392. self.icon.setPixmap(pixmap)
  1393. self.title_box.addWidget(self.icon, stretch=0)
  1394. ## Title label
  1395. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Gerber Editor'))
  1396. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1397. self.title_box.addWidget(self.title_label, stretch=1)
  1398. ## Object name
  1399. self.name_box = QtWidgets.QHBoxLayout()
  1400. layout.addLayout(self.name_box)
  1401. name_label = QtWidgets.QLabel(_("Name:"))
  1402. self.name_box.addWidget(name_label)
  1403. self.name_entry = FCEntry()
  1404. self.name_box.addWidget(self.name_entry)
  1405. ## Box for custom widgets
  1406. # This gets populated in offspring implementations.
  1407. self.custom_box = QtWidgets.QVBoxLayout()
  1408. layout.addLayout(self.custom_box)
  1409. #### Gerber Apertures ####
  1410. self.apertures_table_label = QtWidgets.QLabel(_('<b>Apertures:</b>'))
  1411. self.apertures_table_label.setToolTip(
  1412. _("Apertures Table for the Gerber Object.")
  1413. )
  1414. self.custom_box.addWidget(self.apertures_table_label)
  1415. self.apertures_table = FCTable()
  1416. # delegate = SpinBoxDelegate(units=self.units)
  1417. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  1418. self.custom_box.addWidget(self.apertures_table)
  1419. self.apertures_table.setColumnCount(5)
  1420. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  1421. self.apertures_table.setSortingEnabled(False)
  1422. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  1423. _("Index"))
  1424. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  1425. _("Aperture Code"))
  1426. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  1427. _("Type of aperture: circular, rectangle, macros etc"))
  1428. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  1429. _("Aperture Size:"))
  1430. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  1431. _("Aperture Dimensions:\n"
  1432. " - (width, height) for R, O type.\n"
  1433. " - (dia, nVertices) for P type"))
  1434. self.empty_label = QtWidgets.QLabel('')
  1435. self.custom_box.addWidget(self.empty_label)
  1436. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Apertures widgets
  1437. # this way I can hide/show the frame
  1438. self.apertures_frame = QtWidgets.QFrame()
  1439. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  1440. self.custom_box.addWidget(self.apertures_frame)
  1441. self.apertures_box = QtWidgets.QVBoxLayout()
  1442. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  1443. self.apertures_frame.setLayout(self.apertures_box)
  1444. #### Add/Delete an new Aperture ####
  1445. grid1 = QtWidgets.QGridLayout()
  1446. self.apertures_box.addLayout(grid1)
  1447. apcode_lbl = QtWidgets.QLabel(_('Aperture Code:'))
  1448. apcode_lbl.setToolTip(
  1449. _("Code for the new aperture")
  1450. )
  1451. grid1.addWidget(apcode_lbl, 1, 0)
  1452. self.apcode_entry = FCEntry()
  1453. self.apcode_entry.setValidator(QtGui.QIntValidator(0, 999))
  1454. grid1.addWidget(self.apcode_entry, 1, 1)
  1455. apsize_lbl = QtWidgets.QLabel(_('Aperture Size:'))
  1456. apsize_lbl.setToolTip(
  1457. _("Size for the new aperture.\n"
  1458. "If aperture type is 'R' or 'O' then\n"
  1459. "this value is automatically\n"
  1460. "calculated as:\n"
  1461. "sqrt(width**2 + height**2)")
  1462. )
  1463. grid1.addWidget(apsize_lbl, 2, 0)
  1464. self.apsize_entry = FCEntry()
  1465. self.apsize_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1466. grid1.addWidget(self.apsize_entry, 2, 1)
  1467. aptype_lbl = QtWidgets.QLabel(_('Aperture Type:'))
  1468. aptype_lbl.setToolTip(
  1469. _("Select the type of new aperture. Can be:\n"
  1470. "C = circular\n"
  1471. "R = rectangular\n"
  1472. "O = oblong")
  1473. )
  1474. grid1.addWidget(aptype_lbl, 3, 0)
  1475. self.aptype_cb = FCComboBox()
  1476. self.aptype_cb.addItems(['C', 'R', 'O'])
  1477. grid1.addWidget(self.aptype_cb, 3, 1)
  1478. self.apdim_lbl = QtWidgets.QLabel(_('Aperture Dim:'))
  1479. self.apdim_lbl.setToolTip(
  1480. _("Dimensions for the new aperture.\n"
  1481. "Active only for rectangular apertures (type R).\n"
  1482. "The format is (width, height)")
  1483. )
  1484. grid1.addWidget(self.apdim_lbl, 4, 0)
  1485. self.apdim_entry = EvalEntry2()
  1486. grid1.addWidget(self.apdim_entry, 4, 1)
  1487. apadd_del_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Aperture:'))
  1488. apadd_del_lbl.setToolTip(
  1489. _("Add/Delete an aperture in the aperture table")
  1490. )
  1491. self.apertures_box.addWidget(apadd_del_lbl)
  1492. hlay_ad = QtWidgets.QHBoxLayout()
  1493. self.apertures_box.addLayout(hlay_ad)
  1494. self.addaperture_btn = QtWidgets.QPushButton(_('Add'))
  1495. self.addaperture_btn.setToolTip(
  1496. _( "Add a new aperture to the aperture list.")
  1497. )
  1498. self.delaperture_btn = QtWidgets.QPushButton(_('Delete'))
  1499. self.delaperture_btn.setToolTip(
  1500. _( "Delete a aperture in the aperture list")
  1501. )
  1502. hlay_ad.addWidget(self.addaperture_btn)
  1503. hlay_ad.addWidget(self.delaperture_btn)
  1504. ### BUFFER TOOL ###
  1505. self.buffer_tool_frame = QtWidgets.QFrame()
  1506. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  1507. self.custom_box.addWidget(self.buffer_tool_frame)
  1508. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  1509. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  1510. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  1511. self.buffer_tool_frame.hide()
  1512. # Title
  1513. buf_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Buffer Aperture:'))
  1514. buf_title_lbl.setToolTip(
  1515. _("Buffer a aperture in the aperture list")
  1516. )
  1517. self.buffer_tools_box.addWidget(buf_title_lbl)
  1518. # Form Layout
  1519. buf_form_layout = QtWidgets.QFormLayout()
  1520. self.buffer_tools_box.addLayout(buf_form_layout)
  1521. # Buffer distance
  1522. self.buffer_distance_entry = FCEntry()
  1523. buf_form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  1524. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  1525. self.buffer_corner_lbl.setToolTip(
  1526. _("There are 3 types of corners:\n"
  1527. " - 'Round': the corner is rounded.\n"
  1528. " - 'Square:' the corner is met in a sharp angle.\n"
  1529. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  1530. )
  1531. self.buffer_corner_cb = FCComboBox()
  1532. self.buffer_corner_cb.addItem(_("Round"))
  1533. self.buffer_corner_cb.addItem(_("Square"))
  1534. self.buffer_corner_cb.addItem(_("Beveled"))
  1535. buf_form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  1536. # Buttons
  1537. hlay_buf = QtWidgets.QHBoxLayout()
  1538. self.buffer_tools_box.addLayout(hlay_buf)
  1539. self.buffer_button = QtWidgets.QPushButton(_("Buffer"))
  1540. hlay_buf.addWidget(self.buffer_button)
  1541. ### SCALE TOOL ###
  1542. self.scale_tool_frame = QtWidgets.QFrame()
  1543. self.scale_tool_frame.setContentsMargins(0, 0, 0, 0)
  1544. self.custom_box.addWidget(self.scale_tool_frame)
  1545. self.scale_tools_box = QtWidgets.QVBoxLayout()
  1546. self.scale_tools_box.setContentsMargins(0, 0, 0, 0)
  1547. self.scale_tool_frame.setLayout(self.scale_tools_box)
  1548. self.scale_tool_frame.hide()
  1549. # Title
  1550. scale_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _('Scale Aperture:'))
  1551. scale_title_lbl.setToolTip(
  1552. _("Scale a aperture in the aperture list")
  1553. )
  1554. self.scale_tools_box.addWidget(scale_title_lbl)
  1555. # Form Layout
  1556. scale_form_layout = QtWidgets.QFormLayout()
  1557. self.scale_tools_box.addLayout(scale_form_layout)
  1558. self.scale_factor_lbl = QtWidgets.QLabel(_("Scale factor:"))
  1559. self.scale_factor_lbl.setToolTip(
  1560. _("The factor by which to scale the selected aperture.\n"
  1561. "Values can be between 0.0000 and 999.9999")
  1562. )
  1563. self.scale_factor_entry = FCEntry()
  1564. self.scale_factor_entry.setValidator(QtGui.QDoubleValidator(0.0000, 999.9999, 4))
  1565. scale_form_layout.addRow(self.scale_factor_lbl, self.scale_factor_entry)
  1566. # Buttons
  1567. hlay_scale = QtWidgets.QHBoxLayout()
  1568. self.scale_tools_box.addLayout(hlay_scale)
  1569. self.scale_button = QtWidgets.QPushButton(_("Scale"))
  1570. hlay_scale.addWidget(self.scale_button)
  1571. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1572. # all the add Pad array widgets
  1573. # this way I can hide/show the frame
  1574. self.array_frame = QtWidgets.QFrame()
  1575. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1576. self.custom_box.addWidget(self.array_frame)
  1577. self.array_box = QtWidgets.QVBoxLayout()
  1578. self.array_box.setContentsMargins(0, 0, 0, 0)
  1579. self.array_frame.setLayout(self.array_box)
  1580. #### Add Pad Array ####
  1581. self.emptyarray_label = QtWidgets.QLabel('')
  1582. self.array_box.addWidget(self.emptyarray_label)
  1583. self.padarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Pad Array"))
  1584. self.padarray_label.setToolTip(
  1585. _("Add an array of pads (linear or circular array)")
  1586. )
  1587. self.array_box.addWidget(self.padarray_label)
  1588. self.array_type_combo = FCComboBox()
  1589. self.array_type_combo.setToolTip(
  1590. _( "Select the type of pads array to create.\n"
  1591. "It can be Linear X(Y) or Circular")
  1592. )
  1593. self.array_type_combo.addItem(_("Linear"))
  1594. self.array_type_combo.addItem(_("Circular"))
  1595. self.array_box.addWidget(self.array_type_combo)
  1596. self.array_form = QtWidgets.QFormLayout()
  1597. self.array_box.addLayout(self.array_form)
  1598. self.pad_array_size_label = QtWidgets.QLabel(_('Nr of pads:'))
  1599. self.pad_array_size_label.setToolTip(
  1600. _("Specify how many pads to be in the array.")
  1601. )
  1602. self.pad_array_size_label.setFixedWidth(100)
  1603. self.pad_array_size_entry = LengthEntry()
  1604. self.array_form.addRow(self.pad_array_size_label, self.pad_array_size_entry)
  1605. self.array_linear_frame = QtWidgets.QFrame()
  1606. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1607. self.array_box.addWidget(self.array_linear_frame)
  1608. self.linear_box = QtWidgets.QVBoxLayout()
  1609. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1610. self.array_linear_frame.setLayout(self.linear_box)
  1611. self.linear_form = QtWidgets.QFormLayout()
  1612. self.linear_box.addLayout(self.linear_form)
  1613. self.pad_axis_label = QtWidgets.QLabel(_('Direction:'))
  1614. self.pad_axis_label.setToolTip(
  1615. _("Direction on which the linear array is oriented:\n"
  1616. "- 'X' - horizontal axis \n"
  1617. "- 'Y' - vertical axis or \n"
  1618. "- 'Angle' - a custom angle for the array inclination")
  1619. )
  1620. self.pad_axis_label.setFixedWidth(100)
  1621. self.pad_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  1622. {'label': 'Y', 'value': 'Y'},
  1623. {'label': 'Angle', 'value': 'A'}])
  1624. self.pad_axis_radio.set_value('X')
  1625. self.linear_form.addRow(self.pad_axis_label, self.pad_axis_radio)
  1626. self.pad_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1627. self.pad_pitch_label.setToolTip(
  1628. _("Pitch = Distance between elements of the array.")
  1629. )
  1630. self.pad_pitch_label.setFixedWidth(100)
  1631. self.pad_pitch_entry = LengthEntry()
  1632. self.linear_form.addRow(self.pad_pitch_label, self.pad_pitch_entry)
  1633. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1634. self.linear_angle_label.setToolTip(
  1635. _( "Angle at which the linear array is placed.\n"
  1636. "The precision is of max 2 decimals.\n"
  1637. "Min value is: -359.99 degrees.\n"
  1638. "Max value is: 360.00 degrees.")
  1639. )
  1640. self.linear_angle_label.setFixedWidth(100)
  1641. self.linear_angle_spinner = FCDoubleSpinner()
  1642. self.linear_angle_spinner.set_precision(2)
  1643. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1644. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1645. self.array_circular_frame = QtWidgets.QFrame()
  1646. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1647. self.array_box.addWidget(self.array_circular_frame)
  1648. self.circular_box = QtWidgets.QVBoxLayout()
  1649. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1650. self.array_circular_frame.setLayout(self.circular_box)
  1651. self.pad_direction_label = QtWidgets.QLabel(_('Direction:'))
  1652. self.pad_direction_label.setToolTip(
  1653. _( "Direction for circular array."
  1654. "Can be CW = clockwise or CCW = counter clockwise.")
  1655. )
  1656. self.pad_direction_label.setFixedWidth(100)
  1657. self.circular_form = QtWidgets.QFormLayout()
  1658. self.circular_box.addLayout(self.circular_form)
  1659. self.pad_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  1660. {'label': 'CCW.', 'value': 'CCW'}])
  1661. self.pad_direction_radio.set_value('CW')
  1662. self.circular_form.addRow(self.pad_direction_label, self.pad_direction_radio)
  1663. self.pad_angle_label = QtWidgets.QLabel(_('Angle:'))
  1664. self.pad_angle_label.setToolTip(
  1665. _("Angle at which each element in circular array is placed.")
  1666. )
  1667. self.pad_angle_label.setFixedWidth(100)
  1668. self.pad_angle_entry = LengthEntry()
  1669. self.circular_form.addRow(self.pad_angle_label, self.pad_angle_entry)
  1670. self.array_circular_frame.hide()
  1671. self.linear_angle_spinner.hide()
  1672. self.linear_angle_label.hide()
  1673. self.array_frame.hide()
  1674. self.custom_box.addStretch()
  1675. ## Toolbar events and properties
  1676. self.tools_gerber = {
  1677. "select": {"button": self.app.ui.grb_select_btn,
  1678. "constructor": FCApertureSelect},
  1679. "pad": {"button": self.app.ui.grb_add_pad_btn,
  1680. "constructor": FCPad},
  1681. "array": {"button": self.app.ui.add_pad_ar_btn,
  1682. "constructor": FCPadArray},
  1683. "track": {"button": self.app.ui.grb_add_track_btn,
  1684. "constructor": FCTrack},
  1685. "region": {"button": self.app.ui.grb_add_region_btn,
  1686. "constructor": FCRegion},
  1687. "poligonize": {"button": self.app.ui.grb_convert_poly_btn,
  1688. "constructor": FCPoligonize},
  1689. "semidisc": {"button": self.app.ui.grb_add_semidisc_btn,
  1690. "constructor": FCSemiDisc},
  1691. "disc": {"button": self.app.ui.grb_add_disc_btn,
  1692. "constructor": FCDisc},
  1693. "buffer": {"button": self.app.ui.aperture_buffer_btn,
  1694. "constructor": FCBuffer},
  1695. "scale": {"button": self.app.ui.aperture_scale_btn,
  1696. "constructor": FCScale},
  1697. "copy": {"button": self.app.ui.aperture_copy_btn,
  1698. "constructor": FCApertureCopy},
  1699. "transform": {"button": self.app.ui.grb_transform_btn,
  1700. "constructor": FCTransform},
  1701. "move": {"button": self.app.ui.aperture_move_btn,
  1702. "constructor": FCApertureMove},
  1703. }
  1704. ### Data
  1705. self.active_tool = None
  1706. self.storage_dict = {}
  1707. self.current_storage = []
  1708. self.sorted_apid =[]
  1709. self.new_apertures = {}
  1710. self.new_aperture_macros = {}
  1711. # store here the plot promises, if empty the delayed plot will be activated
  1712. self.grb_plot_promises = []
  1713. # dictionary to store the tool_row and aperture codes in Tool_table
  1714. # it will be updated everytime self.build_ui() is called
  1715. self.olddia_newdia = {}
  1716. self.tool2tooldia = {}
  1717. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1718. # is cleared but as a side effect also the selected tool is cleared
  1719. self.last_aperture_selected = None
  1720. self.utility = []
  1721. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1722. self.launched_from_shortcuts = False
  1723. # this var will store the state of the toolbar before starting the editor
  1724. self.toolbar_old_state = False
  1725. # holds flattened geometry
  1726. self.flat_geometry = []
  1727. # Init GUI
  1728. self.apdim_lbl.hide()
  1729. self.apdim_entry.hide()
  1730. self.gerber_obj = None
  1731. self.gerber_obj_options = {}
  1732. self.buffer_distance_entry.set_value(0.01)
  1733. self.scale_factor_entry.set_value(1.0)
  1734. # VisPy Visuals
  1735. self.shapes = self.canvas.new_shape_collection(layers=1)
  1736. self.tool_shape = self.canvas.new_shape_collection(layers=1)
  1737. self.app.pool_recreated.connect(self.pool_recreated)
  1738. # Remove from scene
  1739. self.shapes.enabled = False
  1740. self.tool_shape.enabled = False
  1741. ## List of selected shapes.
  1742. self.selected = []
  1743. self.key = None # Currently pressed key
  1744. self.modifiers = None
  1745. self.x = None # Current mouse cursor pos
  1746. self.y = None
  1747. # Current snapped mouse pos
  1748. self.snap_x = None
  1749. self.snap_y = None
  1750. self.pos = None
  1751. # used in FCRegion and FCTrack. Will store the bending mode
  1752. self.bend_mode = 1
  1753. # signal that there is an action active like polygon or path
  1754. self.in_action = False
  1755. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1756. self.launched_from_shortcuts = False
  1757. def make_callback(thetool):
  1758. def f():
  1759. self.on_tool_select(thetool)
  1760. return f
  1761. for tool in self.tools_gerber:
  1762. self.tools_gerber[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1763. self.tools_gerber[tool]["button"].setCheckable(True) # Checkable
  1764. self.options = {
  1765. "global_gridx": 0.1,
  1766. "global_gridy": 0.1,
  1767. "snap_max": 0.05,
  1768. "grid_snap": True,
  1769. "corner_snap": False,
  1770. "grid_gap_link": True
  1771. }
  1772. self.app.options_read_form()
  1773. for option in self.options:
  1774. if option in self.app.options:
  1775. self.options[option] = self.app.options[option]
  1776. # flag to show if the object was modified
  1777. self.is_modified = False
  1778. self.edited_obj_name = ""
  1779. self.tool_row = 0
  1780. # A QTimer
  1781. self.plot_thread = None
  1782. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1783. self.editor_active = False
  1784. def entry2option(option, entry):
  1785. self.options[option] = float(entry.text())
  1786. self.transform_tool = TransformEditorTool(self.app, self)
  1787. # Signals
  1788. self.buffer_button.clicked.connect(self.on_buffer)
  1789. self.scale_button.clicked.connect(self.on_scale)
  1790. self.app.ui.aperture_delete_btn.triggered.connect(self.on_delete_btn)
  1791. self.name_entry.returnPressed.connect(self.on_name_activate)
  1792. self.aptype_cb.currentIndexChanged[str].connect(self.on_aptype_changed)
  1793. self.addaperture_btn.clicked.connect(self.on_aperture_add)
  1794. self.apsize_entry.returnPressed.connect(self.on_aperture_add)
  1795. self.apdim_entry.returnPressed.connect(self.on_aperture_add)
  1796. self.delaperture_btn.clicked.connect(self.on_aperture_delete)
  1797. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1798. self.app.ui.grb_add_pad_menuitem.triggered.connect(self.on_pad_add)
  1799. self.app.ui.grb_add_pad_array_menuitem.triggered.connect(self.on_pad_add_array)
  1800. self.app.ui.grb_add_track_menuitem.triggered.connect(self.on_track_add)
  1801. self.app.ui.grb_add_region_menuitem.triggered.connect(self.on_region_add)
  1802. self.app.ui.grb_convert_poly_menuitem.triggered.connect(self.on_poligonize)
  1803. self.app.ui.grb_add_semidisc_menuitem.triggered.connect(self.on_add_semidisc)
  1804. self.app.ui.grb_add_disc_menuitem.triggered.connect(self.on_disc_add)
  1805. self.app.ui.grb_add_buffer_menuitem.triggered.connect(self.on_buffer)
  1806. self.app.ui.grb_add_scale_menuitem.triggered.connect(self.on_scale)
  1807. self.app.ui.grb_transform_menuitem.triggered.connect(self.transform_tool.run)
  1808. self.app.ui.grb_copy_menuitem.triggered.connect(self.on_copy_button)
  1809. self.app.ui.grb_delete_menuitem.triggered.connect(self.on_delete_btn)
  1810. self.app.ui.grb_move_menuitem.triggered.connect(self.on_move_button)
  1811. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1812. self.pad_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1813. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1814. self.editor_active = False
  1815. def pool_recreated(self, pool):
  1816. self.shapes.pool = pool
  1817. self.tool_shape.pool = pool
  1818. def set_ui(self):
  1819. # updated units
  1820. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1821. self.olddia_newdia.clear()
  1822. self.tool2tooldia.clear()
  1823. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1824. for key in self.storage_dict:
  1825. self.olddia_newdia[key] = key
  1826. sort_temp = []
  1827. for aperture in self.olddia_newdia:
  1828. sort_temp.append(int(aperture))
  1829. self.sorted_apid = sorted(sort_temp)
  1830. # populate self.intial_table_rows dict with the tool number as keys and aperture codes as values
  1831. for i in range(len(self.sorted_apid)):
  1832. tt_aperture = self.sorted_apid[i]
  1833. self.tool2tooldia[i + 1] = tt_aperture
  1834. if self.units == "IN":
  1835. self.apsize_entry.set_value(0.039)
  1836. else:
  1837. self.apsize_entry.set_value(1.00)
  1838. # Init GUI
  1839. self.pad_array_size_entry.set_value(5)
  1840. self.pad_pitch_entry.set_value(2.54)
  1841. self.pad_angle_entry.set_value(12)
  1842. self.pad_direction_radio.set_value('CW')
  1843. self.pad_axis_radio.set_value('X')
  1844. def build_ui(self, first_run=None):
  1845. try:
  1846. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1847. self.apertures_table.itemChanged.disconnect()
  1848. except:
  1849. pass
  1850. try:
  1851. self.apertures_table.cellPressed.disconnect()
  1852. except:
  1853. pass
  1854. # updated units
  1855. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1856. # make a new name for the new Excellon object (the one with edited content)
  1857. self.edited_obj_name = self.gerber_obj.options['name']
  1858. self.name_entry.set_value(self.edited_obj_name)
  1859. self.apertures_row = 0
  1860. aper_no = self.apertures_row + 1
  1861. sort = []
  1862. for k, v in list(self.storage_dict.items()):
  1863. sort.append(int(k))
  1864. sorted_apertures = sorted(sort)
  1865. sort = []
  1866. for k, v in list(self.gerber_obj.aperture_macros.items()):
  1867. sort.append(k)
  1868. sorted_macros = sorted(sort)
  1869. n = len(sorted_apertures) + len(sorted_macros)
  1870. self.apertures_table.setRowCount(n)
  1871. for ap_code in sorted_apertures:
  1872. ap_code = str(ap_code)
  1873. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1874. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1875. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1876. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1877. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1878. ap_type_item = QtWidgets.QTableWidgetItem(str(self.storage_dict[ap_code]['type']))
  1879. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1880. if str(self.storage_dict[ap_code]['type']) == 'R' or str(self.storage_dict[ap_code]['type']) == 'O':
  1881. ap_dim_item = QtWidgets.QTableWidgetItem(
  1882. '%.4f, %.4f' % (self.storage_dict[ap_code]['width'],
  1883. self.storage_dict[ap_code]['height']
  1884. )
  1885. )
  1886. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1887. elif str(self.storage_dict[ap_code]['type']) == 'P':
  1888. ap_dim_item = QtWidgets.QTableWidgetItem(
  1889. '%.4f, %.4f' % (self.storage_dict[ap_code]['diam'],
  1890. self.storage_dict[ap_code]['nVertices'])
  1891. )
  1892. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1893. else:
  1894. ap_dim_item = QtWidgets.QTableWidgetItem('')
  1895. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1896. try:
  1897. if self.storage_dict[ap_code]['size'] is not None:
  1898. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  1899. float(self.storage_dict[ap_code]['size']))
  1900. else:
  1901. ap_size_item = QtWidgets.QTableWidgetItem('')
  1902. except KeyError:
  1903. ap_size_item = QtWidgets.QTableWidgetItem('')
  1904. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1905. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1906. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1907. self.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  1908. self.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  1909. self.apertures_row += 1
  1910. if first_run is True:
  1911. # set now the last aperture selected
  1912. self.last_aperture_selected = ap_code
  1913. for ap_code in sorted_macros:
  1914. ap_code = str(ap_code)
  1915. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  1916. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1917. self.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  1918. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  1919. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  1920. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1921. self.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  1922. self.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  1923. self.apertures_row += 1
  1924. if first_run is True:
  1925. # set now the last aperture selected
  1926. self.last_aperture_selected = ap_code
  1927. self.apertures_table.selectColumn(0)
  1928. self.apertures_table.resizeColumnsToContents()
  1929. self.apertures_table.resizeRowsToContents()
  1930. vertical_header = self.apertures_table.verticalHeader()
  1931. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1932. vertical_header.hide()
  1933. self.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1934. horizontal_header = self.apertures_table.horizontalHeader()
  1935. horizontal_header.setMinimumSectionSize(10)
  1936. horizontal_header.setDefaultSectionSize(70)
  1937. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1938. horizontal_header.resizeSection(0, 20)
  1939. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  1940. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1941. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1942. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  1943. self.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1944. self.apertures_table.setSortingEnabled(False)
  1945. self.apertures_table.setMinimumHeight(self.apertures_table.getHeight())
  1946. self.apertures_table.setMaximumHeight(self.apertures_table.getHeight())
  1947. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1948. self.apertures_table.clearSelection()
  1949. # Remove anything else in the GUI Selected Tab
  1950. self.app.ui.selected_scroll_area.takeWidget()
  1951. # Put ourself in the GUI Selected Tab
  1952. self.app.ui.selected_scroll_area.setWidget(self.grb_edit_widget)
  1953. # Switch notebook to Selected page
  1954. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1955. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1956. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  1957. self.apertures_table.cellPressed.connect(self.on_row_selected)
  1958. # for convenience set the next aperture code in the apcode field
  1959. try:
  1960. self.apcode_entry.set_value(max(self.tool2tooldia.values()) + 1)
  1961. except ValueError:
  1962. # this means that the edited object has no apertures so we start with 10 (Gerber specifications)
  1963. self.apcode_entry.set_value(10)
  1964. def on_aperture_add(self, apid=None):
  1965. self.is_modified = True
  1966. if apid:
  1967. ap_id = apid
  1968. else:
  1969. try:
  1970. ap_id = str(self.apcode_entry.get_value())
  1971. except ValueError:
  1972. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1973. "Add it and retry."))
  1974. return
  1975. if ap_id == '':
  1976. self.app.inform.emit(_("[WARNING_NOTCL] Aperture code value is missing or wrong format. "
  1977. "Add it and retry."))
  1978. return
  1979. if ap_id == '0':
  1980. if ap_id not in self.tool2tooldia:
  1981. self.storage_dict[ap_id] = {}
  1982. self.storage_dict[ap_id]['type'] = 'REG'
  1983. size_val = 0
  1984. self.apsize_entry.set_value(size_val)
  1985. self.storage_dict[ap_id]['size'] = size_val
  1986. self.storage_dict[ap_id]['solid_geometry'] = []
  1987. self.storage_dict[ap_id]['follow_geometry'] = []
  1988. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  1989. # each time a aperture code is edited or added
  1990. self.olddia_newdia[ap_id] = ap_id
  1991. else:
  1992. if ap_id not in self.olddia_newdia:
  1993. self.storage_dict[ap_id] = {}
  1994. type_val = self.aptype_cb.currentText()
  1995. self.storage_dict[ap_id]['type'] = type_val
  1996. if type_val == 'R' or type_val == 'O':
  1997. try:
  1998. dims = self.apdim_entry.get_value()
  1999. self.storage_dict[ap_id]['width'] = dims[0]
  2000. self.storage_dict[ap_id]['height'] = dims[1]
  2001. size_val = math.sqrt((dims[0] ** 2) + (dims[1] ** 2))
  2002. self.apsize_entry.set_value(size_val)
  2003. except Exception as e:
  2004. log.error("FlatCAMGrbEditor.on_aperture_add() --> the R or O aperture dims has to be in a "
  2005. "tuple format (x,y)\nError: %s" % str(e))
  2006. self.app.inform.emit(_("[WARNING_NOTCL] Aperture dimensions value is missing or wrong format. "
  2007. "Add it in format (width, height) and retry."))
  2008. return
  2009. else:
  2010. try:
  2011. size_val = float(self.apsize_entry.get_value())
  2012. except ValueError:
  2013. # try to convert comma to decimal point. if it's still not working error message and return
  2014. try:
  2015. size_val = float(self.apsize_entry.get_value().replace(',', '.'))
  2016. self.apsize_entry.set_value(size_val)
  2017. except ValueError:
  2018. self.app.inform.emit(_("[WARNING_NOTCL] Aperture size value is missing or wrong format. "
  2019. "Add it and retry."))
  2020. return
  2021. self.storage_dict[ap_id]['size'] = size_val
  2022. self.storage_dict[ap_id]['solid_geometry'] = []
  2023. self.storage_dict[ap_id]['follow_geometry'] = []
  2024. # self.olddia_newdia dict keeps the evidence on current aperture codes as keys and gets updated on values
  2025. # each time a aperture code is edited or added
  2026. self.olddia_newdia[ap_id] = ap_id
  2027. else:
  2028. self.app.inform.emit(_("[WARNING_NOTCL] Aperture already in the aperture table."))
  2029. return
  2030. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  2031. # we add a new entry in the tool2tooldia dict
  2032. self.tool2tooldia[len(self.olddia_newdia)] = int(ap_id)
  2033. self.app.inform.emit(_("[success] Added new aperture with code: {apid}").format(apid=str(ap_id)))
  2034. self.build_ui()
  2035. self.last_aperture_selected = ap_id
  2036. # make a quick sort through the tool2tooldia dict so we find which row to select
  2037. row_to_be_selected = None
  2038. for key in sorted(self.tool2tooldia):
  2039. if self.tool2tooldia[key] == int(ap_id):
  2040. row_to_be_selected = int(key) - 1
  2041. break
  2042. self.apertures_table.selectRow(row_to_be_selected)
  2043. def on_aperture_delete(self, apid=None):
  2044. self.is_modified = True
  2045. deleted_apcode_list = []
  2046. deleted_tool_offset_list = []
  2047. try:
  2048. if apid:
  2049. if isinstance(apid, list):
  2050. for dd in apid:
  2051. deleted_apcode_list.append(dd)
  2052. else:
  2053. deleted_apcode_list.append(apid)
  2054. else:
  2055. # deleted_tool_dia = float(self.apertures_table.item(self.apertures_table.currentRow(), 1).text())
  2056. if len(self.apertures_table.selectionModel().selectedRows()) == 0:
  2057. self.app.inform.emit(_("[WARNING_NOTCL] Select an aperture in Aperture Table"))
  2058. return
  2059. for index in self.apertures_table.selectionModel().selectedRows():
  2060. row = index.row()
  2061. deleted_apcode_list.append(self.apertures_table.item(row, 1).text())
  2062. except:
  2063. self.app.inform.emit(_("[WARNING_NOTCL] Select an aperture in Aperture Table"))
  2064. return
  2065. if deleted_apcode_list:
  2066. for deleted_aperture in deleted_apcode_list:
  2067. # delete the storage used for that tool
  2068. self.storage_dict.pop(deleted_aperture, None)
  2069. # I've added this flag_del variable because dictionary don't like
  2070. # having keys deleted while iterating through them
  2071. flag_del = []
  2072. for deleted_tool in self.tool2tooldia:
  2073. if self.tool2tooldia[deleted_tool] == deleted_aperture:
  2074. flag_del.append(deleted_tool)
  2075. if flag_del:
  2076. for aperture_to_be_deleted in flag_del:
  2077. # delete the tool
  2078. self.tool2tooldia.pop(aperture_to_be_deleted, None)
  2079. flag_del = []
  2080. self.olddia_newdia.pop(deleted_aperture, None)
  2081. self.app.inform.emit(_("[success] Deleted aperture with code: {del_dia}").format(
  2082. del_dia=str(deleted_aperture)))
  2083. self.plot_all()
  2084. self.build_ui()
  2085. # if last aperture selected was in the apertures deleted than make sure to select a 'new' last aperture selected
  2086. # because there are tools who depend on it.
  2087. # if there is no aperture left, then add a default one :)
  2088. if self.last_aperture_selected in deleted_apcode_list:
  2089. if self.apertures_table.rowCount() == 0:
  2090. self.on_aperture_add('10')
  2091. else:
  2092. self.last_aperture_selected = self.apertures_table.item(0, 1).text()
  2093. def on_tool_edit(self, item_changed):
  2094. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2095. self.apertures_table.itemChanged.disconnect()
  2096. # self.apertures_table.cellPressed.disconnect()
  2097. self.is_modified = True
  2098. geometry = []
  2099. current_table_dia_edited = None
  2100. if self.apertures_table.currentItem() is not None:
  2101. try:
  2102. current_table_dia_edited = float(self.apertures_table.currentItem().text())
  2103. except ValueError as e:
  2104. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  2105. self.apertures_table.setCurrentItem(None)
  2106. return
  2107. row_of_item_changed = self.apertures_table.currentRow()
  2108. # rows start with 0, tools start with 1 so we adjust the value by 1
  2109. key_in_tool2tooldia = row_of_item_changed + 1
  2110. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  2111. # aperture code is not used so we create a new tool with the desired diameter
  2112. if current_table_dia_edited not in self.olddia_newdia.values():
  2113. # update the dict that holds as keys our initial diameters and as values the edited diameters
  2114. self.olddia_newdia[dia_changed] = current_table_dia_edited
  2115. # update the dict that holds tool_no as key and tool_dia as value
  2116. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  2117. # update the tool offset
  2118. modified_offset = self.gerber_obj.tool_offset.pop(dia_changed)
  2119. self.gerber_obj.tool_offset[current_table_dia_edited] = modified_offset
  2120. self.plot_all()
  2121. else:
  2122. # aperture code is already in use so we move the pads from the prior tool to the new tool
  2123. factor = current_table_dia_edited / dia_changed
  2124. for shape in self.storage_dict[dia_changed].get_objects():
  2125. geometry.append(DrawToolShape(
  2126. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  2127. self.points_edit[current_table_dia_edited].append((0, 0))
  2128. self.add_gerber_shape(geometry, self.storage_dict[current_table_dia_edited])
  2129. self.on_aperture_delete(apid=dia_changed)
  2130. # delete the tool offset
  2131. self.gerber_obj.tool_offset.pop(dia_changed, None)
  2132. # we reactivate the signals after the after the tool editing
  2133. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  2134. # self.apertures_table.cellPressed.connect(self.on_row_selected)
  2135. def on_name_activate(self):
  2136. self.edited_obj_name = self.name_entry.get_value()
  2137. def on_aptype_changed(self, current_text):
  2138. # 'O' is letter O not zero.
  2139. if current_text == 'R' or current_text == 'O':
  2140. self.apdim_lbl.show()
  2141. self.apdim_entry.show()
  2142. self.apsize_entry.setDisabled(True)
  2143. else:
  2144. self.apdim_lbl.hide()
  2145. self.apdim_entry.hide()
  2146. self.apsize_entry.setDisabled(False)
  2147. def activate_grb_editor(self):
  2148. # adjust the status of the menu entries related to the editor
  2149. self.app.ui.menueditedit.setDisabled(True)
  2150. self.app.ui.menueditok.setDisabled(False)
  2151. # adjust the visibility of some of the canvas context menu
  2152. self.app.ui.popmenu_edit.setVisible(False)
  2153. self.app.ui.popmenu_save.setVisible(True)
  2154. self.connect_canvas_event_handlers()
  2155. # init working objects
  2156. self.storage_dict = {}
  2157. self.current_storage = []
  2158. self.sorted_apid = []
  2159. self.new_apertures = {}
  2160. self.new_aperture_macros = {}
  2161. self.grb_plot_promises = []
  2162. self.olddia_newdia = {}
  2163. self.tool2tooldia = {}
  2164. self.shapes.enabled = True
  2165. self.tool_shape.enabled = True
  2166. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2167. self.app.ui.corner_snap_btn.setEnabled(True)
  2168. self.app.ui.snap_magnet.setVisible(True)
  2169. self.app.ui.corner_snap_btn.setVisible(True)
  2170. self.app.ui.grb_editor_menu.setDisabled(False)
  2171. self.app.ui.grb_editor_menu.menuAction().setVisible(True)
  2172. self.app.ui.update_obj_btn.setEnabled(True)
  2173. self.app.ui.grb_editor_cmenu.setEnabled(True)
  2174. self.app.ui.grb_edit_toolbar.setDisabled(False)
  2175. self.app.ui.grb_edit_toolbar.setVisible(True)
  2176. # self.app.ui.snap_toolbar.setDisabled(False)
  2177. # start with GRID toolbar activated
  2178. if self.app.ui.grid_snap_btn.isChecked() is False:
  2179. self.app.ui.grid_snap_btn.trigger()
  2180. # adjust the visibility of some of the canvas context menu
  2181. self.app.ui.popmenu_edit.setVisible(False)
  2182. self.app.ui.popmenu_save.setVisible(True)
  2183. self.app.ui.popmenu_disable.setVisible(False)
  2184. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2185. self.app.ui.popmenu_properties.setVisible(False)
  2186. self.app.ui.grb_editor_cmenu.menuAction().setVisible(True)
  2187. # Tell the App that the editor is active
  2188. self.editor_active = True
  2189. def deactivate_grb_editor(self):
  2190. try:
  2191. QtGui.QGuiApplication.restoreOverrideCursor()
  2192. except:
  2193. pass
  2194. # adjust the status of the menu entries related to the editor
  2195. self.app.ui.menueditedit.setDisabled(False)
  2196. self.app.ui.menueditok.setDisabled(True)
  2197. # adjust the visibility of some of the canvas context menu
  2198. self.app.ui.popmenu_edit.setVisible(True)
  2199. self.app.ui.popmenu_save.setVisible(False)
  2200. self.disconnect_canvas_event_handlers()
  2201. self.clear()
  2202. self.app.ui.grb_edit_toolbar.setDisabled(True)
  2203. settings = QSettings("Open Source", "FlatCAM")
  2204. if settings.contains("layout"):
  2205. layout = settings.value('layout', type=str)
  2206. if layout == 'standard':
  2207. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2208. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2209. self.app.ui.corner_snap_btn.setEnabled(False)
  2210. self.app.ui.snap_magnet.setVisible(False)
  2211. self.app.ui.corner_snap_btn.setVisible(False)
  2212. elif layout == 'compact':
  2213. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2214. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2215. self.app.ui.corner_snap_btn.setEnabled(False)
  2216. self.app.ui.snap_magnet.setVisible(True)
  2217. self.app.ui.corner_snap_btn.setVisible(True)
  2218. else:
  2219. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2220. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2221. self.app.ui.corner_snap_btn.setEnabled(False)
  2222. self.app.ui.snap_magnet.setVisible(False)
  2223. self.app.ui.corner_snap_btn.setVisible(False)
  2224. # set the Editor Toolbar visibility to what was before entering in the Editor
  2225. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2226. else self.app.ui.grb_edit_toolbar.setVisible(True)
  2227. # Disable visuals
  2228. self.shapes.enabled = False
  2229. self.tool_shape.enabled = False
  2230. # self.app.app_cursor.enabled = False
  2231. # Tell the app that the editor is no longer active
  2232. self.editor_active = False
  2233. self.app.ui.grb_editor_menu.setDisabled(True)
  2234. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  2235. self.app.ui.update_obj_btn.setEnabled(False)
  2236. # adjust the visibility of some of the canvas context menu
  2237. self.app.ui.popmenu_edit.setVisible(True)
  2238. self.app.ui.popmenu_save.setVisible(False)
  2239. self.app.ui.popmenu_disable.setVisible(True)
  2240. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2241. self.app.ui.popmenu_properties.setVisible(True)
  2242. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2243. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2244. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2245. # Show original geometry
  2246. if self.gerber_obj:
  2247. self.gerber_obj.visible = True
  2248. def connect_canvas_event_handlers(self):
  2249. ## Canvas events
  2250. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2251. # but those from FlatCAMGeoEditor
  2252. # first connect to new, then disconnect the old handlers
  2253. # don't ask why but if there is nothing connected I've seen issues
  2254. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2255. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2256. self.canvas.vis_connect('mouse_release', self.on_grb_click_release)
  2257. self.canvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2258. self.canvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2259. self.canvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2260. self.canvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2261. self.app.collection.view.clicked.disconnect()
  2262. self.app.ui.popmenu_copy.triggered.disconnect()
  2263. self.app.ui.popmenu_delete.triggered.disconnect()
  2264. self.app.ui.popmenu_move.triggered.disconnect()
  2265. self.app.ui.popmenu_copy.triggered.connect(self.on_copy_button)
  2266. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2267. self.app.ui.popmenu_move.triggered.connect(self.on_move_button)
  2268. # Gerber Editor
  2269. self.app.ui.grb_draw_pad.triggered.connect(self.on_pad_add)
  2270. self.app.ui.grb_draw_pad_array.triggered.connect(self.on_pad_add_array)
  2271. self.app.ui.grb_draw_track.triggered.connect(self.on_track_add)
  2272. self.app.ui.grb_draw_region.triggered.connect(self.on_region_add)
  2273. def disconnect_canvas_event_handlers(self):
  2274. # we restore the key and mouse control to FlatCAMApp method
  2275. # first connect to new, then disconnect the old handlers
  2276. # don't ask why but if there is nothing connected I've seen issues
  2277. self.canvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2278. self.canvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2279. self.canvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2280. self.canvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2281. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2282. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2283. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2284. self.canvas.vis_disconnect('mouse_release', self.on_grb_click_release)
  2285. try:
  2286. self.app.ui.popmenu_copy.triggered.disconnect(self.on_copy_button)
  2287. except TypeError:
  2288. pass
  2289. try:
  2290. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2291. except TypeError:
  2292. pass
  2293. try:
  2294. self.app.ui.popmenu_move.triggered.disconnect(self.on_move_button)
  2295. except TypeError:
  2296. pass
  2297. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2298. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2299. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2300. # Gerber Editor
  2301. try:
  2302. self.app.ui.grb_draw_pad.triggered.disconnect(self.on_pad_add)
  2303. except TypeError:
  2304. pass
  2305. try:
  2306. self.app.ui.grb_draw_pad_array.triggered.disconnect(self.on_pad_add_array)
  2307. except TypeError:
  2308. pass
  2309. try:
  2310. self.app.ui.grb_draw_track.triggered.disconnect(self.on_track_add)
  2311. except TypeError:
  2312. pass
  2313. try:
  2314. self.app.ui.grb_draw_region.triggered.disconnect(self.on_region_add)
  2315. except TypeError:
  2316. pass
  2317. def clear(self):
  2318. self.active_tool = None
  2319. # self.shape_buffer = []
  2320. self.selected = []
  2321. self.shapes.clear(update=True)
  2322. self.tool_shape.clear(update=True)
  2323. def flatten(self, geometry=None, reset=True, pathonly=False):
  2324. """
  2325. Creates a list of non-iterable linear geometry objects.
  2326. Polygons are expanded into its exterior pathonly param if specified.
  2327. Results are placed in flat_geometry
  2328. :param geometry: Shapely type or list or list of list of such.
  2329. :param reset: Clears the contents of self.flat_geometry.
  2330. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  2331. """
  2332. if reset:
  2333. self.flat_geometry = []
  2334. ## If iterable, expand recursively.
  2335. try:
  2336. for geo in geometry:
  2337. if geo is not None:
  2338. self.flatten(geometry=geo, reset=False, pathonly=pathonly)
  2339. ## Not iterable, do the actual indexing and add.
  2340. except TypeError:
  2341. if pathonly and type(geometry) == Polygon:
  2342. self.flat_geometry.append(geometry.exterior)
  2343. self.flatten(geometry=geometry.interiors,
  2344. reset=False,
  2345. pathonly=True)
  2346. else:
  2347. self.flat_geometry.append(geometry)
  2348. return self.flat_geometry
  2349. def edit_fcgerber(self, orig_grb_obj):
  2350. """
  2351. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  2352. into the editor.
  2353. :param fcgeometry: FlatCAMExcellon
  2354. :return: None
  2355. """
  2356. self.deactivate_grb_editor()
  2357. self.activate_grb_editor()
  2358. # create a reference to the source object
  2359. self.gerber_obj = orig_grb_obj
  2360. self.gerber_obj_options = orig_grb_obj.options
  2361. # Hide original geometry
  2362. orig_grb_obj.visible = False
  2363. # Set selection tolerance
  2364. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2365. self.select_tool("select")
  2366. # we activate this after the initial build as we don't need to see the tool been populated
  2367. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  2368. # and then add it to the storage elements (each storage elements is a member of a list
  2369. def job_thread(self, apid):
  2370. with self.app.proc_container.new(_("Adding aperture: %s geo ...") % str(apid)):
  2371. solid_storage_elem = []
  2372. follow_storage_elem = []
  2373. self.storage_dict[apid] = {}
  2374. # add the Gerber geometry to editor storage
  2375. for k, v in self.gerber_obj.apertures[apid].items():
  2376. try:
  2377. if k == 'solid_geometry':
  2378. for geo in v:
  2379. if geo:
  2380. self.add_gerber_shape(DrawToolShape(geo), solid_storage_elem)
  2381. self.storage_dict[apid][k] = solid_storage_elem
  2382. elif k == 'follow_geometry':
  2383. for geo in v:
  2384. if geo is not None:
  2385. self.add_gerber_shape(DrawToolShape(geo), follow_storage_elem)
  2386. self.storage_dict[apid][k] = follow_storage_elem
  2387. else:
  2388. self.storage_dict[apid][k] = v
  2389. except Exception as e:
  2390. log.debug("FlatCAMGrbEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  2391. # Check promises and clear if exists
  2392. while True:
  2393. try:
  2394. self.grb_plot_promises.remove(apid)
  2395. time.sleep(0.5)
  2396. except ValueError:
  2397. break
  2398. for apid in self.gerber_obj.apertures:
  2399. self.grb_plot_promises.append(apid)
  2400. self.app.worker_task.emit({'fcn': job_thread, 'params': [self, apid]})
  2401. # do the delayed plot only if there is something to plot (the gerber is not empty)
  2402. if bool(self.gerber_obj.apertures):
  2403. self.start_delayed_plot(check_period=1000)
  2404. else:
  2405. self.set_ui()
  2406. # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  2407. self.build_ui(first_run=True)
  2408. # and add the first aperture to have something to play with
  2409. self.on_aperture_add('10')
  2410. def update_fcgerber(self, grb_obj):
  2411. """
  2412. Create a new Gerber object that contain the edited content of the source Gerber object
  2413. :param grb_obj: FlatCAMGerber
  2414. :return: None
  2415. """
  2416. new_grb_name = self.edited_obj_name
  2417. # if the 'delayed plot' malfunctioned stop the QTimer
  2418. try:
  2419. self.plot_thread.stop()
  2420. except:
  2421. pass
  2422. if "_edit" in self.edited_obj_name:
  2423. try:
  2424. id = int(self.edited_obj_name[-1]) + 1
  2425. new_grb_name= self.edited_obj_name[:-1] + str(id)
  2426. except ValueError:
  2427. new_grb_name += "_1"
  2428. else:
  2429. new_grb_name = self.edited_obj_name + "_edit"
  2430. self.app.worker_task.emit({'fcn': self.new_edited_gerber,
  2431. 'params': [new_grb_name]})
  2432. # reset the tool table
  2433. self.apertures_table.clear()
  2434. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  2435. self.last_aperture_selected = None
  2436. # restore GUI to the Selected TAB
  2437. # Remove anything else in the GUI
  2438. self.app.ui.selected_scroll_area.takeWidget()
  2439. # Switch notebook to Selected page
  2440. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2441. def update_options(self, obj):
  2442. try:
  2443. if not obj.options:
  2444. obj.options = {}
  2445. obj.options['xmin'] = 0
  2446. obj.options['ymin'] = 0
  2447. obj.options['xmax'] = 0
  2448. obj.options['ymax'] = 0
  2449. return True
  2450. else:
  2451. return False
  2452. except AttributeError:
  2453. obj.options = {}
  2454. return True
  2455. def new_edited_gerber(self, outname):
  2456. """
  2457. Creates a new Gerber object for the edited Gerber. Thread-safe.
  2458. :param outname: Name of the resulting object. None causes the name to be that of the file.
  2459. :type outname: str
  2460. :return: None
  2461. """
  2462. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  2463. self.gerber_obj.options['name'].upper())
  2464. out_name = outname
  2465. local_storage_dict = deepcopy(self.storage_dict)
  2466. # How the object should be initialized
  2467. def obj_init(grb_obj, app_obj):
  2468. poly_buffer = []
  2469. follow_buffer = []
  2470. for storage_apid, storage_val in local_storage_dict.items():
  2471. grb_obj.apertures[storage_apid] = {}
  2472. for k, v in storage_val.items():
  2473. if k == 'solid_geometry':
  2474. grb_obj.apertures[storage_apid][k] = []
  2475. for geo in v:
  2476. new_geo = deepcopy(geo.geo)
  2477. grb_obj.apertures[storage_apid][k].append(new_geo)
  2478. poly_buffer.append(new_geo)
  2479. elif k == 'follow_geometry':
  2480. grb_obj.apertures[storage_apid][k] = []
  2481. for geo in v:
  2482. new_geo = deepcopy(geo.geo)
  2483. grb_obj.apertures[storage_apid][k].append(new_geo)
  2484. follow_buffer.append(new_geo)
  2485. else:
  2486. grb_obj.apertures[storage_apid][k] = deepcopy(v)
  2487. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  2488. new_poly = MultiPolygon(poly_buffer)
  2489. new_poly = new_poly.buffer(0.00000001)
  2490. new_poly = new_poly.buffer(-0.00000001)
  2491. grb_obj.solid_geometry = new_poly
  2492. grb_obj.follow_geometry = deepcopy(follow_buffer)
  2493. for k, v in self.gerber_obj_options.items():
  2494. if k == 'name':
  2495. grb_obj.options[k] = out_name
  2496. else:
  2497. grb_obj.options[k] = deepcopy(v)
  2498. grb_obj.source_file = []
  2499. grb_obj.multigeo = False
  2500. grb_obj.follow = False
  2501. try:
  2502. grb_obj.create_geometry()
  2503. except KeyError:
  2504. self.app.inform.emit(
  2505. _( "[ERROR_NOTCL] There are no Aperture definitions in the file. Aborting Gerber creation.")
  2506. )
  2507. except:
  2508. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2509. msg += traceback.format_exc()
  2510. app_obj.inform.emit(msg)
  2511. raise
  2512. # raise
  2513. with self.app.proc_container.new(_("Creating Gerber.")):
  2514. try:
  2515. self.app.new_object("gerber", outname, obj_init)
  2516. except Exception as e:
  2517. log.error("Error on object creation: %s" % str(e))
  2518. self.app.progress.emit(100)
  2519. return
  2520. self.app.inform.emit(_("[success] Gerber editing finished."))
  2521. # self.progress.emit(100)
  2522. def on_tool_select(self, tool):
  2523. """
  2524. Behavior of the toolbar. Tool initialization.
  2525. :rtype : None
  2526. """
  2527. current_tool = tool
  2528. self.app.log.debug("on_tool_select('%s')" % tool)
  2529. if self.last_aperture_selected is None and current_tool is not 'select':
  2530. # self.draw_app.select_tool('select')
  2531. self.complete = True
  2532. current_tool = 'select'
  2533. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No aperture is selected"))
  2534. # This is to make the group behave as radio group
  2535. if current_tool in self.tools_gerber:
  2536. if self.tools_gerber[current_tool]["button"].isChecked():
  2537. self.app.log.debug("%s is checked." % current_tool)
  2538. for t in self.tools_gerber:
  2539. if t != current_tool:
  2540. self.tools_gerber[t]["button"].setChecked(False)
  2541. # this is where the Editor toolbar classes (button's) are instantiated
  2542. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  2543. # self.app.inform.emit(self.active_tool.start_msg)
  2544. else:
  2545. self.app.log.debug("%s is NOT checked." % current_tool)
  2546. for t in self.tools_gerber:
  2547. self.tools_gerber[t]["button"].setChecked(False)
  2548. self.select_tool('select')
  2549. self.active_tool = FCApertureSelect(self)
  2550. def on_row_selected(self, row, col):
  2551. if col == 0:
  2552. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2553. if self.app.defaults["global_mselect_key"] == 'Control':
  2554. modifier_to_use = Qt.ControlModifier
  2555. else:
  2556. modifier_to_use = Qt.ShiftModifier
  2557. if key_modifier == modifier_to_use:
  2558. pass
  2559. else:
  2560. self.selected = []
  2561. try:
  2562. # selected_apid = str(self.tool2tooldia[row + 1])
  2563. selected_apid = self.apertures_table.item(row, 1).text()
  2564. self.last_aperture_selected = copy(selected_apid)
  2565. for obj in self.storage_dict[selected_apid]['solid_geometry']:
  2566. self.selected.append(obj)
  2567. except Exception as e:
  2568. self.app.log.debug(str(e))
  2569. self.plot_all()
  2570. def toolbar_tool_toggle(self, key):
  2571. self.options[key] = self.sender().isChecked()
  2572. return self.options[key]
  2573. def on_grb_shape_complete(self, storage=None, specific_shape=None):
  2574. self.app.log.debug("on_shape_complete()")
  2575. if specific_shape:
  2576. geo = specific_shape
  2577. else:
  2578. geo = self.active_tool.geometry
  2579. if geo is None:
  2580. return
  2581. if storage is not None:
  2582. # Add shape
  2583. self.add_gerber_shape(geo, storage)
  2584. else:
  2585. stora = self.storage_dict[self.last_aperture_selected]['solid_geometry']
  2586. self.add_gerber_shape(geo, storage=stora)
  2587. # Remove any utility shapes
  2588. self.delete_utility_geometry()
  2589. self.tool_shape.clear(update=True)
  2590. # Replot and reset tool.
  2591. self.plot_all()
  2592. def add_gerber_shape(self, shape, storage):
  2593. """
  2594. Adds a shape to the shape storage.
  2595. :param shape: Shape to be added.
  2596. :type shape: DrawToolShape
  2597. :return: None
  2598. """
  2599. # List of DrawToolShape?
  2600. if isinstance(shape, list):
  2601. for subshape in shape:
  2602. self.add_gerber_shape(subshape, storage)
  2603. return
  2604. assert isinstance(shape, DrawToolShape), \
  2605. "Expected a DrawToolShape, got %s" % str(type(shape))
  2606. assert shape.geo is not None, \
  2607. "Shape object has empty geometry (None)"
  2608. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2609. not isinstance(shape.geo, list), \
  2610. "Shape objects has empty geometry ([])"
  2611. if isinstance(shape, DrawToolUtilityShape):
  2612. self.utility.append(shape)
  2613. else:
  2614. storage.append(shape) # TODO: Check performance
  2615. def on_canvas_click(self, event):
  2616. """
  2617. event.x and .y have canvas coordinates
  2618. event.xdata and .ydata have plot coordinates
  2619. :param event: Event object dispatched by VisPy
  2620. :return: None
  2621. """
  2622. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2623. if self.app.grid_status():
  2624. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2625. self.app.app_cursor.enabled = True
  2626. # Update cursor
  2627. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2628. size=20)
  2629. else:
  2630. self.pos = (self.pos[0], self.pos[1])
  2631. self.app.app_cursor.enabled = False
  2632. if event.button is 1:
  2633. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2634. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2635. # Selection with left mouse button
  2636. if self.active_tool is not None and event.button is 1:
  2637. # Dispatch event to active_tool
  2638. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2639. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2640. # If it is a shape generating tool
  2641. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2642. if self.current_storage is not None:
  2643. self.on_grb_shape_complete(self.current_storage)
  2644. self.build_ui()
  2645. # MS: always return to the Select Tool if modifier key is not pressed
  2646. # else return to the current tool
  2647. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2648. if self.app.defaults["global_mselect_key"] == 'Control':
  2649. modifier_to_use = Qt.ControlModifier
  2650. else:
  2651. modifier_to_use = Qt.ShiftModifier
  2652. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2653. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2654. if key_modifier == modifier_to_use:
  2655. self.select_tool(self.active_tool.name)
  2656. else:
  2657. # return to Select tool but not for FCPad
  2658. if isinstance(self.active_tool, FCPad):
  2659. self.select_tool(self.active_tool.name)
  2660. else:
  2661. self.select_tool("select")
  2662. return
  2663. if isinstance(self.active_tool, FCApertureSelect):
  2664. # self.app.log.debug("Replotting after click.")
  2665. self.plot_all()
  2666. else:
  2667. self.app.log.debug("No active tool to respond to click!")
  2668. def on_grb_click_release(self, event):
  2669. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2670. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2671. if self.app.grid_status():
  2672. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2673. else:
  2674. pos = (pos_canvas[0], pos_canvas[1])
  2675. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2676. # canvas menu
  2677. try:
  2678. if event.button == 2: # right click
  2679. if self.app.ui.popMenu.mouse_is_panning is False:
  2680. if self.in_action is False:
  2681. try:
  2682. QtGui.QGuiApplication.restoreOverrideCursor()
  2683. except:
  2684. pass
  2685. if self.active_tool.complete is False and not isinstance(self.active_tool, FCApertureSelect):
  2686. self.active_tool.complete = True
  2687. self.in_action = False
  2688. self.delete_utility_geometry()
  2689. self.app.inform.emit(_("[success] Done."))
  2690. self.select_tool('select')
  2691. else:
  2692. self.app.cursor = QtGui.QCursor()
  2693. self.app.populate_cmenu_grids()
  2694. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2695. else:
  2696. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2697. # right mouse click will finish the action
  2698. if isinstance(self.active_tool, FCShapeTool):
  2699. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  2700. self.active_tool.make()
  2701. if self.active_tool.complete:
  2702. self.on_grb_shape_complete()
  2703. self.app.inform.emit(_("[success] Done."))
  2704. # MS: always return to the Select Tool if modifier key is not pressed
  2705. # else return to the current tool but not for FCTrack
  2706. if isinstance(self.active_tool, FCTrack):
  2707. self.select_tool(self.active_tool.name)
  2708. else:
  2709. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2710. if (self.app.defaults["global_mselect_key"] == 'Control' and
  2711. key_modifier == Qt.ControlModifier) or \
  2712. (self.app.defaults["global_mselect_key"] == 'Shift' and
  2713. key_modifier == Qt.ShiftModifier):
  2714. self.select_tool(self.active_tool.name)
  2715. else:
  2716. self.select_tool("select")
  2717. except Exception as e:
  2718. log.warning("Error: %s" % str(e))
  2719. raise
  2720. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2721. # selection and then select a type of selection ("enclosing" or "touching")
  2722. try:
  2723. if event.button == 1: # left click
  2724. if self.app.selection_type is not None:
  2725. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2726. self.app.selection_type = None
  2727. elif isinstance(self.active_tool, FCApertureSelect):
  2728. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2729. # if there are selected objects then plot them
  2730. if self.selected:
  2731. self.plot_all()
  2732. except Exception as e:
  2733. log.warning("Error: %s" % str(e))
  2734. raise
  2735. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2736. """
  2737. :param start_pos: mouse position when the selection LMB click was done
  2738. :param end_pos: mouse position when the left mouse button is released
  2739. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2740. :type Bool
  2741. :return:
  2742. """
  2743. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2744. sel_aperture = set()
  2745. self.apertures_table.clearSelection()
  2746. self.app.delete_selection_shape()
  2747. for storage in self.storage_dict:
  2748. try:
  2749. for obj in self.storage_dict[storage]['solid_geometry']:
  2750. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2751. (sel_type is False and poly_selection.intersects(obj.geo)):
  2752. if self.key == self.app.defaults["global_mselect_key"]:
  2753. if obj in self.selected:
  2754. self.selected.remove(obj)
  2755. else:
  2756. # add the object to the selected shapes
  2757. self.selected.append(obj)
  2758. sel_aperture.add(storage)
  2759. else:
  2760. self.selected.append(obj)
  2761. sel_aperture.add(storage)
  2762. except KeyError:
  2763. pass
  2764. try:
  2765. self.apertures_table.cellPressed.disconnect()
  2766. except:
  2767. pass
  2768. # select the aperture code of the selected geometry, in the tool table
  2769. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2770. for aper in sel_aperture:
  2771. for row in range(self.apertures_table.rowCount()):
  2772. if str(aper) == self.apertures_table.item(row, 1).text():
  2773. self.apertures_table.selectRow(row)
  2774. self.last_aperture_selected = aper
  2775. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2776. self.apertures_table.cellPressed.connect(self.on_row_selected)
  2777. self.plot_all()
  2778. def on_canvas_move(self, event):
  2779. """
  2780. Called on 'mouse_move' event
  2781. event.pos have canvas screen coordinates
  2782. :param event: Event object dispatched by VisPy SceneCavas
  2783. :return: None
  2784. """
  2785. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2786. event.xdata, event.ydata = pos_canvas[0], pos_canvas[1]
  2787. self.x = event.xdata
  2788. self.y = event.ydata
  2789. self.app.ui.popMenu.mouse_is_panning = False
  2790. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2791. if event.button == 2 and event.is_dragging == 1:
  2792. self.app.ui.popMenu.mouse_is_panning = True
  2793. return
  2794. try:
  2795. x = float(event.xdata)
  2796. y = float(event.ydata)
  2797. except TypeError:
  2798. return
  2799. if self.active_tool is None:
  2800. return
  2801. ### Snap coordinates
  2802. if self.app.grid_status():
  2803. x, y = self.app.geo_editor.snap(x, y)
  2804. self.app.app_cursor.enabled = True
  2805. # Update cursor
  2806. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2807. else:
  2808. self.app.app_cursor.enabled = False
  2809. self.snap_x = x
  2810. self.snap_y = y
  2811. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2812. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2813. "<b>Y</b>: %.4f" % (x, y))
  2814. if self.pos is None:
  2815. self.pos = (0, 0)
  2816. dx = x - self.pos[0]
  2817. dy = y - self.pos[1]
  2818. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2819. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2820. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2821. ### Utility geometry (animated)
  2822. geo = self.active_tool.utility_geometry(data=(x, y))
  2823. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2824. # Remove any previous utility shape
  2825. self.tool_shape.clear(update=True)
  2826. self.draw_utility_geometry(geo=geo)
  2827. ### Selection area on canvas section ###
  2828. if event.is_dragging == 1 and event.button == 1:
  2829. # I make an exception for FCRegion and FCTrack because clicking and dragging while making regions can
  2830. # create strange issues like missing a point in a track/region
  2831. if isinstance(self.active_tool, FCRegion) or isinstance(self.active_tool, FCTrack):
  2832. pass
  2833. else:
  2834. dx = pos_canvas[0] - self.pos[0]
  2835. self.app.delete_selection_shape()
  2836. if dx < 0:
  2837. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2838. color=self.app.defaults["global_alt_sel_line"],
  2839. face_color=self.app.defaults['global_alt_sel_fill'])
  2840. self.app.selection_type = False
  2841. else:
  2842. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2843. self.app.selection_type = True
  2844. else:
  2845. self.app.selection_type = None
  2846. def on_canvas_key_release(self, event):
  2847. self.key = None
  2848. def draw_utility_geometry(self, geo):
  2849. if type(geo.geo) == list:
  2850. for el in geo.geo:
  2851. # Add the new utility shape
  2852. self.tool_shape.add(
  2853. shape=el, color=(self.app.defaults["global_draw_color"] + '80'),
  2854. # face_color=self.app.defaults['global_alt_sel_fill'],
  2855. update=False, layer=0, tolerance=None)
  2856. else:
  2857. # Add the new utility shape
  2858. self.tool_shape.add(
  2859. shape=geo.geo,
  2860. color=(self.app.defaults["global_draw_color"] + '80'),
  2861. # face_color=self.app.defaults['global_alt_sel_fill'],
  2862. update=False, layer=0, tolerance=None)
  2863. self.tool_shape.redraw()
  2864. def plot_all(self):
  2865. """
  2866. Plots all shapes in the editor.
  2867. :return: None
  2868. :rtype: None
  2869. """
  2870. with self.app.proc_container.new("Plotting"):
  2871. # self.app.log.debug("plot_all()")
  2872. self.shapes.clear(update=True)
  2873. for storage in self.storage_dict:
  2874. try:
  2875. for shape in self.storage_dict[storage]['solid_geometry']:
  2876. if shape.geo is None:
  2877. continue
  2878. if shape in self.selected:
  2879. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'],
  2880. linewidth=2)
  2881. continue
  2882. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2883. except KeyError:
  2884. pass
  2885. for shape in self.utility:
  2886. self.plot_shape(geometry=shape.geo, linewidth=1)
  2887. continue
  2888. self.shapes.redraw()
  2889. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2890. """
  2891. Plots a geometric object or list of objects without rendering. Plotted objects
  2892. are returned as a list. This allows for efficient/animated rendering.
  2893. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2894. :param color: Shape color
  2895. :param linewidth: Width of lines in # of pixels.
  2896. :return: List of plotted elements.
  2897. """
  2898. # plot_elements = []
  2899. if geometry is None:
  2900. geometry = self.active_tool.geometry
  2901. try:
  2902. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0)
  2903. except AttributeError:
  2904. if type(geometry) == Point:
  2905. return
  2906. self.shapes.add(shape=geometry, color=color, face_color=color+'AF', layer=0)
  2907. def start_delayed_plot(self, check_period):
  2908. """
  2909. This function starts an QTImer and it will periodically check if all the workers finish the plotting functions
  2910. :param check_period: time at which to check periodically if all plots finished to be plotted
  2911. :return:
  2912. """
  2913. # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  2914. # self.plot_thread.start()
  2915. log.debug("FlatCAMGrbEditor --> Delayed Plot started.")
  2916. self.plot_thread = QtCore.QTimer()
  2917. self.plot_thread.setInterval(check_period)
  2918. self.plot_thread.timeout.connect(self.check_plot_finished)
  2919. self.plot_thread.start()
  2920. def check_plot_finished(self):
  2921. """
  2922. If all the promises made are finished then all the shapes are in shapes_storage and can be plotted safely and
  2923. then the UI is rebuilt accordingly.
  2924. :return:
  2925. """
  2926. try:
  2927. if not self.grb_plot_promises:
  2928. self.plot_thread.stop()
  2929. self.set_ui()
  2930. # now that we have data, create the GUI interface and add it to the Tool Tab
  2931. self.build_ui(first_run=True)
  2932. self.plot_all()
  2933. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  2934. # - perhaps is a bug in VisPy implementation
  2935. self.app.app_cursor.enabled = False
  2936. self.app.app_cursor.enabled = True
  2937. log.debug("FlatCAMGrbEditor --> delayed_plot finished")
  2938. except Exception:
  2939. traceback.print_exc()
  2940. def on_shape_complete(self):
  2941. self.app.log.debug("on_shape_complete()")
  2942. # Add shape
  2943. self.add_gerber_shape(self.active_tool.geometry)
  2944. # Remove any utility shapes
  2945. self.delete_utility_geometry()
  2946. self.tool_shape.clear(update=True)
  2947. # Replot and reset tool.
  2948. self.plot_all()
  2949. # self.active_tool = type(self.active_tool)(self)
  2950. def get_selected(self):
  2951. """
  2952. Returns list of shapes that are selected in the editor.
  2953. :return: List of shapes.
  2954. """
  2955. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2956. return self.selected
  2957. def delete_selected(self):
  2958. temp_ref = [s for s in self.selected]
  2959. if len(temp_ref) == 0:
  2960. self.app.inform.emit(_("[ERROR_NOTCL] Failed. No aperture geometry is selected."))
  2961. return
  2962. for shape_sel in temp_ref:
  2963. self.delete_shape(shape_sel)
  2964. self.selected = []
  2965. self.build_ui()
  2966. self.app.inform.emit(_("[success] Done. Apertures geometry deleted."))
  2967. def delete_shape(self, shape):
  2968. self.is_modified = True
  2969. if shape in self.utility:
  2970. self.utility.remove(shape)
  2971. return
  2972. for storage in self.storage_dict:
  2973. try:
  2974. if shape in self.storage_dict[storage]['solid_geometry']:
  2975. self.storage_dict[storage]['solid_geometry'].remove(shape)
  2976. except KeyError:
  2977. pass
  2978. if shape in self.selected:
  2979. self.selected.remove(shape) # TODO: Check performance
  2980. def delete_utility_geometry(self):
  2981. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2982. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2983. for_deletion = [shape for shape in self.utility]
  2984. for shape in for_deletion:
  2985. self.delete_shape(shape)
  2986. self.tool_shape.clear(update=True)
  2987. self.tool_shape.redraw()
  2988. def on_delete_btn(self):
  2989. self.delete_selected()
  2990. self.plot_all()
  2991. def select_tool(self, toolname):
  2992. """
  2993. Selects a drawing tool. Impacts the object and GUI.
  2994. :param toolname: Name of the tool.
  2995. :return: None
  2996. """
  2997. self.tools_gerber[toolname]["button"].setChecked(True)
  2998. self.on_tool_select(toolname)
  2999. def set_selected(self, shape):
  3000. # Remove and add to the end.
  3001. if shape in self.selected:
  3002. self.selected.remove(shape)
  3003. self.selected.append(shape)
  3004. def set_unselected(self, shape):
  3005. if shape in self.selected:
  3006. self.selected.remove(shape)
  3007. def on_array_type_combo(self):
  3008. if self.array_type_combo.currentIndex() == 0:
  3009. self.array_circular_frame.hide()
  3010. self.array_linear_frame.show()
  3011. else:
  3012. self.delete_utility_geometry()
  3013. self.array_circular_frame.show()
  3014. self.array_linear_frame.hide()
  3015. self.app.inform.emit(_("Click on the circular array Center position"))
  3016. def on_linear_angle_radio(self):
  3017. val = self.pad_axis_radio.get_value()
  3018. if val == 'A':
  3019. self.linear_angle_spinner.show()
  3020. self.linear_angle_label.show()
  3021. else:
  3022. self.linear_angle_spinner.hide()
  3023. self.linear_angle_label.hide()
  3024. def on_copy_button(self):
  3025. self.select_tool('copy')
  3026. return
  3027. def on_move_button(self):
  3028. self.select_tool('move')
  3029. return
  3030. def on_pad_add(self):
  3031. self.select_tool('pad')
  3032. def on_pad_add_array(self):
  3033. self.select_tool('array')
  3034. def on_track_add(self):
  3035. self.select_tool('track')
  3036. def on_region_add(self):
  3037. self.select_tool('region')
  3038. def on_poligonize(self):
  3039. self.select_tool('poligonize')
  3040. def on_disc_add(self):
  3041. self.select_tool('disc')
  3042. def on_add_semidisc(self):
  3043. self.select_tool('semidisc')
  3044. def on_buffer(self):
  3045. buff_value = 0.01
  3046. log.debug("FlatCAMGrbEditor.on_buffer()")
  3047. try:
  3048. buff_value = float(self.buffer_distance_entry.get_value())
  3049. except ValueError:
  3050. # try to convert comma to decimal point. if it's still not working error message and return
  3051. try:
  3052. buff_value = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  3053. self.buffer_distance_entry.set_value(buff_value)
  3054. except ValueError:
  3055. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  3056. "Add it and retry."))
  3057. return
  3058. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  3059. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  3060. join_style = self.buffer_corner_cb.currentIndex() + 1
  3061. def buffer_recursion(geom, selection):
  3062. if type(geom) == list or type(geom) is MultiPolygon:
  3063. geoms = list()
  3064. for local_geom in geom:
  3065. geoms.append(buffer_recursion(local_geom, selection=selection))
  3066. return geoms
  3067. else:
  3068. if geom in selection:
  3069. return DrawToolShape(geom.geo.buffer(buff_value, join_style=join_style))
  3070. else:
  3071. return geom
  3072. if not self.apertures_table.selectedItems():
  3073. self.app.inform.emit(_(
  3074. "[WARNING_NOTCL] No aperture to buffer. Select at least one aperture and try again."
  3075. ))
  3076. return
  3077. for x in self.apertures_table.selectedItems():
  3078. try:
  3079. apid = self.apertures_table.item(x.row(), 1).text()
  3080. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3081. self.storage_dict[apid]['solid_geometry'] = []
  3082. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3083. except Exception as e:
  3084. log.debug("FlatCAMGrbEditor.buffer() --> %s" % str(e))
  3085. self.plot_all()
  3086. self.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  3087. def on_scale(self):
  3088. scale_factor = 1.0
  3089. log.debug("FlatCAMGrbEditor.on_scale()")
  3090. try:
  3091. scale_factor = float(self.scale_factor_entry.get_value())
  3092. except ValueError:
  3093. # try to convert comma to decimal point. if it's still not working error message and return
  3094. try:
  3095. scale_factor = float(self.scale_factor_entry.get_value().replace(',', '.'))
  3096. self.scale_factor_entry.set_value(scale_factor)
  3097. except ValueError:
  3098. self.app.inform.emit(_("[WARNING_NOTCL] Scale factor value is missing or wrong format. "
  3099. "Add it and retry."))
  3100. return
  3101. def scale_recursion(geom, selection):
  3102. if type(geom) == list or type(geom) is MultiPolygon:
  3103. geoms = list()
  3104. for local_geom in geom:
  3105. geoms.append(scale_recursion(local_geom, selection=selection))
  3106. return geoms
  3107. else:
  3108. if geom in selection:
  3109. return DrawToolShape(affinity.scale(geom.geo, scale_factor, scale_factor, origin='center'))
  3110. else:
  3111. return geom
  3112. if not self.apertures_table.selectedItems():
  3113. self.app.inform.emit(_(
  3114. "[WARNING_NOTCL] No aperture to scale. Select at least one aperture and try again."
  3115. ))
  3116. return
  3117. for x in self.apertures_table.selectedItems():
  3118. try:
  3119. apid = self.apertures_table.item(x.row(), 1).text()
  3120. temp_storage = deepcopy(scale_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3121. self.storage_dict[apid]['solid_geometry'] = []
  3122. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3123. except Exception as e:
  3124. log.debug("FlatCAMGrbEditor.on_scale() --> %s" % str(e))
  3125. self.plot_all()
  3126. self.app.inform.emit(_("[success] Done. Scale Tool completed."))
  3127. def on_transform(self):
  3128. if type(self.active_tool) == FCTransform:
  3129. self.select_tool('select')
  3130. else:
  3131. self.select_tool('transform')
  3132. def hide_tool(self, tool_name):
  3133. # self.app.ui.notebook.setTabText(2, _("Tools"))
  3134. if tool_name == 'all':
  3135. self.apertures_frame.hide()
  3136. if tool_name == 'select':
  3137. self.apertures_frame.show()
  3138. if tool_name == 'buffer' or tool_name == 'all':
  3139. self.buffer_tool_frame.hide()
  3140. if tool_name == 'scale' or tool_name == 'all':
  3141. self.scale_tool_frame.hide()
  3142. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3143. class TransformEditorTool(FlatCAMTool):
  3144. """
  3145. Inputs to specify how to paint the selected polygons.
  3146. """
  3147. toolName = _("Transform Tool")
  3148. rotateName = _("Rotate")
  3149. skewName = _("Skew/Shear")
  3150. scaleName = _("Scale")
  3151. flipName = _("Mirror (Flip)")
  3152. offsetName = _("Offset")
  3153. def __init__(self, app, draw_app):
  3154. FlatCAMTool.__init__(self, app)
  3155. self.app = app
  3156. self.draw_app = draw_app
  3157. self.transform_lay = QtWidgets.QVBoxLayout()
  3158. self.layout.addLayout(self.transform_lay)
  3159. ## Title
  3160. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  3161. title_label.setStyleSheet("""
  3162. QLabel
  3163. {
  3164. font-size: 16px;
  3165. font-weight: bold;
  3166. }
  3167. """)
  3168. self.transform_lay.addWidget(title_label)
  3169. self.empty_label = QtWidgets.QLabel("")
  3170. self.empty_label.setFixedWidth(50)
  3171. self.empty_label1 = QtWidgets.QLabel("")
  3172. self.empty_label1.setFixedWidth(70)
  3173. self.empty_label2 = QtWidgets.QLabel("")
  3174. self.empty_label2.setFixedWidth(70)
  3175. self.empty_label3 = QtWidgets.QLabel("")
  3176. self.empty_label3.setFixedWidth(70)
  3177. self.empty_label4 = QtWidgets.QLabel("")
  3178. self.empty_label4.setFixedWidth(70)
  3179. self.transform_lay.addWidget(self.empty_label)
  3180. ## Rotate Title
  3181. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  3182. self.transform_lay.addWidget(rotate_title_label)
  3183. ## Layout
  3184. form_layout = QtWidgets.QFormLayout()
  3185. self.transform_lay.addLayout(form_layout)
  3186. form_child = QtWidgets.QHBoxLayout()
  3187. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  3188. self.rotate_label.setToolTip(
  3189. _("Angle for Rotation action, in degrees.\n"
  3190. "Float number between -360 and 359.\n"
  3191. "Positive numbers for CW motion.\n"
  3192. "Negative numbers for CCW motion.")
  3193. )
  3194. self.rotate_label.setFixedWidth(50)
  3195. self.rotate_entry = FCEntry()
  3196. # self.rotate_entry.setFixedWidth(60)
  3197. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3198. self.rotate_button = FCButton()
  3199. self.rotate_button.set_value(_("Rotate"))
  3200. self.rotate_button.setToolTip(
  3201. _("Rotate the selected shape(s).\n"
  3202. "The point of reference is the middle of\n"
  3203. "the bounding box for all selected shapes.")
  3204. )
  3205. self.rotate_button.setFixedWidth(60)
  3206. form_child.addWidget(self.rotate_entry)
  3207. form_child.addWidget(self.rotate_button)
  3208. form_layout.addRow(self.rotate_label, form_child)
  3209. self.transform_lay.addWidget(self.empty_label1)
  3210. ## Skew Title
  3211. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  3212. self.transform_lay.addWidget(skew_title_label)
  3213. ## Form Layout
  3214. form1_layout = QtWidgets.QFormLayout()
  3215. self.transform_lay.addLayout(form1_layout)
  3216. form1_child_1 = QtWidgets.QHBoxLayout()
  3217. form1_child_2 = QtWidgets.QHBoxLayout()
  3218. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  3219. self.skewx_label.setToolTip(
  3220. _("Angle for Skew action, in degrees.\n"
  3221. "Float number between -360 and 359.")
  3222. )
  3223. self.skewx_label.setFixedWidth(50)
  3224. self.skewx_entry = FCEntry()
  3225. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3226. # self.skewx_entry.setFixedWidth(60)
  3227. self.skewx_button = FCButton()
  3228. self.skewx_button.set_value(_("Skew X"))
  3229. self.skewx_button.setToolTip(
  3230. _("Skew/shear the selected shape(s).\n"
  3231. "The point of reference is the middle of\n"
  3232. "the bounding box for all selected shapes."))
  3233. self.skewx_button.setFixedWidth(60)
  3234. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  3235. self.skewy_label.setToolTip(
  3236. _("Angle for Skew action, in degrees.\n"
  3237. "Float number between -360 and 359.")
  3238. )
  3239. self.skewy_label.setFixedWidth(50)
  3240. self.skewy_entry = FCEntry()
  3241. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3242. # self.skewy_entry.setFixedWidth(60)
  3243. self.skewy_button = FCButton()
  3244. self.skewy_button.set_value(_("Skew Y"))
  3245. self.skewy_button.setToolTip(
  3246. _("Skew/shear the selected shape(s).\n"
  3247. "The point of reference is the middle of\n"
  3248. "the bounding box for all selected shapes."))
  3249. self.skewy_button.setFixedWidth(60)
  3250. form1_child_1.addWidget(self.skewx_entry)
  3251. form1_child_1.addWidget(self.skewx_button)
  3252. form1_child_2.addWidget(self.skewy_entry)
  3253. form1_child_2.addWidget(self.skewy_button)
  3254. form1_layout.addRow(self.skewx_label, form1_child_1)
  3255. form1_layout.addRow(self.skewy_label, form1_child_2)
  3256. self.transform_lay.addWidget(self.empty_label2)
  3257. ## Scale Title
  3258. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  3259. self.transform_lay.addWidget(scale_title_label)
  3260. ## Form Layout
  3261. form2_layout = QtWidgets.QFormLayout()
  3262. self.transform_lay.addLayout(form2_layout)
  3263. form2_child_1 = QtWidgets.QHBoxLayout()
  3264. form2_child_2 = QtWidgets.QHBoxLayout()
  3265. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  3266. self.scalex_label.setToolTip(
  3267. _("Factor for Scale action over X axis.")
  3268. )
  3269. self.scalex_label.setFixedWidth(50)
  3270. self.scalex_entry = FCEntry()
  3271. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3272. # self.scalex_entry.setFixedWidth(60)
  3273. self.scalex_button = FCButton()
  3274. self.scalex_button.set_value(_("Scale X"))
  3275. self.scalex_button.setToolTip(
  3276. _("Scale the selected shape(s).\n"
  3277. "The point of reference depends on \n"
  3278. "the Scale reference checkbox state."))
  3279. self.scalex_button.setFixedWidth(60)
  3280. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  3281. self.scaley_label.setToolTip(
  3282. _("Factor for Scale action over Y axis.")
  3283. )
  3284. self.scaley_label.setFixedWidth(50)
  3285. self.scaley_entry = FCEntry()
  3286. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3287. # self.scaley_entry.setFixedWidth(60)
  3288. self.scaley_button = FCButton()
  3289. self.scaley_button.set_value(_("Scale Y"))
  3290. self.scaley_button.setToolTip(
  3291. _("Scale the selected shape(s).\n"
  3292. "The point of reference depends on \n"
  3293. "the Scale reference checkbox state."))
  3294. self.scaley_button.setFixedWidth(60)
  3295. self.scale_link_cb = FCCheckBox()
  3296. self.scale_link_cb.set_value(True)
  3297. self.scale_link_cb.setText(_("Link"))
  3298. self.scale_link_cb.setToolTip(
  3299. _("Scale the selected shape(s)\n"
  3300. "using the Scale Factor X for both axis."))
  3301. self.scale_link_cb.setFixedWidth(50)
  3302. self.scale_zero_ref_cb = FCCheckBox()
  3303. self.scale_zero_ref_cb.set_value(True)
  3304. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  3305. self.scale_zero_ref_cb.setToolTip(
  3306. _("Scale the selected shape(s)\n"
  3307. "using the origin reference when checked,\n"
  3308. "and the center of the biggest bounding box\n"
  3309. "of the selected shapes when unchecked."))
  3310. form2_child_1.addWidget(self.scalex_entry)
  3311. form2_child_1.addWidget(self.scalex_button)
  3312. form2_child_2.addWidget(self.scaley_entry)
  3313. form2_child_2.addWidget(self.scaley_button)
  3314. form2_layout.addRow(self.scalex_label, form2_child_1)
  3315. form2_layout.addRow(self.scaley_label, form2_child_2)
  3316. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  3317. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button],
  3318. logic=False)
  3319. self.transform_lay.addWidget(self.empty_label3)
  3320. ## Offset Title
  3321. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  3322. self.transform_lay.addWidget(offset_title_label)
  3323. ## Form Layout
  3324. form3_layout = QtWidgets.QFormLayout()
  3325. self.transform_lay.addLayout(form3_layout)
  3326. form3_child_1 = QtWidgets.QHBoxLayout()
  3327. form3_child_2 = QtWidgets.QHBoxLayout()
  3328. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  3329. self.offx_label.setToolTip(
  3330. _("Value for Offset action on X axis.")
  3331. )
  3332. self.offx_label.setFixedWidth(50)
  3333. self.offx_entry = FCEntry()
  3334. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3335. # self.offx_entry.setFixedWidth(60)
  3336. self.offx_button = FCButton()
  3337. self.offx_button.set_value(_("Offset X"))
  3338. self.offx_button.setToolTip(
  3339. _("Offset the selected shape(s).\n"
  3340. "The point of reference is the middle of\n"
  3341. "the bounding box for all selected shapes.\n")
  3342. )
  3343. self.offx_button.setFixedWidth(60)
  3344. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  3345. self.offy_label.setToolTip(
  3346. _("Value for Offset action on Y axis.")
  3347. )
  3348. self.offy_label.setFixedWidth(50)
  3349. self.offy_entry = FCEntry()
  3350. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3351. # self.offy_entry.setFixedWidth(60)
  3352. self.offy_button = FCButton()
  3353. self.offy_button.set_value(_("Offset Y"))
  3354. self.offy_button.setToolTip(
  3355. _("Offset the selected shape(s).\n"
  3356. "The point of reference is the middle of\n"
  3357. "the bounding box for all selected shapes.\n")
  3358. )
  3359. self.offy_button.setFixedWidth(60)
  3360. form3_child_1.addWidget(self.offx_entry)
  3361. form3_child_1.addWidget(self.offx_button)
  3362. form3_child_2.addWidget(self.offy_entry)
  3363. form3_child_2.addWidget(self.offy_button)
  3364. form3_layout.addRow(self.offx_label, form3_child_1)
  3365. form3_layout.addRow(self.offy_label, form3_child_2)
  3366. self.transform_lay.addWidget(self.empty_label4)
  3367. ## Flip Title
  3368. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  3369. self.transform_lay.addWidget(flip_title_label)
  3370. ## Form Layout
  3371. form4_layout = QtWidgets.QFormLayout()
  3372. form4_child_hlay = QtWidgets.QHBoxLayout()
  3373. self.transform_lay.addLayout(form4_child_hlay)
  3374. self.transform_lay.addLayout(form4_layout)
  3375. form4_child_1 = QtWidgets.QHBoxLayout()
  3376. self.flipx_button = FCButton()
  3377. self.flipx_button.set_value(_("Flip on X"))
  3378. self.flipx_button.setToolTip(
  3379. _("Flip the selected shape(s) over the X axis.\n"
  3380. "Does not create a new shape.")
  3381. )
  3382. self.flipx_button.setFixedWidth(60)
  3383. self.flipy_button = FCButton()
  3384. self.flipy_button.set_value(_("Flip on Y"))
  3385. self.flipy_button.setToolTip(
  3386. _("Flip the selected shape(s) over the X axis.\n"
  3387. "Does not create a new shape.")
  3388. )
  3389. self.flipy_button.setFixedWidth(60)
  3390. self.flip_ref_cb = FCCheckBox()
  3391. self.flip_ref_cb.set_value(True)
  3392. self.flip_ref_cb.setText(_("Ref Pt"))
  3393. self.flip_ref_cb.setToolTip(
  3394. _("Flip the selected shape(s)\n"
  3395. "around the point in Point Entry Field.\n"
  3396. "\n"
  3397. "The point coordinates can be captured by\n"
  3398. "left click on canvas together with pressing\n"
  3399. "SHIFT key. \n"
  3400. "Then click Add button to insert coordinates.\n"
  3401. "Or enter the coords in format (x, y) in the\n"
  3402. "Point Entry field and click Flip on X(Y)")
  3403. )
  3404. self.flip_ref_cb.setFixedWidth(50)
  3405. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  3406. self.flip_ref_label.setToolTip(
  3407. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  3408. "The 'x' in (x, y) will be used when using Flip on X and\n"
  3409. "the 'y' in (x, y) will be used when using Flip on Y.")
  3410. )
  3411. self.flip_ref_label.setFixedWidth(50)
  3412. self.flip_ref_entry = EvalEntry2("(0, 0)")
  3413. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3414. # self.flip_ref_entry.setFixedWidth(60)
  3415. self.flip_ref_button = FCButton()
  3416. self.flip_ref_button.set_value(_("Add"))
  3417. self.flip_ref_button.setToolTip(
  3418. _("The point coordinates can be captured by\n"
  3419. "left click on canvas together with pressing\n"
  3420. "SHIFT key. Then click Add button to insert.")
  3421. )
  3422. self.flip_ref_button.setFixedWidth(60)
  3423. form4_child_hlay.addStretch()
  3424. form4_child_hlay.addWidget(self.flipx_button)
  3425. form4_child_hlay.addWidget(self.flipy_button)
  3426. form4_child_1.addWidget(self.flip_ref_entry)
  3427. form4_child_1.addWidget(self.flip_ref_button)
  3428. form4_layout.addRow(self.flip_ref_cb)
  3429. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  3430. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  3431. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  3432. self.transform_lay.addStretch()
  3433. ## Signals
  3434. self.rotate_button.clicked.connect(self.on_rotate)
  3435. self.skewx_button.clicked.connect(self.on_skewx)
  3436. self.skewy_button.clicked.connect(self.on_skewy)
  3437. self.scalex_button.clicked.connect(self.on_scalex)
  3438. self.scaley_button.clicked.connect(self.on_scaley)
  3439. self.offx_button.clicked.connect(self.on_offx)
  3440. self.offy_button.clicked.connect(self.on_offy)
  3441. self.flipx_button.clicked.connect(self.on_flipx)
  3442. self.flipy_button.clicked.connect(self.on_flipy)
  3443. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  3444. self.rotate_entry.returnPressed.connect(self.on_rotate)
  3445. self.skewx_entry.returnPressed.connect(self.on_skewx)
  3446. self.skewy_entry.returnPressed.connect(self.on_skewy)
  3447. self.scalex_entry.returnPressed.connect(self.on_scalex)
  3448. self.scaley_entry.returnPressed.connect(self.on_scaley)
  3449. self.offx_entry.returnPressed.connect(self.on_offx)
  3450. self.offy_entry.returnPressed.connect(self.on_offy)
  3451. self.set_tool_ui()
  3452. def run(self, toggle=True):
  3453. self.app.report_usage("Geo Editor Transform Tool()")
  3454. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3455. if self.app.ui.splitter.sizes()[0] == 0:
  3456. self.app.ui.splitter.setSizes([1, 1])
  3457. if toggle:
  3458. try:
  3459. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  3460. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3461. else:
  3462. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  3463. except AttributeError:
  3464. pass
  3465. FlatCAMTool.run(self)
  3466. self.set_tool_ui()
  3467. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  3468. def install(self, icon=None, separator=None, **kwargs):
  3469. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  3470. def set_tool_ui(self):
  3471. ## Initialize form
  3472. if self.app.defaults["tools_transform_rotate"]:
  3473. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  3474. else:
  3475. self.rotate_entry.set_value(0.0)
  3476. if self.app.defaults["tools_transform_skew_x"]:
  3477. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  3478. else:
  3479. self.skewx_entry.set_value(0.0)
  3480. if self.app.defaults["tools_transform_skew_y"]:
  3481. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  3482. else:
  3483. self.skewy_entry.set_value(0.0)
  3484. if self.app.defaults["tools_transform_scale_x"]:
  3485. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  3486. else:
  3487. self.scalex_entry.set_value(1.0)
  3488. if self.app.defaults["tools_transform_scale_y"]:
  3489. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  3490. else:
  3491. self.scaley_entry.set_value(1.0)
  3492. if self.app.defaults["tools_transform_scale_link"]:
  3493. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  3494. else:
  3495. self.scale_link_cb.set_value(True)
  3496. if self.app.defaults["tools_transform_scale_reference"]:
  3497. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  3498. else:
  3499. self.scale_zero_ref_cb.set_value(True)
  3500. if self.app.defaults["tools_transform_offset_x"]:
  3501. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  3502. else:
  3503. self.offx_entry.set_value(0.0)
  3504. if self.app.defaults["tools_transform_offset_y"]:
  3505. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  3506. else:
  3507. self.offy_entry.set_value(0.0)
  3508. if self.app.defaults["tools_transform_mirror_reference"]:
  3509. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  3510. else:
  3511. self.flip_ref_cb.set_value(False)
  3512. if self.app.defaults["tools_transform_mirror_point"]:
  3513. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  3514. else:
  3515. self.flip_ref_entry.set_value((0, 0))
  3516. def template(self):
  3517. if not self.fcdraw.selected:
  3518. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  3519. return
  3520. self.draw_app.select_tool("select")
  3521. self.app.ui.notebook.setTabText(2, "Tools")
  3522. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  3523. self.app.ui.splitter.setSizes([0, 1])
  3524. def on_rotate(self, sig=None, val=None):
  3525. if val:
  3526. value = val
  3527. else:
  3528. try:
  3529. value = float(self.rotate_entry.get_value())
  3530. except ValueError:
  3531. # try to convert comma to decimal point. if it's still not working error message and return
  3532. try:
  3533. value = float(self.rotate_entry.get_value().replace(',', '.'))
  3534. except ValueError:
  3535. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  3536. "use a number."))
  3537. return
  3538. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  3539. 'params': [value]})
  3540. # self.on_rotate_action(value)
  3541. return
  3542. def on_flipx(self):
  3543. # self.on_flip("Y")
  3544. axis = 'Y'
  3545. self.app.worker_task.emit({'fcn': self.on_flip,
  3546. 'params': [axis]})
  3547. return
  3548. def on_flipy(self):
  3549. # self.on_flip("X")
  3550. axis = 'X'
  3551. self.app.worker_task.emit({'fcn': self.on_flip,
  3552. 'params': [axis]})
  3553. return
  3554. def on_flip_add_coords(self):
  3555. val = self.app.clipboard.text()
  3556. self.flip_ref_entry.set_value(val)
  3557. def on_skewx(self, sig=None, val=None):
  3558. if val:
  3559. value = val
  3560. else:
  3561. try:
  3562. value = float(self.skewx_entry.get_value())
  3563. except ValueError:
  3564. # try to convert comma to decimal point. if it's still not working error message and return
  3565. try:
  3566. value = float(self.skewx_entry.get_value().replace(',', '.'))
  3567. except ValueError:
  3568. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  3569. "use a number."))
  3570. return
  3571. # self.on_skew("X", value)
  3572. axis = 'X'
  3573. self.app.worker_task.emit({'fcn': self.on_skew,
  3574. 'params': [axis, value]})
  3575. return
  3576. def on_skewy(self, sig=None, val=None):
  3577. if val:
  3578. value = val
  3579. else:
  3580. try:
  3581. value = float(self.skewy_entry.get_value())
  3582. except ValueError:
  3583. # try to convert comma to decimal point. if it's still not working error message and return
  3584. try:
  3585. value = float(self.skewy_entry.get_value().replace(',', '.'))
  3586. except ValueError:
  3587. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  3588. "use a number."))
  3589. return
  3590. # self.on_skew("Y", value)
  3591. axis = 'Y'
  3592. self.app.worker_task.emit({'fcn': self.on_skew,
  3593. 'params': [axis, value]})
  3594. return
  3595. def on_scalex(self, sig=None, val=None):
  3596. if val:
  3597. xvalue = val
  3598. else:
  3599. try:
  3600. xvalue = float(self.scalex_entry.get_value())
  3601. except ValueError:
  3602. # try to convert comma to decimal point. if it's still not working error message and return
  3603. try:
  3604. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  3605. except ValueError:
  3606. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  3607. "use a number."))
  3608. return
  3609. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3610. if xvalue == 0:
  3611. xvalue = 1
  3612. if self.scale_link_cb.get_value():
  3613. yvalue = xvalue
  3614. else:
  3615. yvalue = 1
  3616. axis = 'X'
  3617. point = (0, 0)
  3618. if self.scale_zero_ref_cb.get_value():
  3619. self.app.worker_task.emit({'fcn': self.on_scale,
  3620. 'params': [axis, xvalue, yvalue, point]})
  3621. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  3622. else:
  3623. # self.on_scale("X", xvalue, yvalue)
  3624. self.app.worker_task.emit({'fcn': self.on_scale,
  3625. 'params': [axis, xvalue, yvalue]})
  3626. return
  3627. def on_scaley(self, sig=None, val=None):
  3628. xvalue = 1
  3629. if val:
  3630. yvalue = val
  3631. else:
  3632. try:
  3633. yvalue = float(self.scaley_entry.get_value())
  3634. except ValueError:
  3635. # try to convert comma to decimal point. if it's still not working error message and return
  3636. try:
  3637. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  3638. except ValueError:
  3639. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  3640. "use a number."))
  3641. return
  3642. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3643. if yvalue == 0:
  3644. yvalue = 1
  3645. axis = 'Y'
  3646. point = (0, 0)
  3647. if self.scale_zero_ref_cb.get_value():
  3648. self.app.worker_task.emit({'fcn': self.on_scale,
  3649. 'params': [axis, xvalue, yvalue, point]})
  3650. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  3651. else:
  3652. # self.on_scale("Y", xvalue, yvalue)
  3653. self.app.worker_task.emit({'fcn': self.on_scale,
  3654. 'params': [axis, xvalue, yvalue]})
  3655. return
  3656. def on_offx(self, sig=None, val=None):
  3657. if val:
  3658. value = val
  3659. else:
  3660. try:
  3661. value = float(self.offx_entry.get_value())
  3662. except ValueError:
  3663. # try to convert comma to decimal point. if it's still not working error message and return
  3664. try:
  3665. value = float(self.offx_entry.get_value().replace(',', '.'))
  3666. except ValueError:
  3667. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  3668. "use a number."))
  3669. return
  3670. # self.on_offset("X", value)
  3671. axis = 'X'
  3672. self.app.worker_task.emit({'fcn': self.on_offset,
  3673. 'params': [axis, value]})
  3674. return
  3675. def on_offy(self, sig=None, val=None):
  3676. if val:
  3677. value = val
  3678. else:
  3679. try:
  3680. value = float(self.offy_entry.get_value())
  3681. except ValueError:
  3682. # try to convert comma to decimal point. if it's still not working error message and return
  3683. try:
  3684. value = float(self.offy_entry.get_value().replace(',', '.'))
  3685. except ValueError:
  3686. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  3687. "use a number."))
  3688. return
  3689. # self.on_offset("Y", value)
  3690. axis = 'Y'
  3691. self.app.worker_task.emit({'fcn': self.on_offset,
  3692. 'params': [axis, value]})
  3693. return
  3694. def on_rotate_action(self, num):
  3695. shape_list = self.draw_app.selected
  3696. xminlist = []
  3697. yminlist = []
  3698. xmaxlist = []
  3699. ymaxlist = []
  3700. if not shape_list:
  3701. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  3702. return
  3703. else:
  3704. with self.app.proc_container.new(_("Appying Rotate")):
  3705. try:
  3706. # first get a bounding box to fit all
  3707. for sha in shape_list:
  3708. xmin, ymin, xmax, ymax = sha.bounds()
  3709. xminlist.append(xmin)
  3710. yminlist.append(ymin)
  3711. xmaxlist.append(xmax)
  3712. ymaxlist.append(ymax)
  3713. # get the minimum x,y and maximum x,y for all objects selected
  3714. xminimal = min(xminlist)
  3715. yminimal = min(yminlist)
  3716. xmaximal = max(xmaxlist)
  3717. ymaximal = max(ymaxlist)
  3718. self.app.progress.emit(20)
  3719. for sel_sha in shape_list:
  3720. px = 0.5 * (xminimal + xmaximal)
  3721. py = 0.5 * (yminimal + ymaximal)
  3722. sel_sha.rotate(-num, point=(px, py))
  3723. self.draw_app.plot_all()
  3724. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  3725. # self.draw_app.transform_complete.emit()
  3726. self.app.inform.emit(_("[success] Done. Rotate completed."))
  3727. self.app.progress.emit(100)
  3728. except Exception as e:
  3729. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3730. return
  3731. def on_flip(self, axis):
  3732. shape_list = self.draw_app.selected
  3733. xminlist = []
  3734. yminlist = []
  3735. xmaxlist = []
  3736. ymaxlist = []
  3737. if not shape_list:
  3738. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  3739. return
  3740. else:
  3741. with self.app.proc_container.new(_("Applying Flip")):
  3742. try:
  3743. # get mirroring coords from the point entry
  3744. if self.flip_ref_cb.isChecked():
  3745. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  3746. # get mirroing coords from the center of an all-enclosing bounding box
  3747. else:
  3748. # first get a bounding box to fit all
  3749. for sha in shape_list:
  3750. xmin, ymin, xmax, ymax = sha.bounds()
  3751. xminlist.append(xmin)
  3752. yminlist.append(ymin)
  3753. xmaxlist.append(xmax)
  3754. ymaxlist.append(ymax)
  3755. # get the minimum x,y and maximum x,y for all objects selected
  3756. xminimal = min(xminlist)
  3757. yminimal = min(yminlist)
  3758. xmaximal = max(xmaxlist)
  3759. ymaximal = max(ymaxlist)
  3760. px = 0.5 * (xminimal + xmaximal)
  3761. py = 0.5 * (yminimal + ymaximal)
  3762. self.app.progress.emit(20)
  3763. # execute mirroring
  3764. for sha in shape_list:
  3765. if axis is 'X':
  3766. sha.mirror('X', (px, py))
  3767. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  3768. elif axis is 'Y':
  3769. sha.mirror('Y', (px, py))
  3770. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  3771. self.draw_app.plot_all()
  3772. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3773. #
  3774. # self.draw_app.transform_complete.emit()
  3775. self.app.progress.emit(100)
  3776. except Exception as e:
  3777. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3778. return
  3779. def on_skew(self, axis, num):
  3780. shape_list = self.draw_app.selected
  3781. xminlist = []
  3782. yminlist = []
  3783. if not shape_list:
  3784. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  3785. return
  3786. else:
  3787. with self.app.proc_container.new(_("Applying Skew")):
  3788. try:
  3789. # first get a bounding box to fit all
  3790. for sha in shape_list:
  3791. xmin, ymin, xmax, ymax = sha.bounds()
  3792. xminlist.append(xmin)
  3793. yminlist.append(ymin)
  3794. # get the minimum x,y and maximum x,y for all objects selected
  3795. xminimal = min(xminlist)
  3796. yminimal = min(yminlist)
  3797. self.app.progress.emit(20)
  3798. for sha in shape_list:
  3799. if axis is 'X':
  3800. sha.skew(num, 0, point=(xminimal, yminimal))
  3801. elif axis is 'Y':
  3802. sha.skew(0, num, point=(xminimal, yminimal))
  3803. self.draw_app.plot_all()
  3804. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3805. #
  3806. # self.draw_app.transform_complete.emit()
  3807. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  3808. self.app.progress.emit(100)
  3809. except Exception as e:
  3810. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  3811. return
  3812. def on_scale(self, axis, xfactor, yfactor, point=None):
  3813. shape_list = self.draw_app.selected
  3814. xminlist = []
  3815. yminlist = []
  3816. xmaxlist = []
  3817. ymaxlist = []
  3818. if not shape_list:
  3819. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  3820. return
  3821. else:
  3822. with self.app.proc_container.new(_("Applying Scale")):
  3823. try:
  3824. # first get a bounding box to fit all
  3825. for sha in shape_list:
  3826. xmin, ymin, xmax, ymax = sha.bounds()
  3827. xminlist.append(xmin)
  3828. yminlist.append(ymin)
  3829. xmaxlist.append(xmax)
  3830. ymaxlist.append(ymax)
  3831. # get the minimum x,y and maximum x,y for all objects selected
  3832. xminimal = min(xminlist)
  3833. yminimal = min(yminlist)
  3834. xmaximal = max(xmaxlist)
  3835. ymaximal = max(ymaxlist)
  3836. self.app.progress.emit(20)
  3837. if point is None:
  3838. px = 0.5 * (xminimal + xmaximal)
  3839. py = 0.5 * (yminimal + ymaximal)
  3840. else:
  3841. px = 0
  3842. py = 0
  3843. for sha in shape_list:
  3844. sha.scale(xfactor, yfactor, point=(px, py))
  3845. self.draw_app.plot_all()
  3846. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3847. #
  3848. # self.draw_app.transform_complete.emit()
  3849. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  3850. self.app.progress.emit(100)
  3851. except Exception as e:
  3852. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  3853. return
  3854. def on_offset(self, axis, num):
  3855. shape_list = self.draw_app.selected
  3856. xminlist = []
  3857. yminlist = []
  3858. if not shape_list:
  3859. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  3860. return
  3861. else:
  3862. with self.app.proc_container.new(_("Applying Offset")):
  3863. try:
  3864. # first get a bounding box to fit all
  3865. for sha in shape_list:
  3866. xmin, ymin, xmax, ymax = sha.bounds()
  3867. xminlist.append(xmin)
  3868. yminlist.append(ymin)
  3869. # get the minimum x,y and maximum x,y for all objects selected
  3870. xminimal = min(xminlist)
  3871. yminimal = min(yminlist)
  3872. self.app.progress.emit(20)
  3873. for sha in shape_list:
  3874. if axis is 'X':
  3875. sha.offset((num, 0))
  3876. elif axis is 'Y':
  3877. sha.offset((0, num))
  3878. self.draw_app.plot_all()
  3879. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3880. #
  3881. # self.draw_app.transform_complete.emit()
  3882. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  3883. self.app.progress.emit(100)
  3884. except Exception as e:
  3885. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  3886. return
  3887. def on_rotate_key(self):
  3888. val_box = FCInputDialog(title=_("Rotate ..."),
  3889. text=_('Enter an Angle Value (degrees):'),
  3890. min=-359.9999, max=360.0000, decimals=4,
  3891. init_val=float(self.app.defaults['tools_transform_rotate']))
  3892. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  3893. val, ok = val_box.get_value()
  3894. if ok:
  3895. self.on_rotate(val=val)
  3896. self.app.inform.emit(
  3897. _("[success] Geometry shape rotate done...")
  3898. )
  3899. return
  3900. else:
  3901. self.app.inform.emit(
  3902. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  3903. )
  3904. def on_offx_key(self):
  3905. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3906. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  3907. text=(_('Enter a distance Value (%s):') % str(units)),
  3908. min=-9999.9999, max=10000.0000, decimals=4,
  3909. init_val=float(self.app.defaults['tools_transform_offset_x']))
  3910. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  3911. val, ok = val_box.get_value()
  3912. if ok:
  3913. self.on_offx(val=val)
  3914. self.app.inform.emit(
  3915. _("[success] Geometry shape offset on X axis done..."))
  3916. return
  3917. else:
  3918. self.app.inform.emit(
  3919. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  3920. def on_offy_key(self):
  3921. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3922. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  3923. text=(_('Enter a distance Value (%s):') % str(units)),
  3924. min=-9999.9999, max=10000.0000, decimals=4,
  3925. init_val=float(self.app.defaults['tools_transform_offset_y']))
  3926. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  3927. val, ok = val_box.get_value()
  3928. if ok:
  3929. self.on_offx(val=val)
  3930. self.app.inform.emit(
  3931. _("[success] Geometry shape offset on Y axis done..."))
  3932. return
  3933. else:
  3934. self.app.inform.emit(
  3935. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  3936. def on_skewx_key(self):
  3937. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  3938. text=_('Enter an Angle Value (degrees):'),
  3939. min=-359.9999, max=360.0000, decimals=4,
  3940. init_val=float(self.app.defaults['tools_transform_skew_x']))
  3941. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  3942. val, ok = val_box.get_value()
  3943. if ok:
  3944. self.on_skewx(val=val)
  3945. self.app.inform.emit(
  3946. _("[success] Geometry shape skew on X axis done..."))
  3947. return
  3948. else:
  3949. self.app.inform.emit(
  3950. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  3951. def on_skewy_key(self):
  3952. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  3953. text=_('Enter an Angle Value (degrees):'),
  3954. min=-359.9999, max=360.0000, decimals=4,
  3955. init_val=float(self.app.defaults['tools_transform_skew_y']))
  3956. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  3957. val, ok = val_box.get_value()
  3958. if ok:
  3959. self.on_skewx(val=val)
  3960. self.app.inform.emit(
  3961. _("[success] Geometry shape skew on Y axis done..."))
  3962. return
  3963. else:
  3964. self.app.inform.emit(
  3965. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))