FlatCAMGrbEditor.py 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848
  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. self.app.ui.popmenu_disable.setVisible(False)
  2181. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2182. self.app.ui.popmenu_properties.setVisible(False)
  2183. self.app.ui.grb_editor_cmenu.menuAction().setVisible(True)
  2184. # Tell the App that the editor is active
  2185. self.editor_active = True
  2186. def deactivate_grb_editor(self):
  2187. try:
  2188. QtGui.QGuiApplication.restoreOverrideCursor()
  2189. except:
  2190. pass
  2191. # adjust the status of the menu entries related to the editor
  2192. self.app.ui.menueditedit.setDisabled(False)
  2193. self.app.ui.menueditok.setDisabled(True)
  2194. # adjust the visibility of some of the canvas context menu
  2195. self.app.ui.popmenu_edit.setVisible(True)
  2196. self.app.ui.popmenu_save.setVisible(False)
  2197. self.disconnect_canvas_event_handlers()
  2198. self.clear()
  2199. self.app.ui.grb_edit_toolbar.setDisabled(True)
  2200. settings = QSettings("Open Source", "FlatCAM")
  2201. if settings.contains("layout"):
  2202. layout = settings.value('layout', type=str)
  2203. if layout == 'standard':
  2204. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2205. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2206. self.app.ui.corner_snap_btn.setEnabled(False)
  2207. self.app.ui.snap_magnet.setVisible(False)
  2208. self.app.ui.corner_snap_btn.setVisible(False)
  2209. elif layout == 'compact':
  2210. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2211. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2212. self.app.ui.corner_snap_btn.setEnabled(False)
  2213. self.app.ui.snap_magnet.setVisible(True)
  2214. self.app.ui.corner_snap_btn.setVisible(True)
  2215. else:
  2216. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2217. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2218. self.app.ui.corner_snap_btn.setEnabled(False)
  2219. self.app.ui.snap_magnet.setVisible(False)
  2220. self.app.ui.corner_snap_btn.setVisible(False)
  2221. # set the Editor Toolbar visibility to what was before entering in the Editor
  2222. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2223. else self.app.ui.grb_edit_toolbar.setVisible(True)
  2224. # Disable visuals
  2225. self.shapes.enabled = False
  2226. self.tool_shape.enabled = False
  2227. # self.app.app_cursor.enabled = False
  2228. # Tell the app that the editor is no longer active
  2229. self.editor_active = False
  2230. self.app.ui.grb_editor_menu.setDisabled(True)
  2231. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  2232. self.app.ui.update_obj_btn.setEnabled(False)
  2233. # adjust the visibility of some of the canvas context menu
  2234. self.app.ui.popmenu_edit.setVisible(True)
  2235. self.app.ui.popmenu_save.setVisible(False)
  2236. self.app.ui.popmenu_disable.setVisible(True)
  2237. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2238. self.app.ui.popmenu_properties.setVisible(True)
  2239. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2240. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2241. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2242. # Show original geometry
  2243. if self.gerber_obj:
  2244. self.gerber_obj.visible = True
  2245. def connect_canvas_event_handlers(self):
  2246. ## Canvas events
  2247. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2248. # but those from FlatCAMGeoEditor
  2249. # first connect to new, then disconnect the old handlers
  2250. # don't ask why but if there is nothing connected I've seen issues
  2251. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2252. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2253. self.canvas.vis_connect('mouse_release', self.on_grb_click_release)
  2254. self.canvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2255. self.canvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2256. self.canvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2257. self.canvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2258. self.app.collection.view.clicked.disconnect()
  2259. self.app.ui.popmenu_copy.triggered.disconnect()
  2260. self.app.ui.popmenu_delete.triggered.disconnect()
  2261. self.app.ui.popmenu_move.triggered.disconnect()
  2262. self.app.ui.popmenu_copy.triggered.connect(self.on_copy_button)
  2263. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2264. self.app.ui.popmenu_move.triggered.connect(self.on_move_button)
  2265. # Gerber Editor
  2266. self.app.ui.grb_draw_pad.triggered.connect(self.on_pad_add)
  2267. self.app.ui.grb_draw_pad_array.triggered.connect(self.on_pad_add_array)
  2268. self.app.ui.grb_draw_track.triggered.connect(self.on_track_add)
  2269. self.app.ui.grb_draw_region.triggered.connect(self.on_region_add)
  2270. def disconnect_canvas_event_handlers(self):
  2271. # we restore the key and mouse control to FlatCAMApp method
  2272. # first connect to new, then disconnect the old handlers
  2273. # don't ask why but if there is nothing connected I've seen issues
  2274. self.canvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2275. self.canvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2276. self.canvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2277. self.canvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2278. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2279. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2280. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2281. self.canvas.vis_disconnect('mouse_release', self.on_grb_click_release)
  2282. try:
  2283. self.app.ui.popmenu_copy.triggered.disconnect(self.on_copy_button)
  2284. except TypeError:
  2285. pass
  2286. try:
  2287. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2288. except TypeError:
  2289. pass
  2290. try:
  2291. self.app.ui.popmenu_move.triggered.disconnect(self.on_move_button)
  2292. except TypeError:
  2293. pass
  2294. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2295. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2296. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2297. # Gerber Editor
  2298. try:
  2299. self.app.ui.grb_draw_pad.triggered.disconnect(self.on_pad_add)
  2300. except TypeError:
  2301. pass
  2302. try:
  2303. self.app.ui.grb_draw_pad_array.triggered.disconnect(self.on_pad_add_array)
  2304. except TypeError:
  2305. pass
  2306. try:
  2307. self.app.ui.grb_draw_track.triggered.disconnect(self.on_track_add)
  2308. except TypeError:
  2309. pass
  2310. try:
  2311. self.app.ui.grb_draw_region.triggered.disconnect(self.on_region_add)
  2312. except TypeError:
  2313. pass
  2314. def clear(self):
  2315. self.active_tool = None
  2316. # self.shape_buffer = []
  2317. self.selected = []
  2318. self.shapes.clear(update=True)
  2319. self.tool_shape.clear(update=True)
  2320. def flatten(self, geometry=None, reset=True, pathonly=False):
  2321. """
  2322. Creates a list of non-iterable linear geometry objects.
  2323. Polygons are expanded into its exterior pathonly param if specified.
  2324. Results are placed in flat_geometry
  2325. :param geometry: Shapely type or list or list of list of such.
  2326. :param reset: Clears the contents of self.flat_geometry.
  2327. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  2328. """
  2329. if reset:
  2330. self.flat_geometry = []
  2331. ## If iterable, expand recursively.
  2332. try:
  2333. for geo in geometry:
  2334. if geo is not None:
  2335. self.flatten(geometry=geo, reset=False, pathonly=pathonly)
  2336. ## Not iterable, do the actual indexing and add.
  2337. except TypeError:
  2338. if pathonly and type(geometry) == Polygon:
  2339. self.flat_geometry.append(geometry.exterior)
  2340. self.flatten(geometry=geometry.interiors,
  2341. reset=False,
  2342. pathonly=True)
  2343. else:
  2344. self.flat_geometry.append(geometry)
  2345. return self.flat_geometry
  2346. def edit_fcgerber(self, orig_grb_obj):
  2347. """
  2348. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  2349. into the editor.
  2350. :param fcgeometry: FlatCAMExcellon
  2351. :return: None
  2352. """
  2353. self.deactivate_grb_editor()
  2354. self.activate_grb_editor()
  2355. # create a reference to the source object
  2356. self.gerber_obj = orig_grb_obj
  2357. self.gerber_obj_options = orig_grb_obj.options
  2358. # Hide original geometry
  2359. orig_grb_obj.visible = False
  2360. # Set selection tolerance
  2361. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2362. self.select_tool("select")
  2363. # we activate this after the initial build as we don't need to see the tool been populated
  2364. self.apertures_table.itemChanged.connect(self.on_tool_edit)
  2365. # and then add it to the storage elements (each storage elements is a member of a list
  2366. def job_thread(self, apid):
  2367. with self.app.proc_container.new(_("Adding aperture: %s geo ...") % str(apid)):
  2368. solid_storage_elem = []
  2369. follow_storage_elem = []
  2370. self.storage_dict[apid] = {}
  2371. # add the Gerber geometry to editor storage
  2372. for k, v in self.gerber_obj.apertures[apid].items():
  2373. try:
  2374. if k == 'solid_geometry':
  2375. for geo in v:
  2376. if geo:
  2377. self.add_gerber_shape(DrawToolShape(geo), solid_storage_elem)
  2378. self.storage_dict[apid][k] = solid_storage_elem
  2379. elif k == 'follow_geometry':
  2380. for geo in v:
  2381. if geo is not None:
  2382. self.add_gerber_shape(DrawToolShape(geo), follow_storage_elem)
  2383. self.storage_dict[apid][k] = follow_storage_elem
  2384. else:
  2385. self.storage_dict[apid][k] = v
  2386. except Exception as e:
  2387. log.debug("FlatCAMGrbEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  2388. # Check promises and clear if exists
  2389. while True:
  2390. try:
  2391. self.grb_plot_promises.remove(apid)
  2392. time.sleep(0.5)
  2393. except ValueError:
  2394. break
  2395. for apid in self.gerber_obj.apertures:
  2396. self.grb_plot_promises.append(apid)
  2397. self.app.worker_task.emit({'fcn': job_thread, 'params': [self, apid]})
  2398. # do the delayed plot only if there is something to plot (the gerber is not empty)
  2399. if bool(self.gerber_obj.apertures):
  2400. self.start_delayed_plot(check_period=1000)
  2401. else:
  2402. self.set_ui()
  2403. # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  2404. self.build_ui(first_run=True)
  2405. # and add the first aperture to have something to play with
  2406. self.on_aperture_add('10')
  2407. def update_fcgerber(self, grb_obj):
  2408. """
  2409. Create a new Gerber object that contain the edited content of the source Gerber object
  2410. :param grb_obj: FlatCAMGerber
  2411. :return: None
  2412. """
  2413. new_grb_name = self.edited_obj_name
  2414. # if the 'delayed plot' malfunctioned stop the QTimer
  2415. try:
  2416. self.plot_thread.stop()
  2417. except:
  2418. pass
  2419. if "_edit" in self.edited_obj_name:
  2420. try:
  2421. id = int(self.edited_obj_name[-1]) + 1
  2422. new_grb_name= self.edited_obj_name[:-1] + str(id)
  2423. except ValueError:
  2424. new_grb_name += "_1"
  2425. else:
  2426. new_grb_name = self.edited_obj_name + "_edit"
  2427. self.app.worker_task.emit({'fcn': self.new_edited_gerber,
  2428. 'params': [new_grb_name]})
  2429. # reset the tool table
  2430. self.apertures_table.clear()
  2431. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  2432. self.last_aperture_selected = None
  2433. # restore GUI to the Selected TAB
  2434. # Remove anything else in the GUI
  2435. self.app.ui.selected_scroll_area.takeWidget()
  2436. # Switch notebook to Selected page
  2437. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2438. def update_options(self, obj):
  2439. try:
  2440. if not obj.options:
  2441. obj.options = {}
  2442. obj.options['xmin'] = 0
  2443. obj.options['ymin'] = 0
  2444. obj.options['xmax'] = 0
  2445. obj.options['ymax'] = 0
  2446. return True
  2447. else:
  2448. return False
  2449. except AttributeError:
  2450. obj.options = {}
  2451. return True
  2452. def new_edited_gerber(self, outname):
  2453. """
  2454. Creates a new Gerber object for the edited Gerber. Thread-safe.
  2455. :param outname: Name of the resulting object. None causes the name to be that of the file.
  2456. :type outname: str
  2457. :return: None
  2458. """
  2459. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  2460. self.gerber_obj.options['name'].upper())
  2461. out_name = outname
  2462. local_storage_dict = deepcopy(self.storage_dict)
  2463. # How the object should be initialized
  2464. def obj_init(grb_obj, app_obj):
  2465. poly_buffer = []
  2466. follow_buffer = []
  2467. for storage_apid, storage_val in local_storage_dict.items():
  2468. grb_obj.apertures[storage_apid] = {}
  2469. for k, v in storage_val.items():
  2470. if k == 'solid_geometry':
  2471. grb_obj.apertures[storage_apid][k] = []
  2472. for geo in v:
  2473. new_geo = deepcopy(geo.geo)
  2474. grb_obj.apertures[storage_apid][k].append(new_geo)
  2475. poly_buffer.append(new_geo)
  2476. elif k == 'follow_geometry':
  2477. grb_obj.apertures[storage_apid][k] = []
  2478. for geo in v:
  2479. new_geo = deepcopy(geo.geo)
  2480. grb_obj.apertures[storage_apid][k].append(new_geo)
  2481. follow_buffer.append(new_geo)
  2482. else:
  2483. grb_obj.apertures[storage_apid][k] = deepcopy(v)
  2484. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  2485. new_poly = MultiPolygon(poly_buffer)
  2486. new_poly = new_poly.buffer(0.00000001)
  2487. new_poly = new_poly.buffer(-0.00000001)
  2488. grb_obj.solid_geometry = new_poly
  2489. grb_obj.follow_geometry = deepcopy(follow_buffer)
  2490. for k, v in self.gerber_obj_options.items():
  2491. if k == 'name':
  2492. grb_obj.options[k] = out_name
  2493. else:
  2494. grb_obj.options[k] = deepcopy(v)
  2495. grb_obj.source_file = []
  2496. grb_obj.multigeo = False
  2497. grb_obj.follow = False
  2498. try:
  2499. grb_obj.create_geometry()
  2500. except KeyError:
  2501. self.app.inform.emit(
  2502. _( "[ERROR_NOTCL] There are no Aperture definitions in the file. Aborting Gerber creation.")
  2503. )
  2504. except:
  2505. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2506. msg += traceback.format_exc()
  2507. app_obj.inform.emit(msg)
  2508. raise
  2509. # raise
  2510. with self.app.proc_container.new(_("Creating Gerber.")):
  2511. try:
  2512. self.app.new_object("gerber", outname, obj_init)
  2513. except Exception as e:
  2514. log.error("Error on object creation: %s" % str(e))
  2515. self.app.progress.emit(100)
  2516. return
  2517. self.app.inform.emit(_("[success] Gerber editing finished."))
  2518. # self.progress.emit(100)
  2519. def on_tool_select(self, tool):
  2520. """
  2521. Behavior of the toolbar. Tool initialization.
  2522. :rtype : None
  2523. """
  2524. current_tool = tool
  2525. self.app.log.debug("on_tool_select('%s')" % tool)
  2526. if self.last_aperture_selected is None and current_tool is not 'select':
  2527. # self.draw_app.select_tool('select')
  2528. self.complete = True
  2529. current_tool = 'select'
  2530. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No aperture is selected"))
  2531. # This is to make the group behave as radio group
  2532. if current_tool in self.tools_gerber:
  2533. if self.tools_gerber[current_tool]["button"].isChecked():
  2534. self.app.log.debug("%s is checked." % current_tool)
  2535. for t in self.tools_gerber:
  2536. if t != current_tool:
  2537. self.tools_gerber[t]["button"].setChecked(False)
  2538. # this is where the Editor toolbar classes (button's) are instantiated
  2539. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  2540. # self.app.inform.emit(self.active_tool.start_msg)
  2541. else:
  2542. self.app.log.debug("%s is NOT checked." % current_tool)
  2543. for t in self.tools_gerber:
  2544. self.tools_gerber[t]["button"].setChecked(False)
  2545. self.select_tool('select')
  2546. self.active_tool = FCApertureSelect(self)
  2547. def on_row_selected(self, row, col):
  2548. if col == 0:
  2549. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2550. if self.app.defaults["global_mselect_key"] == 'Control':
  2551. modifier_to_use = Qt.ControlModifier
  2552. else:
  2553. modifier_to_use = Qt.ShiftModifier
  2554. if key_modifier == modifier_to_use:
  2555. pass
  2556. else:
  2557. self.selected = []
  2558. try:
  2559. # selected_apid = str(self.tool2tooldia[row + 1])
  2560. selected_apid = self.apertures_table.item(row, 1).text()
  2561. self.last_aperture_selected = copy(selected_apid)
  2562. for obj in self.storage_dict[selected_apid]['solid_geometry']:
  2563. self.selected.append(obj)
  2564. except Exception as e:
  2565. self.app.log.debug(str(e))
  2566. self.plot_all()
  2567. def toolbar_tool_toggle(self, key):
  2568. self.options[key] = self.sender().isChecked()
  2569. return self.options[key]
  2570. def on_grb_shape_complete(self, storage=None, specific_shape=None):
  2571. self.app.log.debug("on_shape_complete()")
  2572. if specific_shape:
  2573. geo = specific_shape
  2574. else:
  2575. geo = self.active_tool.geometry
  2576. if geo is None:
  2577. return
  2578. if storage is not None:
  2579. # Add shape
  2580. self.add_gerber_shape(geo, storage)
  2581. else:
  2582. stora = self.storage_dict[self.last_aperture_selected]['solid_geometry']
  2583. self.add_gerber_shape(geo, storage=stora)
  2584. # Remove any utility shapes
  2585. self.delete_utility_geometry()
  2586. self.tool_shape.clear(update=True)
  2587. # Replot and reset tool.
  2588. self.plot_all()
  2589. def add_gerber_shape(self, shape, storage):
  2590. """
  2591. Adds a shape to the shape storage.
  2592. :param shape: Shape to be added.
  2593. :type shape: DrawToolShape
  2594. :return: None
  2595. """
  2596. # List of DrawToolShape?
  2597. if isinstance(shape, list):
  2598. for subshape in shape:
  2599. self.add_gerber_shape(subshape, storage)
  2600. return
  2601. assert isinstance(shape, DrawToolShape), \
  2602. "Expected a DrawToolShape, got %s" % str(type(shape))
  2603. assert shape.geo is not None, \
  2604. "Shape object has empty geometry (None)"
  2605. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2606. not isinstance(shape.geo, list), \
  2607. "Shape objects has empty geometry ([])"
  2608. if isinstance(shape, DrawToolUtilityShape):
  2609. self.utility.append(shape)
  2610. else:
  2611. storage.append(shape) # TODO: Check performance
  2612. def on_canvas_click(self, event):
  2613. """
  2614. event.x and .y have canvas coordinates
  2615. event.xdaya and .ydata have plot coordinates
  2616. :param event: Event object dispatched by Matplotlib
  2617. :return: None
  2618. """
  2619. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2620. if self.app.grid_status():
  2621. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2622. self.app.app_cursor.enabled = True
  2623. # Update cursor
  2624. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2625. size=20)
  2626. else:
  2627. self.pos = (self.pos[0], self.pos[1])
  2628. self.app.app_cursor.enabled = False
  2629. if event.button is 1:
  2630. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2631. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2632. # Selection with left mouse button
  2633. if self.active_tool is not None and event.button is 1:
  2634. # Dispatch event to active_tool
  2635. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2636. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2637. # If it is a shape generating tool
  2638. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2639. if self.current_storage is not None:
  2640. self.on_grb_shape_complete(self.current_storage)
  2641. self.build_ui()
  2642. # MS: always return to the Select Tool if modifier key is not pressed
  2643. # else return to the current tool
  2644. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2645. if self.app.defaults["global_mselect_key"] == 'Control':
  2646. modifier_to_use = Qt.ControlModifier
  2647. else:
  2648. modifier_to_use = Qt.ShiftModifier
  2649. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2650. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2651. if key_modifier == modifier_to_use:
  2652. self.select_tool(self.active_tool.name)
  2653. else:
  2654. # return to Select tool but not for FCPad
  2655. if isinstance(self.active_tool, FCPad):
  2656. self.select_tool(self.active_tool.name)
  2657. else:
  2658. self.select_tool("select")
  2659. return
  2660. if isinstance(self.active_tool, FCApertureSelect):
  2661. # self.app.log.debug("Replotting after click.")
  2662. self.plot_all()
  2663. else:
  2664. self.app.log.debug("No active tool to respond to click!")
  2665. def on_grb_click_release(self, event):
  2666. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2667. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2668. if self.app.grid_status():
  2669. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2670. else:
  2671. pos = (pos_canvas[0], pos_canvas[1])
  2672. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2673. # canvas menu
  2674. try:
  2675. if event.button == 2: # right click
  2676. if self.app.ui.popMenu.mouse_is_panning is False:
  2677. if self.in_action is False:
  2678. try:
  2679. QtGui.QGuiApplication.restoreOverrideCursor()
  2680. except:
  2681. pass
  2682. if self.active_tool.complete is False and not isinstance(self.active_tool, FCApertureSelect):
  2683. self.active_tool.complete = True
  2684. self.in_action = False
  2685. self.delete_utility_geometry()
  2686. self.app.inform.emit(_("[success] Done."))
  2687. self.select_tool('select')
  2688. else:
  2689. self.app.cursor = QtGui.QCursor()
  2690. self.app.populate_cmenu_grids()
  2691. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2692. else:
  2693. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2694. # right mouse click will finish the action
  2695. if isinstance(self.active_tool, FCShapeTool):
  2696. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  2697. self.active_tool.make()
  2698. if self.active_tool.complete:
  2699. self.on_grb_shape_complete()
  2700. self.app.inform.emit(_("[success] Done."))
  2701. # MS: always return to the Select Tool if modifier key is not pressed
  2702. # else return to the current tool but not for FCTrack
  2703. if isinstance(self.active_tool, FCTrack):
  2704. self.select_tool(self.active_tool.name)
  2705. else:
  2706. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2707. if (self.app.defaults["global_mselect_key"] == 'Control' and
  2708. key_modifier == Qt.ControlModifier) or \
  2709. (self.app.defaults["global_mselect_key"] == 'Shift' and
  2710. key_modifier == Qt.ShiftModifier):
  2711. self.select_tool(self.active_tool.name)
  2712. else:
  2713. self.select_tool("select")
  2714. except Exception as e:
  2715. log.warning("Error: %s" % str(e))
  2716. raise
  2717. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2718. # selection and then select a type of selection ("enclosing" or "touching")
  2719. try:
  2720. if event.button == 1: # left click
  2721. if self.app.selection_type is not None:
  2722. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2723. self.app.selection_type = None
  2724. elif isinstance(self.active_tool, FCApertureSelect):
  2725. # Dispatch event to active_tool
  2726. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2727. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2728. # self.app.inform.emit(msg)
  2729. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2730. # if there are selected objects then plot them
  2731. if self.selected:
  2732. self.plot_all()
  2733. except Exception as e:
  2734. log.warning("Error: %s" % str(e))
  2735. raise
  2736. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2737. """
  2738. :param start_pos: mouse position when the selection LMB click was done
  2739. :param end_pos: mouse position when the left mouse button is released
  2740. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2741. :type Bool
  2742. :return:
  2743. """
  2744. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2745. sel_aperture = set()
  2746. self.apertures_table.clearSelection()
  2747. self.app.delete_selection_shape()
  2748. for storage in self.storage_dict:
  2749. for obj in self.storage_dict[storage]['solid_geometry']:
  2750. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2751. (sel_type is False and poly_selection.intersects(obj.geo)):
  2752. if self.key == self.app.defaults["global_mselect_key"]:
  2753. if obj in self.selected:
  2754. self.selected.remove(obj)
  2755. else:
  2756. # add the object to the selected shapes
  2757. self.selected.append(obj)
  2758. sel_aperture.add(storage)
  2759. else:
  2760. self.selected.append(obj)
  2761. sel_aperture.add(storage)
  2762. try:
  2763. self.apertures_table.cellPressed.disconnect()
  2764. except:
  2765. pass
  2766. # select the aperture code of the selected geometry, in the tool table
  2767. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2768. for aper in sel_aperture:
  2769. for row in range(self.apertures_table.rowCount()):
  2770. if str(aper) == self.apertures_table.item(row, 1).text():
  2771. self.apertures_table.selectRow(row)
  2772. self.last_aperture_selected = aper
  2773. self.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2774. self.apertures_table.cellPressed.connect(self.on_row_selected)
  2775. self.plot_all()
  2776. def on_canvas_move(self, event):
  2777. """
  2778. Called on 'mouse_move' event
  2779. event.pos have canvas screen coordinates
  2780. :param event: Event object dispatched by VisPy SceneCavas
  2781. :return: None
  2782. """
  2783. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2784. event.xdata, event.ydata = pos_canvas[0], pos_canvas[1]
  2785. self.x = event.xdata
  2786. self.y = event.ydata
  2787. self.app.ui.popMenu.mouse_is_panning = False
  2788. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2789. if event.button == 2 and event.is_dragging == 1:
  2790. self.app.ui.popMenu.mouse_is_panning = True
  2791. return
  2792. try:
  2793. x = float(event.xdata)
  2794. y = float(event.ydata)
  2795. except TypeError:
  2796. return
  2797. if self.active_tool is None:
  2798. return
  2799. ### Snap coordinates
  2800. if self.app.grid_status():
  2801. x, y = self.app.geo_editor.snap(x, y)
  2802. self.app.app_cursor.enabled = True
  2803. # Update cursor
  2804. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2805. else:
  2806. self.app.app_cursor.enabled = False
  2807. self.snap_x = x
  2808. self.snap_y = y
  2809. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2810. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2811. "<b>Y</b>: %.4f" % (x, y))
  2812. if self.pos is None:
  2813. self.pos = (0, 0)
  2814. dx = x - self.pos[0]
  2815. dy = y - self.pos[1]
  2816. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2817. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2818. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2819. ### Utility geometry (animated)
  2820. geo = self.active_tool.utility_geometry(data=(x, y))
  2821. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2822. # Remove any previous utility shape
  2823. self.tool_shape.clear(update=True)
  2824. self.draw_utility_geometry(geo=geo)
  2825. ### Selection area on canvas section ###
  2826. if event.is_dragging == 1 and event.button == 1:
  2827. # I make an exception for FCRegion and FCTrack because clicking and dragging while making regions can
  2828. # create strange issues like missing a point in a track/region
  2829. if isinstance(self.active_tool, FCRegion) or isinstance(self.active_tool, FCTrack):
  2830. pass
  2831. else:
  2832. dx = pos_canvas[0] - self.pos[0]
  2833. self.app.delete_selection_shape()
  2834. if dx < 0:
  2835. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2836. color=self.app.defaults["global_alt_sel_line"],
  2837. face_color=self.app.defaults['global_alt_sel_fill'])
  2838. self.app.selection_type = False
  2839. else:
  2840. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2841. self.app.selection_type = True
  2842. else:
  2843. self.app.selection_type = None
  2844. def on_canvas_key_release(self, event):
  2845. self.key = None
  2846. def draw_utility_geometry(self, geo):
  2847. if type(geo.geo) == list:
  2848. for el in geo.geo:
  2849. # Add the new utility shape
  2850. self.tool_shape.add(
  2851. shape=el, color=(self.app.defaults["global_draw_color"] + '80'),
  2852. # face_color=self.app.defaults['global_alt_sel_fill'],
  2853. update=False, layer=0, tolerance=None)
  2854. else:
  2855. # Add the new utility shape
  2856. self.tool_shape.add(
  2857. shape=geo.geo,
  2858. color=(self.app.defaults["global_draw_color"] + '80'),
  2859. # face_color=self.app.defaults['global_alt_sel_fill'],
  2860. update=False, layer=0, tolerance=None)
  2861. self.tool_shape.redraw()
  2862. def plot_all(self):
  2863. """
  2864. Plots all shapes in the editor.
  2865. :return: None
  2866. :rtype: None
  2867. """
  2868. with self.app.proc_container.new("Plotting"):
  2869. # self.app.log.debug("plot_all()")
  2870. self.shapes.clear(update=True)
  2871. for storage in self.storage_dict:
  2872. for shape in self.storage_dict[storage]['solid_geometry']:
  2873. if shape.geo is None:
  2874. continue
  2875. if shape in self.selected:
  2876. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'],
  2877. linewidth=2)
  2878. continue
  2879. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2880. for shape in self.utility:
  2881. self.plot_shape(geometry=shape.geo, linewidth=1)
  2882. continue
  2883. self.shapes.redraw()
  2884. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2885. """
  2886. Plots a geometric object or list of objects without rendering. Plotted objects
  2887. are returned as a list. This allows for efficient/animated rendering.
  2888. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2889. :param color: Shape color
  2890. :param linewidth: Width of lines in # of pixels.
  2891. :return: List of plotted elements.
  2892. """
  2893. # plot_elements = []
  2894. if geometry is None:
  2895. geometry = self.active_tool.geometry
  2896. try:
  2897. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0)
  2898. except AttributeError:
  2899. if type(geometry) == Point:
  2900. return
  2901. self.shapes.add(shape=geometry, color=color, face_color=color+'AF', layer=0)
  2902. def start_delayed_plot(self, check_period):
  2903. """
  2904. This function starts an QTImer and it will periodically check if all the workers finish the plotting functions
  2905. :param check_period: time at which to check periodically if all plots finished to be plotted
  2906. :return:
  2907. """
  2908. # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  2909. # self.plot_thread.start()
  2910. log.debug("FlatCAMGrbEditor --> Delayed Plot started.")
  2911. self.plot_thread = QtCore.QTimer()
  2912. self.plot_thread.setInterval(check_period)
  2913. self.plot_thread.timeout.connect(self.check_plot_finished)
  2914. self.plot_thread.start()
  2915. def check_plot_finished(self):
  2916. """
  2917. If all the promises made are finished then all the shapes are in shapes_storage and can be plotted safely and
  2918. then the UI is rebuilt accordingly.
  2919. :return:
  2920. """
  2921. try:
  2922. if not self.grb_plot_promises:
  2923. self.plot_thread.stop()
  2924. self.set_ui()
  2925. # now that we have data, create the GUI interface and add it to the Tool Tab
  2926. self.build_ui(first_run=True)
  2927. self.plot_all()
  2928. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  2929. # - perhaps is a bug in VisPy implementation
  2930. self.app.app_cursor.enabled = False
  2931. self.app.app_cursor.enabled = True
  2932. log.debug("FlatCAMGrbEditor --> delayed_plot finished")
  2933. except Exception:
  2934. traceback.print_exc()
  2935. def on_shape_complete(self):
  2936. self.app.log.debug("on_shape_complete()")
  2937. # Add shape
  2938. self.add_gerber_shape(self.active_tool.geometry)
  2939. # Remove any utility shapes
  2940. self.delete_utility_geometry()
  2941. self.tool_shape.clear(update=True)
  2942. # Replot and reset tool.
  2943. self.plot_all()
  2944. # self.active_tool = type(self.active_tool)(self)
  2945. def get_selected(self):
  2946. """
  2947. Returns list of shapes that are selected in the editor.
  2948. :return: List of shapes.
  2949. """
  2950. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2951. return self.selected
  2952. def delete_selected(self):
  2953. temp_ref = [s for s in self.selected]
  2954. if len(temp_ref) == 0:
  2955. self.app.inform.emit(_("[ERROR_NOTCL] Failed. No aperture geometry is selected."))
  2956. return
  2957. for shape_sel in temp_ref:
  2958. self.delete_shape(shape_sel)
  2959. self.selected = []
  2960. self.build_ui()
  2961. self.app.inform.emit(_("[success] Done. Apertures geometry deleted."))
  2962. def delete_shape(self, shape):
  2963. self.is_modified = True
  2964. if shape in self.utility:
  2965. self.utility.remove(shape)
  2966. return
  2967. for storage in self.storage_dict:
  2968. # try:
  2969. # self.storage_dict[storage].remove(shape)
  2970. # except:
  2971. # pass
  2972. if shape in self.storage_dict[storage]['solid_geometry']:
  2973. self.storage_dict[storage]['solid_geometry'].remove(shape)
  2974. if shape in self.selected:
  2975. self.selected.remove(shape) # TODO: Check performance
  2976. def delete_utility_geometry(self):
  2977. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2978. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2979. for_deletion = [shape for shape in self.utility]
  2980. for shape in for_deletion:
  2981. self.delete_shape(shape)
  2982. self.tool_shape.clear(update=True)
  2983. self.tool_shape.redraw()
  2984. def on_delete_btn(self):
  2985. self.delete_selected()
  2986. self.plot_all()
  2987. def select_tool(self, toolname):
  2988. """
  2989. Selects a drawing tool. Impacts the object and GUI.
  2990. :param toolname: Name of the tool.
  2991. :return: None
  2992. """
  2993. self.tools_gerber[toolname]["button"].setChecked(True)
  2994. self.on_tool_select(toolname)
  2995. def set_selected(self, shape):
  2996. # Remove and add to the end.
  2997. if shape in self.selected:
  2998. self.selected.remove(shape)
  2999. self.selected.append(shape)
  3000. def set_unselected(self, shape):
  3001. if shape in self.selected:
  3002. self.selected.remove(shape)
  3003. def on_array_type_combo(self):
  3004. if self.array_type_combo.currentIndex() == 0:
  3005. self.array_circular_frame.hide()
  3006. self.array_linear_frame.show()
  3007. else:
  3008. self.delete_utility_geometry()
  3009. self.array_circular_frame.show()
  3010. self.array_linear_frame.hide()
  3011. self.app.inform.emit(_("Click on the circular array Center position"))
  3012. def on_linear_angle_radio(self):
  3013. val = self.pad_axis_radio.get_value()
  3014. if val == 'A':
  3015. self.linear_angle_spinner.show()
  3016. self.linear_angle_label.show()
  3017. else:
  3018. self.linear_angle_spinner.hide()
  3019. self.linear_angle_label.hide()
  3020. def on_copy_button(self):
  3021. self.select_tool('copy')
  3022. return
  3023. def on_move_button(self):
  3024. self.select_tool('move')
  3025. return
  3026. def on_pad_add(self):
  3027. self.select_tool('pad')
  3028. def on_pad_add_array(self):
  3029. self.select_tool('array')
  3030. def on_track_add(self):
  3031. self.select_tool('track')
  3032. def on_region_add(self):
  3033. self.select_tool('region')
  3034. def on_poligonize(self):
  3035. self.select_tool('poligonize')
  3036. def on_disc_add(self):
  3037. self.select_tool('disc')
  3038. def on_add_semidisc(self):
  3039. self.select_tool('semidisc')
  3040. def on_buffer(self):
  3041. buff_value = 0.01
  3042. log.debug("FlatCAMGrbEditor.on_buffer()")
  3043. try:
  3044. buff_value = float(self.buffer_distance_entry.get_value())
  3045. except ValueError:
  3046. # try to convert comma to decimal point. if it's still not working error message and return
  3047. try:
  3048. buff_value = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  3049. self.buffer_distance_entry.set_value(buff_value)
  3050. except ValueError:
  3051. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  3052. "Add it and retry."))
  3053. return
  3054. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  3055. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  3056. join_style = self.buffer_corner_cb.currentIndex() + 1
  3057. def buffer_recursion(geom, selection):
  3058. if type(geom) == list or type(geom) is MultiPolygon:
  3059. geoms = list()
  3060. for local_geom in geom:
  3061. geoms.append(buffer_recursion(local_geom, selection=selection))
  3062. return geoms
  3063. else:
  3064. if geom in selection:
  3065. return DrawToolShape(geom.geo.buffer(buff_value, join_style=join_style))
  3066. else:
  3067. return geom
  3068. if not self.apertures_table.selectedItems():
  3069. self.app.inform.emit(_(
  3070. "[WARNING_NOTCL] No aperture to buffer. Select at least one aperture and try again."
  3071. ))
  3072. return
  3073. for x in self.apertures_table.selectedItems():
  3074. try:
  3075. apid = self.apertures_table.item(x.row(), 1).text()
  3076. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3077. self.storage_dict[apid]['solid_geometry'] = []
  3078. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3079. except Exception as e:
  3080. log.debug("FlatCAMGrbEditor.buffer() --> %s" % str(e))
  3081. self.plot_all()
  3082. self.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  3083. def on_scale(self):
  3084. scale_factor = 1.0
  3085. log.debug("FlatCAMGrbEditor.on_scale()")
  3086. try:
  3087. scale_factor = float(self.scale_factor_entry.get_value())
  3088. except ValueError:
  3089. # try to convert comma to decimal point. if it's still not working error message and return
  3090. try:
  3091. scale_factor = float(self.scale_factor_entry.get_value().replace(',', '.'))
  3092. self.scale_factor_entry.set_value(scale_factor)
  3093. except ValueError:
  3094. self.app.inform.emit(_("[WARNING_NOTCL] Scale factor value is missing or wrong format. "
  3095. "Add it and retry."))
  3096. return
  3097. def scale_recursion(geom, selection):
  3098. if type(geom) == list or type(geom) is MultiPolygon:
  3099. geoms = list()
  3100. for local_geom in geom:
  3101. geoms.append(scale_recursion(local_geom, selection=selection))
  3102. return geoms
  3103. else:
  3104. if geom in selection:
  3105. return DrawToolShape(affinity.scale(geom.geo, scale_factor, scale_factor, origin='center'))
  3106. else:
  3107. return geom
  3108. if not self.apertures_table.selectedItems():
  3109. self.app.inform.emit(_(
  3110. "[WARNING_NOTCL] No aperture to scale. Select at least one aperture and try again."
  3111. ))
  3112. return
  3113. for x in self.apertures_table.selectedItems():
  3114. try:
  3115. apid = self.apertures_table.item(x.row(), 1).text()
  3116. temp_storage = deepcopy(scale_recursion(self.storage_dict[apid]['solid_geometry'], self.selected))
  3117. self.storage_dict[apid]['solid_geometry'] = []
  3118. self.storage_dict[apid]['solid_geometry'] = temp_storage
  3119. except Exception as e:
  3120. log.debug("FlatCAMGrbEditor.on_scale() --> %s" % str(e))
  3121. self.plot_all()
  3122. self.app.inform.emit(_("[success] Done. Scale Tool completed."))
  3123. def on_transform(self):
  3124. if type(self.active_tool) == FCTransform:
  3125. self.select_tool('select')
  3126. else:
  3127. self.select_tool('transform')
  3128. def hide_tool(self, tool_name):
  3129. # self.app.ui.notebook.setTabText(2, _("Tools"))
  3130. if tool_name == 'all':
  3131. self.apertures_frame.hide()
  3132. if tool_name == 'select':
  3133. self.apertures_frame.show()
  3134. if tool_name == 'buffer' or tool_name == 'all':
  3135. self.buffer_tool_frame.hide()
  3136. if tool_name == 'scale' or tool_name == 'all':
  3137. self.scale_tool_frame.hide()
  3138. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3139. class TransformEditorTool(FlatCAMTool):
  3140. """
  3141. Inputs to specify how to paint the selected polygons.
  3142. """
  3143. toolName = _("Transform Tool")
  3144. rotateName = _("Rotate")
  3145. skewName = _("Skew/Shear")
  3146. scaleName = _("Scale")
  3147. flipName = _("Mirror (Flip)")
  3148. offsetName = _("Offset")
  3149. def __init__(self, app, draw_app):
  3150. FlatCAMTool.__init__(self, app)
  3151. self.app = app
  3152. self.draw_app = draw_app
  3153. self.transform_lay = QtWidgets.QVBoxLayout()
  3154. self.layout.addLayout(self.transform_lay)
  3155. ## Title
  3156. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  3157. title_label.setStyleSheet("""
  3158. QLabel
  3159. {
  3160. font-size: 16px;
  3161. font-weight: bold;
  3162. }
  3163. """)
  3164. self.transform_lay.addWidget(title_label)
  3165. self.empty_label = QtWidgets.QLabel("")
  3166. self.empty_label.setFixedWidth(50)
  3167. self.empty_label1 = QtWidgets.QLabel("")
  3168. self.empty_label1.setFixedWidth(70)
  3169. self.empty_label2 = QtWidgets.QLabel("")
  3170. self.empty_label2.setFixedWidth(70)
  3171. self.empty_label3 = QtWidgets.QLabel("")
  3172. self.empty_label3.setFixedWidth(70)
  3173. self.empty_label4 = QtWidgets.QLabel("")
  3174. self.empty_label4.setFixedWidth(70)
  3175. self.transform_lay.addWidget(self.empty_label)
  3176. ## Rotate Title
  3177. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  3178. self.transform_lay.addWidget(rotate_title_label)
  3179. ## Layout
  3180. form_layout = QtWidgets.QFormLayout()
  3181. self.transform_lay.addLayout(form_layout)
  3182. form_child = QtWidgets.QHBoxLayout()
  3183. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  3184. self.rotate_label.setToolTip(
  3185. _("Angle for Rotation action, in degrees.\n"
  3186. "Float number between -360 and 359.\n"
  3187. "Positive numbers for CW motion.\n"
  3188. "Negative numbers for CCW motion.")
  3189. )
  3190. self.rotate_label.setFixedWidth(50)
  3191. self.rotate_entry = FCEntry()
  3192. # self.rotate_entry.setFixedWidth(60)
  3193. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3194. self.rotate_button = FCButton()
  3195. self.rotate_button.set_value(_("Rotate"))
  3196. self.rotate_button.setToolTip(
  3197. _("Rotate the selected shape(s).\n"
  3198. "The point of reference is the middle of\n"
  3199. "the bounding box for all selected shapes.")
  3200. )
  3201. self.rotate_button.setFixedWidth(60)
  3202. form_child.addWidget(self.rotate_entry)
  3203. form_child.addWidget(self.rotate_button)
  3204. form_layout.addRow(self.rotate_label, form_child)
  3205. self.transform_lay.addWidget(self.empty_label1)
  3206. ## Skew Title
  3207. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  3208. self.transform_lay.addWidget(skew_title_label)
  3209. ## Form Layout
  3210. form1_layout = QtWidgets.QFormLayout()
  3211. self.transform_lay.addLayout(form1_layout)
  3212. form1_child_1 = QtWidgets.QHBoxLayout()
  3213. form1_child_2 = QtWidgets.QHBoxLayout()
  3214. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  3215. self.skewx_label.setToolTip(
  3216. _("Angle for Skew action, in degrees.\n"
  3217. "Float number between -360 and 359.")
  3218. )
  3219. self.skewx_label.setFixedWidth(50)
  3220. self.skewx_entry = FCEntry()
  3221. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3222. # self.skewx_entry.setFixedWidth(60)
  3223. self.skewx_button = FCButton()
  3224. self.skewx_button.set_value(_("Skew X"))
  3225. self.skewx_button.setToolTip(
  3226. _("Skew/shear the selected shape(s).\n"
  3227. "The point of reference is the middle of\n"
  3228. "the bounding box for all selected shapes."))
  3229. self.skewx_button.setFixedWidth(60)
  3230. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  3231. self.skewy_label.setToolTip(
  3232. _("Angle for Skew action, in degrees.\n"
  3233. "Float number between -360 and 359.")
  3234. )
  3235. self.skewy_label.setFixedWidth(50)
  3236. self.skewy_entry = FCEntry()
  3237. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3238. # self.skewy_entry.setFixedWidth(60)
  3239. self.skewy_button = FCButton()
  3240. self.skewy_button.set_value(_("Skew Y"))
  3241. self.skewy_button.setToolTip(
  3242. _("Skew/shear the selected shape(s).\n"
  3243. "The point of reference is the middle of\n"
  3244. "the bounding box for all selected shapes."))
  3245. self.skewy_button.setFixedWidth(60)
  3246. form1_child_1.addWidget(self.skewx_entry)
  3247. form1_child_1.addWidget(self.skewx_button)
  3248. form1_child_2.addWidget(self.skewy_entry)
  3249. form1_child_2.addWidget(self.skewy_button)
  3250. form1_layout.addRow(self.skewx_label, form1_child_1)
  3251. form1_layout.addRow(self.skewy_label, form1_child_2)
  3252. self.transform_lay.addWidget(self.empty_label2)
  3253. ## Scale Title
  3254. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  3255. self.transform_lay.addWidget(scale_title_label)
  3256. ## Form Layout
  3257. form2_layout = QtWidgets.QFormLayout()
  3258. self.transform_lay.addLayout(form2_layout)
  3259. form2_child_1 = QtWidgets.QHBoxLayout()
  3260. form2_child_2 = QtWidgets.QHBoxLayout()
  3261. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  3262. self.scalex_label.setToolTip(
  3263. _("Factor for Scale action over X axis.")
  3264. )
  3265. self.scalex_label.setFixedWidth(50)
  3266. self.scalex_entry = FCEntry()
  3267. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3268. # self.scalex_entry.setFixedWidth(60)
  3269. self.scalex_button = FCButton()
  3270. self.scalex_button.set_value(_("Scale X"))
  3271. self.scalex_button.setToolTip(
  3272. _("Scale the selected shape(s).\n"
  3273. "The point of reference depends on \n"
  3274. "the Scale reference checkbox state."))
  3275. self.scalex_button.setFixedWidth(60)
  3276. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  3277. self.scaley_label.setToolTip(
  3278. _("Factor for Scale action over Y axis.")
  3279. )
  3280. self.scaley_label.setFixedWidth(50)
  3281. self.scaley_entry = FCEntry()
  3282. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3283. # self.scaley_entry.setFixedWidth(60)
  3284. self.scaley_button = FCButton()
  3285. self.scaley_button.set_value(_("Scale Y"))
  3286. self.scaley_button.setToolTip(
  3287. _("Scale the selected shape(s).\n"
  3288. "The point of reference depends on \n"
  3289. "the Scale reference checkbox state."))
  3290. self.scaley_button.setFixedWidth(60)
  3291. self.scale_link_cb = FCCheckBox()
  3292. self.scale_link_cb.set_value(True)
  3293. self.scale_link_cb.setText(_("Link"))
  3294. self.scale_link_cb.setToolTip(
  3295. _("Scale the selected shape(s)\n"
  3296. "using the Scale Factor X for both axis."))
  3297. self.scale_link_cb.setFixedWidth(50)
  3298. self.scale_zero_ref_cb = FCCheckBox()
  3299. self.scale_zero_ref_cb.set_value(True)
  3300. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  3301. self.scale_zero_ref_cb.setToolTip(
  3302. _("Scale the selected shape(s)\n"
  3303. "using the origin reference when checked,\n"
  3304. "and the center of the biggest bounding box\n"
  3305. "of the selected shapes when unchecked."))
  3306. form2_child_1.addWidget(self.scalex_entry)
  3307. form2_child_1.addWidget(self.scalex_button)
  3308. form2_child_2.addWidget(self.scaley_entry)
  3309. form2_child_2.addWidget(self.scaley_button)
  3310. form2_layout.addRow(self.scalex_label, form2_child_1)
  3311. form2_layout.addRow(self.scaley_label, form2_child_2)
  3312. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  3313. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button],
  3314. logic=False)
  3315. self.transform_lay.addWidget(self.empty_label3)
  3316. ## Offset Title
  3317. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  3318. self.transform_lay.addWidget(offset_title_label)
  3319. ## Form Layout
  3320. form3_layout = QtWidgets.QFormLayout()
  3321. self.transform_lay.addLayout(form3_layout)
  3322. form3_child_1 = QtWidgets.QHBoxLayout()
  3323. form3_child_2 = QtWidgets.QHBoxLayout()
  3324. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  3325. self.offx_label.setToolTip(
  3326. _("Value for Offset action on X axis.")
  3327. )
  3328. self.offx_label.setFixedWidth(50)
  3329. self.offx_entry = FCEntry()
  3330. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3331. # self.offx_entry.setFixedWidth(60)
  3332. self.offx_button = FCButton()
  3333. self.offx_button.set_value(_("Offset X"))
  3334. self.offx_button.setToolTip(
  3335. _("Offset the selected shape(s).\n"
  3336. "The point of reference is the middle of\n"
  3337. "the bounding box for all selected shapes.\n")
  3338. )
  3339. self.offx_button.setFixedWidth(60)
  3340. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  3341. self.offy_label.setToolTip(
  3342. _("Value for Offset action on Y axis.")
  3343. )
  3344. self.offy_label.setFixedWidth(50)
  3345. self.offy_entry = FCEntry()
  3346. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3347. # self.offy_entry.setFixedWidth(60)
  3348. self.offy_button = FCButton()
  3349. self.offy_button.set_value(_("Offset Y"))
  3350. self.offy_button.setToolTip(
  3351. _("Offset the selected shape(s).\n"
  3352. "The point of reference is the middle of\n"
  3353. "the bounding box for all selected shapes.\n")
  3354. )
  3355. self.offy_button.setFixedWidth(60)
  3356. form3_child_1.addWidget(self.offx_entry)
  3357. form3_child_1.addWidget(self.offx_button)
  3358. form3_child_2.addWidget(self.offy_entry)
  3359. form3_child_2.addWidget(self.offy_button)
  3360. form3_layout.addRow(self.offx_label, form3_child_1)
  3361. form3_layout.addRow(self.offy_label, form3_child_2)
  3362. self.transform_lay.addWidget(self.empty_label4)
  3363. ## Flip Title
  3364. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  3365. self.transform_lay.addWidget(flip_title_label)
  3366. ## Form Layout
  3367. form4_layout = QtWidgets.QFormLayout()
  3368. form4_child_hlay = QtWidgets.QHBoxLayout()
  3369. self.transform_lay.addLayout(form4_child_hlay)
  3370. self.transform_lay.addLayout(form4_layout)
  3371. form4_child_1 = QtWidgets.QHBoxLayout()
  3372. self.flipx_button = FCButton()
  3373. self.flipx_button.set_value(_("Flip on X"))
  3374. self.flipx_button.setToolTip(
  3375. _("Flip the selected shape(s) over the X axis.\n"
  3376. "Does not create a new shape.")
  3377. )
  3378. self.flipx_button.setFixedWidth(60)
  3379. self.flipy_button = FCButton()
  3380. self.flipy_button.set_value(_("Flip on Y"))
  3381. self.flipy_button.setToolTip(
  3382. _("Flip the selected shape(s) over the X axis.\n"
  3383. "Does not create a new shape.")
  3384. )
  3385. self.flipy_button.setFixedWidth(60)
  3386. self.flip_ref_cb = FCCheckBox()
  3387. self.flip_ref_cb.set_value(True)
  3388. self.flip_ref_cb.setText(_("Ref Pt"))
  3389. self.flip_ref_cb.setToolTip(
  3390. _("Flip the selected shape(s)\n"
  3391. "around the point in Point Entry Field.\n"
  3392. "\n"
  3393. "The point coordinates can be captured by\n"
  3394. "left click on canvas together with pressing\n"
  3395. "SHIFT key. \n"
  3396. "Then click Add button to insert coordinates.\n"
  3397. "Or enter the coords in format (x, y) in the\n"
  3398. "Point Entry field and click Flip on X(Y)")
  3399. )
  3400. self.flip_ref_cb.setFixedWidth(50)
  3401. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  3402. self.flip_ref_label.setToolTip(
  3403. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  3404. "The 'x' in (x, y) will be used when using Flip on X and\n"
  3405. "the 'y' in (x, y) will be used when using Flip on Y.")
  3406. )
  3407. self.flip_ref_label.setFixedWidth(50)
  3408. self.flip_ref_entry = EvalEntry2("(0, 0)")
  3409. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  3410. # self.flip_ref_entry.setFixedWidth(60)
  3411. self.flip_ref_button = FCButton()
  3412. self.flip_ref_button.set_value(_("Add"))
  3413. self.flip_ref_button.setToolTip(
  3414. _("The point coordinates can be captured by\n"
  3415. "left click on canvas together with pressing\n"
  3416. "SHIFT key. Then click Add button to insert.")
  3417. )
  3418. self.flip_ref_button.setFixedWidth(60)
  3419. form4_child_hlay.addStretch()
  3420. form4_child_hlay.addWidget(self.flipx_button)
  3421. form4_child_hlay.addWidget(self.flipy_button)
  3422. form4_child_1.addWidget(self.flip_ref_entry)
  3423. form4_child_1.addWidget(self.flip_ref_button)
  3424. form4_layout.addRow(self.flip_ref_cb)
  3425. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  3426. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  3427. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  3428. self.transform_lay.addStretch()
  3429. ## Signals
  3430. self.rotate_button.clicked.connect(self.on_rotate)
  3431. self.skewx_button.clicked.connect(self.on_skewx)
  3432. self.skewy_button.clicked.connect(self.on_skewy)
  3433. self.scalex_button.clicked.connect(self.on_scalex)
  3434. self.scaley_button.clicked.connect(self.on_scaley)
  3435. self.offx_button.clicked.connect(self.on_offx)
  3436. self.offy_button.clicked.connect(self.on_offy)
  3437. self.flipx_button.clicked.connect(self.on_flipx)
  3438. self.flipy_button.clicked.connect(self.on_flipy)
  3439. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  3440. self.rotate_entry.returnPressed.connect(self.on_rotate)
  3441. self.skewx_entry.returnPressed.connect(self.on_skewx)
  3442. self.skewy_entry.returnPressed.connect(self.on_skewy)
  3443. self.scalex_entry.returnPressed.connect(self.on_scalex)
  3444. self.scaley_entry.returnPressed.connect(self.on_scaley)
  3445. self.offx_entry.returnPressed.connect(self.on_offx)
  3446. self.offy_entry.returnPressed.connect(self.on_offy)
  3447. self.set_tool_ui()
  3448. def run(self, toggle=True):
  3449. self.app.report_usage("Geo Editor Transform Tool()")
  3450. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3451. if self.app.ui.splitter.sizes()[0] == 0:
  3452. self.app.ui.splitter.setSizes([1, 1])
  3453. if toggle:
  3454. try:
  3455. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  3456. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3457. else:
  3458. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  3459. except AttributeError:
  3460. pass
  3461. FlatCAMTool.run(self)
  3462. self.set_tool_ui()
  3463. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  3464. def install(self, icon=None, separator=None, **kwargs):
  3465. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  3466. def set_tool_ui(self):
  3467. ## Initialize form
  3468. if self.app.defaults["tools_transform_rotate"]:
  3469. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  3470. else:
  3471. self.rotate_entry.set_value(0.0)
  3472. if self.app.defaults["tools_transform_skew_x"]:
  3473. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  3474. else:
  3475. self.skewx_entry.set_value(0.0)
  3476. if self.app.defaults["tools_transform_skew_y"]:
  3477. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  3478. else:
  3479. self.skewy_entry.set_value(0.0)
  3480. if self.app.defaults["tools_transform_scale_x"]:
  3481. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  3482. else:
  3483. self.scalex_entry.set_value(1.0)
  3484. if self.app.defaults["tools_transform_scale_y"]:
  3485. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  3486. else:
  3487. self.scaley_entry.set_value(1.0)
  3488. if self.app.defaults["tools_transform_scale_link"]:
  3489. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  3490. else:
  3491. self.scale_link_cb.set_value(True)
  3492. if self.app.defaults["tools_transform_scale_reference"]:
  3493. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  3494. else:
  3495. self.scale_zero_ref_cb.set_value(True)
  3496. if self.app.defaults["tools_transform_offset_x"]:
  3497. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  3498. else:
  3499. self.offx_entry.set_value(0.0)
  3500. if self.app.defaults["tools_transform_offset_y"]:
  3501. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  3502. else:
  3503. self.offy_entry.set_value(0.0)
  3504. if self.app.defaults["tools_transform_mirror_reference"]:
  3505. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  3506. else:
  3507. self.flip_ref_cb.set_value(False)
  3508. if self.app.defaults["tools_transform_mirror_point"]:
  3509. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  3510. else:
  3511. self.flip_ref_entry.set_value((0, 0))
  3512. def template(self):
  3513. if not self.fcdraw.selected:
  3514. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  3515. return
  3516. self.draw_app.select_tool("select")
  3517. self.app.ui.notebook.setTabText(2, "Tools")
  3518. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  3519. self.app.ui.splitter.setSizes([0, 1])
  3520. def on_rotate(self, sig=None, val=None):
  3521. if val:
  3522. value = val
  3523. else:
  3524. try:
  3525. value = float(self.rotate_entry.get_value())
  3526. except ValueError:
  3527. # try to convert comma to decimal point. if it's still not working error message and return
  3528. try:
  3529. value = float(self.rotate_entry.get_value().replace(',', '.'))
  3530. except ValueError:
  3531. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  3532. "use a number."))
  3533. return
  3534. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  3535. 'params': [value]})
  3536. # self.on_rotate_action(value)
  3537. return
  3538. def on_flipx(self):
  3539. # self.on_flip("Y")
  3540. axis = 'Y'
  3541. self.app.worker_task.emit({'fcn': self.on_flip,
  3542. 'params': [axis]})
  3543. return
  3544. def on_flipy(self):
  3545. # self.on_flip("X")
  3546. axis = 'X'
  3547. self.app.worker_task.emit({'fcn': self.on_flip,
  3548. 'params': [axis]})
  3549. return
  3550. def on_flip_add_coords(self):
  3551. val = self.app.clipboard.text()
  3552. self.flip_ref_entry.set_value(val)
  3553. def on_skewx(self, sig=None, val=None):
  3554. if val:
  3555. value = val
  3556. else:
  3557. try:
  3558. value = float(self.skewx_entry.get_value())
  3559. except ValueError:
  3560. # try to convert comma to decimal point. if it's still not working error message and return
  3561. try:
  3562. value = float(self.skewx_entry.get_value().replace(',', '.'))
  3563. except ValueError:
  3564. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  3565. "use a number."))
  3566. return
  3567. # self.on_skew("X", value)
  3568. axis = 'X'
  3569. self.app.worker_task.emit({'fcn': self.on_skew,
  3570. 'params': [axis, value]})
  3571. return
  3572. def on_skewy(self, sig=None, val=None):
  3573. if val:
  3574. value = val
  3575. else:
  3576. try:
  3577. value = float(self.skewy_entry.get_value())
  3578. except ValueError:
  3579. # try to convert comma to decimal point. if it's still not working error message and return
  3580. try:
  3581. value = float(self.skewy_entry.get_value().replace(',', '.'))
  3582. except ValueError:
  3583. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  3584. "use a number."))
  3585. return
  3586. # self.on_skew("Y", value)
  3587. axis = 'Y'
  3588. self.app.worker_task.emit({'fcn': self.on_skew,
  3589. 'params': [axis, value]})
  3590. return
  3591. def on_scalex(self, sig=None, val=None):
  3592. if val:
  3593. xvalue = val
  3594. else:
  3595. try:
  3596. xvalue = float(self.scalex_entry.get_value())
  3597. except ValueError:
  3598. # try to convert comma to decimal point. if it's still not working error message and return
  3599. try:
  3600. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  3601. except ValueError:
  3602. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  3603. "use a number."))
  3604. return
  3605. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3606. if xvalue == 0:
  3607. xvalue = 1
  3608. if self.scale_link_cb.get_value():
  3609. yvalue = xvalue
  3610. else:
  3611. yvalue = 1
  3612. axis = 'X'
  3613. point = (0, 0)
  3614. if self.scale_zero_ref_cb.get_value():
  3615. self.app.worker_task.emit({'fcn': self.on_scale,
  3616. 'params': [axis, xvalue, yvalue, point]})
  3617. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  3618. else:
  3619. # self.on_scale("X", xvalue, yvalue)
  3620. self.app.worker_task.emit({'fcn': self.on_scale,
  3621. 'params': [axis, xvalue, yvalue]})
  3622. return
  3623. def on_scaley(self, sig=None, val=None):
  3624. xvalue = 1
  3625. if val:
  3626. yvalue = val
  3627. else:
  3628. try:
  3629. yvalue = float(self.scaley_entry.get_value())
  3630. except ValueError:
  3631. # try to convert comma to decimal point. if it's still not working error message and return
  3632. try:
  3633. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  3634. except ValueError:
  3635. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  3636. "use a number."))
  3637. return
  3638. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  3639. if yvalue == 0:
  3640. yvalue = 1
  3641. axis = 'Y'
  3642. point = (0, 0)
  3643. if self.scale_zero_ref_cb.get_value():
  3644. self.app.worker_task.emit({'fcn': self.on_scale,
  3645. 'params': [axis, xvalue, yvalue, point]})
  3646. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  3647. else:
  3648. # self.on_scale("Y", xvalue, yvalue)
  3649. self.app.worker_task.emit({'fcn': self.on_scale,
  3650. 'params': [axis, xvalue, yvalue]})
  3651. return
  3652. def on_offx(self, sig=None, val=None):
  3653. if val:
  3654. value = val
  3655. else:
  3656. try:
  3657. value = float(self.offx_entry.get_value())
  3658. except ValueError:
  3659. # try to convert comma to decimal point. if it's still not working error message and return
  3660. try:
  3661. value = float(self.offx_entry.get_value().replace(',', '.'))
  3662. except ValueError:
  3663. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  3664. "use a number."))
  3665. return
  3666. # self.on_offset("X", value)
  3667. axis = 'X'
  3668. self.app.worker_task.emit({'fcn': self.on_offset,
  3669. 'params': [axis, value]})
  3670. return
  3671. def on_offy(self, sig=None, val=None):
  3672. if val:
  3673. value = val
  3674. else:
  3675. try:
  3676. value = float(self.offy_entry.get_value())
  3677. except ValueError:
  3678. # try to convert comma to decimal point. if it's still not working error message and return
  3679. try:
  3680. value = float(self.offy_entry.get_value().replace(',', '.'))
  3681. except ValueError:
  3682. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  3683. "use a number."))
  3684. return
  3685. # self.on_offset("Y", value)
  3686. axis = 'Y'
  3687. self.app.worker_task.emit({'fcn': self.on_offset,
  3688. 'params': [axis, value]})
  3689. return
  3690. def on_rotate_action(self, num):
  3691. shape_list = self.draw_app.selected
  3692. xminlist = []
  3693. yminlist = []
  3694. xmaxlist = []
  3695. ymaxlist = []
  3696. if not shape_list:
  3697. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  3698. return
  3699. else:
  3700. with self.app.proc_container.new(_("Appying Rotate")):
  3701. try:
  3702. # first get a bounding box to fit all
  3703. for sha in shape_list:
  3704. xmin, ymin, xmax, ymax = sha.bounds()
  3705. xminlist.append(xmin)
  3706. yminlist.append(ymin)
  3707. xmaxlist.append(xmax)
  3708. ymaxlist.append(ymax)
  3709. # get the minimum x,y and maximum x,y for all objects selected
  3710. xminimal = min(xminlist)
  3711. yminimal = min(yminlist)
  3712. xmaximal = max(xmaxlist)
  3713. ymaximal = max(ymaxlist)
  3714. self.app.progress.emit(20)
  3715. for sel_sha in shape_list:
  3716. px = 0.5 * (xminimal + xmaximal)
  3717. py = 0.5 * (yminimal + ymaximal)
  3718. sel_sha.rotate(-num, point=(px, py))
  3719. self.draw_app.plot_all()
  3720. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  3721. # self.draw_app.transform_complete.emit()
  3722. self.app.inform.emit(_("[success] Done. Rotate completed."))
  3723. self.app.progress.emit(100)
  3724. except Exception as e:
  3725. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3726. return
  3727. def on_flip(self, axis):
  3728. shape_list = self.draw_app.selected
  3729. xminlist = []
  3730. yminlist = []
  3731. xmaxlist = []
  3732. ymaxlist = []
  3733. if not shape_list:
  3734. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  3735. return
  3736. else:
  3737. with self.app.proc_container.new(_("Applying Flip")):
  3738. try:
  3739. # get mirroring coords from the point entry
  3740. if self.flip_ref_cb.isChecked():
  3741. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  3742. # get mirroing coords from the center of an all-enclosing bounding box
  3743. else:
  3744. # first get a bounding box to fit all
  3745. for sha in shape_list:
  3746. xmin, ymin, xmax, ymax = sha.bounds()
  3747. xminlist.append(xmin)
  3748. yminlist.append(ymin)
  3749. xmaxlist.append(xmax)
  3750. ymaxlist.append(ymax)
  3751. # get the minimum x,y and maximum x,y for all objects selected
  3752. xminimal = min(xminlist)
  3753. yminimal = min(yminlist)
  3754. xmaximal = max(xmaxlist)
  3755. ymaximal = max(ymaxlist)
  3756. px = 0.5 * (xminimal + xmaximal)
  3757. py = 0.5 * (yminimal + ymaximal)
  3758. self.app.progress.emit(20)
  3759. # execute mirroring
  3760. for sha in shape_list:
  3761. if axis is 'X':
  3762. sha.mirror('X', (px, py))
  3763. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  3764. elif axis is 'Y':
  3765. sha.mirror('Y', (px, py))
  3766. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  3767. self.draw_app.plot_all()
  3768. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3769. #
  3770. # self.draw_app.transform_complete.emit()
  3771. self.app.progress.emit(100)
  3772. except Exception as e:
  3773. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3774. return
  3775. def on_skew(self, axis, num):
  3776. shape_list = self.draw_app.selected
  3777. xminlist = []
  3778. yminlist = []
  3779. if not shape_list:
  3780. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  3781. return
  3782. else:
  3783. with self.app.proc_container.new(_("Applying Skew")):
  3784. try:
  3785. # first get a bounding box to fit all
  3786. for sha in shape_list:
  3787. xmin, ymin, xmax, ymax = sha.bounds()
  3788. xminlist.append(xmin)
  3789. yminlist.append(ymin)
  3790. # get the minimum x,y and maximum x,y for all objects selected
  3791. xminimal = min(xminlist)
  3792. yminimal = min(yminlist)
  3793. self.app.progress.emit(20)
  3794. for sha in shape_list:
  3795. if axis is 'X':
  3796. sha.skew(num, 0, point=(xminimal, yminimal))
  3797. elif axis is 'Y':
  3798. sha.skew(0, num, point=(xminimal, yminimal))
  3799. self.draw_app.plot_all()
  3800. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3801. #
  3802. # self.draw_app.transform_complete.emit()
  3803. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  3804. self.app.progress.emit(100)
  3805. except Exception as e:
  3806. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  3807. return
  3808. def on_scale(self, axis, xfactor, yfactor, point=None):
  3809. shape_list = self.draw_app.selected
  3810. xminlist = []
  3811. yminlist = []
  3812. xmaxlist = []
  3813. ymaxlist = []
  3814. if not shape_list:
  3815. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  3816. return
  3817. else:
  3818. with self.app.proc_container.new(_("Applying Scale")):
  3819. try:
  3820. # first get a bounding box to fit all
  3821. for sha in shape_list:
  3822. xmin, ymin, xmax, ymax = sha.bounds()
  3823. xminlist.append(xmin)
  3824. yminlist.append(ymin)
  3825. xmaxlist.append(xmax)
  3826. ymaxlist.append(ymax)
  3827. # get the minimum x,y and maximum x,y for all objects selected
  3828. xminimal = min(xminlist)
  3829. yminimal = min(yminlist)
  3830. xmaximal = max(xmaxlist)
  3831. ymaximal = max(ymaxlist)
  3832. self.app.progress.emit(20)
  3833. if point is None:
  3834. px = 0.5 * (xminimal + xmaximal)
  3835. py = 0.5 * (yminimal + ymaximal)
  3836. else:
  3837. px = 0
  3838. py = 0
  3839. for sha in shape_list:
  3840. sha.scale(xfactor, yfactor, point=(px, py))
  3841. self.draw_app.plot_all()
  3842. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3843. #
  3844. # self.draw_app.transform_complete.emit()
  3845. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  3846. self.app.progress.emit(100)
  3847. except Exception as e:
  3848. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  3849. return
  3850. def on_offset(self, axis, num):
  3851. shape_list = self.draw_app.selected
  3852. xminlist = []
  3853. yminlist = []
  3854. if not shape_list:
  3855. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  3856. return
  3857. else:
  3858. with self.app.proc_container.new(_("Applying Offset")):
  3859. try:
  3860. # first get a bounding box to fit all
  3861. for sha in shape_list:
  3862. xmin, ymin, xmax, ymax = sha.bounds()
  3863. xminlist.append(xmin)
  3864. yminlist.append(ymin)
  3865. # get the minimum x,y and maximum x,y for all objects selected
  3866. xminimal = min(xminlist)
  3867. yminimal = min(yminlist)
  3868. self.app.progress.emit(20)
  3869. for sha in shape_list:
  3870. if axis is 'X':
  3871. sha.offset((num, 0))
  3872. elif axis is 'Y':
  3873. sha.offset((0, num))
  3874. self.draw_app.plot_all()
  3875. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  3876. #
  3877. # self.draw_app.transform_complete.emit()
  3878. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  3879. self.app.progress.emit(100)
  3880. except Exception as e:
  3881. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  3882. return
  3883. def on_rotate_key(self):
  3884. val_box = FCInputDialog(title=_("Rotate ..."),
  3885. text=_('Enter an Angle Value (degrees):'),
  3886. min=-359.9999, max=360.0000, decimals=4,
  3887. init_val=float(self.app.defaults['tools_transform_rotate']))
  3888. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  3889. val, ok = val_box.get_value()
  3890. if ok:
  3891. self.on_rotate(val=val)
  3892. self.app.inform.emit(
  3893. _("[success] Geometry shape rotate done...")
  3894. )
  3895. return
  3896. else:
  3897. self.app.inform.emit(
  3898. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  3899. )
  3900. def on_offx_key(self):
  3901. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3902. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  3903. text=(_('Enter a distance Value (%s):') % str(units)),
  3904. min=-9999.9999, max=10000.0000, decimals=4,
  3905. init_val=float(self.app.defaults['tools_transform_offset_x']))
  3906. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  3907. val, ok = val_box.get_value()
  3908. if ok:
  3909. self.on_offx(val=val)
  3910. self.app.inform.emit(
  3911. _("[success] Geometry shape offset on X axis done..."))
  3912. return
  3913. else:
  3914. self.app.inform.emit(
  3915. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  3916. def on_offy_key(self):
  3917. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3918. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  3919. text=(_('Enter a distance Value (%s):') % str(units)),
  3920. min=-9999.9999, max=10000.0000, decimals=4,
  3921. init_val=float(self.app.defaults['tools_transform_offset_y']))
  3922. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  3923. val, ok = val_box.get_value()
  3924. if ok:
  3925. self.on_offx(val=val)
  3926. self.app.inform.emit(
  3927. _("[success] Geometry shape offset on Y axis done..."))
  3928. return
  3929. else:
  3930. self.app.inform.emit(
  3931. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  3932. def on_skewx_key(self):
  3933. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  3934. text=_('Enter an Angle Value (degrees):'),
  3935. min=-359.9999, max=360.0000, decimals=4,
  3936. init_val=float(self.app.defaults['tools_transform_skew_x']))
  3937. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  3938. val, ok = val_box.get_value()
  3939. if ok:
  3940. self.on_skewx(val=val)
  3941. self.app.inform.emit(
  3942. _("[success] Geometry shape skew on X axis done..."))
  3943. return
  3944. else:
  3945. self.app.inform.emit(
  3946. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  3947. def on_skewy_key(self):
  3948. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  3949. text=_('Enter an Angle Value (degrees):'),
  3950. min=-359.9999, max=360.0000, decimals=4,
  3951. init_val=float(self.app.defaults['tools_transform_skew_y']))
  3952. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  3953. val, ok = val_box.get_value()
  3954. if ok:
  3955. self.on_skewx(val=val)
  3956. self.app.inform.emit(
  3957. _("[success] Geometry shape skew on Y axis done..."))
  3958. return
  3959. else:
  3960. self.app.inform.emit(
  3961. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))