FlatCAMGrbEditor.py 189 KB

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