FlatCAMGrbEditor.py 190 KB

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