FlatCAMGeoEditor.py 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136
  1. # ######################################################### ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ######################################################### ##
  8. # ########################################################### #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. # ######################################################### ##
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. from camlib import distance, arc, three_point_circle, Geometry, FlatCAMRTreeStorage
  15. from FlatCAMTool import FlatCAMTool
  16. from flatcamGUI.ObjectUI import RadioSet
  17. from flatcamGUI.GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCComboBox, FCTextAreaRich, \
  18. FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog, FCTree
  19. from flatcamParsers.ParseFont import *
  20. import FlatCAMApp
  21. from shapely.geometry import LineString, LinearRing, MultiLineString, Polygon, MultiPolygon
  22. from shapely.ops import cascaded_union, unary_union, linemerge
  23. import shapely.affinity as affinity
  24. from shapely.geometry.polygon import orient
  25. import numpy as np
  26. from numpy.linalg import norm as numpy_norm
  27. from rtree import index as rtindex
  28. from copy import deepcopy
  29. # from vispy.io import read_png
  30. import gettext
  31. import FlatCAMTranslation as fcTranslate
  32. import builtins
  33. fcTranslate.apply_language('strings')
  34. if '_' not in builtins.__dict__:
  35. _ = gettext.gettext
  36. class BufferSelectionTool(FlatCAMTool):
  37. """
  38. Simple input for buffer distance.
  39. """
  40. toolName = "Buffer Selection"
  41. def __init__(self, app, draw_app):
  42. FlatCAMTool.__init__(self, app)
  43. self.draw_app = draw_app
  44. self.decimals = app.decimals
  45. # Title
  46. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  47. title_label.setStyleSheet("""
  48. QLabel
  49. {
  50. font-size: 16px;
  51. font-weight: bold;
  52. }
  53. """)
  54. self.layout.addWidget(title_label)
  55. # this way I can hide/show the frame
  56. self.buffer_tool_frame = QtWidgets.QFrame()
  57. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  58. self.layout.addWidget(self.buffer_tool_frame)
  59. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  60. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  61. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  62. # Form Layout
  63. form_layout = QtWidgets.QFormLayout()
  64. self.buffer_tools_box.addLayout(form_layout)
  65. # Buffer distance
  66. self.buffer_distance_entry = FCDoubleSpinner()
  67. self.buffer_distance_entry.set_precision(self.decimals)
  68. self.buffer_distance_entry.set_range(0.0000, 999999.9999)
  69. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  70. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  71. self.buffer_corner_lbl.setToolTip(
  72. _("There are 3 types of corners:\n"
  73. " - 'Round': the corner is rounded for exterior buffer.\n"
  74. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  75. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  76. )
  77. self.buffer_corner_cb = FCComboBox()
  78. self.buffer_corner_cb.addItem(_("Round"))
  79. self.buffer_corner_cb.addItem(_("Square"))
  80. self.buffer_corner_cb.addItem(_("Beveled"))
  81. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  82. # Buttons
  83. hlay = QtWidgets.QHBoxLayout()
  84. self.buffer_tools_box.addLayout(hlay)
  85. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  86. hlay.addWidget(self.buffer_int_button)
  87. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  88. hlay.addWidget(self.buffer_ext_button)
  89. hlay1 = QtWidgets.QHBoxLayout()
  90. self.buffer_tools_box.addLayout(hlay1)
  91. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  92. hlay1.addWidget(self.buffer_button)
  93. self.layout.addStretch()
  94. # Signals
  95. self.buffer_button.clicked.connect(self.on_buffer)
  96. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  97. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  98. # Init GUI
  99. self.buffer_distance_entry.set_value(0.01)
  100. def run(self):
  101. self.app.report_usage("Geo Editor ToolBuffer()")
  102. FlatCAMTool.run(self)
  103. # if the splitter us hidden, display it
  104. if self.app.ui.splitter.sizes()[0] == 0:
  105. self.app.ui.splitter.setSizes([1, 1])
  106. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  107. def on_buffer(self):
  108. try:
  109. buffer_distance = float(self.buffer_distance_entry.get_value())
  110. except ValueError:
  111. # try to convert comma to decimal point. if it's still not working error message and return
  112. try:
  113. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  114. self.buffer_distance_entry.set_value(buffer_distance)
  115. except ValueError:
  116. self.app.inform.emit('[WARNING_NOTCL] %s' %
  117. _("Buffer distance value is missing or wrong format. Add it and retry."))
  118. return
  119. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  120. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  121. join_style = self.buffer_corner_cb.currentIndex() + 1
  122. self.draw_app.buffer(buffer_distance, join_style)
  123. def on_buffer_int(self):
  124. try:
  125. buffer_distance = float(self.buffer_distance_entry.get_value())
  126. except ValueError:
  127. # try to convert comma to decimal point. if it's still not working error message and return
  128. try:
  129. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  130. self.buffer_distance_entry.set_value(buffer_distance)
  131. except ValueError:
  132. self.app.inform.emit('[WARNING_NOTCL] %s' %
  133. _("Buffer distance value is missing or wrong format. Add it and retry."))
  134. return
  135. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  136. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  137. join_style = self.buffer_corner_cb.currentIndex() + 1
  138. self.draw_app.buffer_int(buffer_distance, join_style)
  139. def on_buffer_ext(self):
  140. try:
  141. buffer_distance = float(self.buffer_distance_entry.get_value())
  142. except ValueError:
  143. # try to convert comma to decimal point. if it's still not working error message and return
  144. try:
  145. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  146. self.buffer_distance_entry.set_value(buffer_distance)
  147. except ValueError:
  148. self.app.inform.emit('[WARNING_NOTCL] %s' %
  149. _("Buffer distance value is missing or wrong format. Add it and retry."))
  150. return
  151. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  152. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  153. join_style = self.buffer_corner_cb.currentIndex() + 1
  154. self.draw_app.buffer_ext(buffer_distance, join_style)
  155. def hide_tool(self):
  156. self.buffer_tool_frame.hide()
  157. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  158. class TextInputTool(FlatCAMTool):
  159. """
  160. Simple input for buffer distance.
  161. """
  162. toolName = "Text Input Tool"
  163. def __init__(self, app):
  164. FlatCAMTool.__init__(self, app)
  165. self.app = app
  166. self.text_path = []
  167. self.decimals = self.app.decimals
  168. self.f_parse = ParseFont(self.app)
  169. self.f_parse.get_fonts_by_types()
  170. # this way I can hide/show the frame
  171. self.text_tool_frame = QtWidgets.QFrame()
  172. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  173. self.layout.addWidget(self.text_tool_frame)
  174. self.text_tools_box = QtWidgets.QVBoxLayout()
  175. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  176. self.text_tool_frame.setLayout(self.text_tools_box)
  177. # Title
  178. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  179. title_label.setStyleSheet("""
  180. QLabel
  181. {
  182. font-size: 16px;
  183. font-weight: bold;
  184. }
  185. """)
  186. self.text_tools_box.addWidget(title_label)
  187. # Form Layout
  188. self.form_layout = QtWidgets.QFormLayout()
  189. self.text_tools_box.addLayout(self.form_layout)
  190. # Font type
  191. if sys.platform == "win32":
  192. f_current = QtGui.QFont("Arial")
  193. elif sys.platform == "linux":
  194. f_current = QtGui.QFont("FreeMono")
  195. else:
  196. f_current = QtGui.QFont("Helvetica Neue")
  197. self.font_name = f_current.family()
  198. self.font_type_cb = QtWidgets.QFontComboBox(self)
  199. self.font_type_cb.setCurrentFont(f_current)
  200. self.form_layout.addRow(QtWidgets.QLabel('%s:' % _("Font")), self.font_type_cb)
  201. # Flag variables to show if font is bold, italic, both or none (regular)
  202. self.font_bold = False
  203. self.font_italic = False
  204. # # Create dictionaries with the filenames of the fonts
  205. # # Key: Fontname
  206. # # Value: Font File Name.ttf
  207. #
  208. # # regular fonts
  209. # self.ff_names_regular ={}
  210. # # bold fonts
  211. # self.ff_names_bold = {}
  212. # # italic fonts
  213. # self.ff_names_italic = {}
  214. # # bold and italic fonts
  215. # self.ff_names_bi = {}
  216. #
  217. # if sys.platform == 'win32':
  218. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  219. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  220. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  221. # try:
  222. # i = 0
  223. # while 1:
  224. # name_font, value, type = EnumValue(font_key, i)
  225. # k = name_font.replace(" (TrueType)", '')
  226. # if 'Bold' in k and 'Italic' in k:
  227. # k = k.replace(" Bold Italic", '')
  228. # self.ff_names_bi.update({k: value})
  229. # elif 'Bold' in k:
  230. # k = k.replace(" Bold", '')
  231. # self.ff_names_bold.update({k: value})
  232. # elif 'Italic' in k:
  233. # k = k.replace(" Italic", '')
  234. # self.ff_names_italic.update({k: value})
  235. # else:
  236. # self.ff_names_regular.update({k: value})
  237. # i += 1
  238. # except WindowsError:
  239. # pass
  240. # Font size
  241. self.font_size_cb = FCComboBox()
  242. self.font_size_cb.setEditable(True)
  243. self.font_size_cb.setMinimumContentsLength(3)
  244. self.font_size_cb.setMaximumWidth(70)
  245. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  246. '15', '16', '18', '20', '22', '24', '26', '28',
  247. '32', '36', '40', '44', '48', '54', '60', '66',
  248. '72', '80', '88', '96']
  249. for i in font_sizes:
  250. self.font_size_cb.addItem(i)
  251. self.font_size_cb.setCurrentIndex(4)
  252. hlay = QtWidgets.QHBoxLayout()
  253. hlay.addWidget(self.font_size_cb)
  254. hlay.addStretch()
  255. self.font_bold_tb = QtWidgets.QToolButton()
  256. self.font_bold_tb.setCheckable(True)
  257. self.font_bold_tb.setIcon(QtGui.QIcon(self.app.resource_location + '/bold32.png'))
  258. hlay.addWidget(self.font_bold_tb)
  259. self.font_italic_tb = QtWidgets.QToolButton()
  260. self.font_italic_tb.setCheckable(True)
  261. self.font_italic_tb.setIcon(QtGui.QIcon(self.app.resource_location + '/italic32.png'))
  262. hlay.addWidget(self.font_italic_tb)
  263. self.form_layout.addRow(QtWidgets.QLabel('%s:' % "Size"), hlay)
  264. # Text input
  265. self.text_input_entry = FCTextAreaRich()
  266. self.text_input_entry.setTabStopWidth(12)
  267. self.text_input_entry.setMinimumHeight(200)
  268. # self.text_input_entry.setMaximumHeight(150)
  269. self.text_input_entry.setCurrentFont(f_current)
  270. self.text_input_entry.setFontPointSize(10)
  271. self.form_layout.addRow(QtWidgets.QLabel('%s:' % _("Text")), self.text_input_entry)
  272. # Buttons
  273. hlay1 = QtWidgets.QHBoxLayout()
  274. self.form_layout.addRow("", hlay1)
  275. hlay1.addStretch()
  276. self.apply_button = QtWidgets.QPushButton("Apply")
  277. hlay1.addWidget(self.apply_button)
  278. # self.layout.addStretch()
  279. # Signals
  280. self.apply_button.clicked.connect(self.on_apply_button)
  281. self.font_type_cb.currentFontChanged.connect(self.font_family)
  282. self.font_size_cb.activated.connect(self.font_size)
  283. self.font_bold_tb.clicked.connect(self.on_bold_button)
  284. self.font_italic_tb.clicked.connect(self.on_italic_button)
  285. def run(self):
  286. self.app.report_usage("Geo Editor TextInputTool()")
  287. FlatCAMTool.run(self)
  288. # if the splitter us hidden, display it
  289. if self.app.ui.splitter.sizes()[0] == 0:
  290. self.app.ui.splitter.setSizes([1, 1])
  291. self.app.ui.notebook.setTabText(2, _("Text Tool"))
  292. def on_apply_button(self):
  293. font_to_geo_type = ""
  294. if self.font_bold is True:
  295. font_to_geo_type = 'bold'
  296. elif self.font_italic is True:
  297. font_to_geo_type = 'italic'
  298. elif self.font_bold is True and self.font_italic is True:
  299. font_to_geo_type = 'bi'
  300. elif self.font_bold is False and self.font_italic is False:
  301. font_to_geo_type = 'regular'
  302. string_to_geo = self.text_input_entry.get_value()
  303. font_to_geo_size = self.font_size_cb.get_value()
  304. self.text_path = self.f_parse.font_to_geometry(char_string=string_to_geo, font_name=self.font_name,
  305. font_size=font_to_geo_size,
  306. font_type=font_to_geo_type,
  307. units=self.app.defaults['units'].upper())
  308. def font_family(self, font):
  309. self.text_input_entry.selectAll()
  310. font.setPointSize(float(self.font_size_cb.get_value()))
  311. self.text_input_entry.setCurrentFont(font)
  312. self.font_name = self.font_type_cb.currentFont().family()
  313. def font_size(self):
  314. self.text_input_entry.selectAll()
  315. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  316. def on_bold_button(self):
  317. if self.font_bold_tb.isChecked():
  318. self.text_input_entry.selectAll()
  319. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  320. self.font_bold = True
  321. else:
  322. self.text_input_entry.selectAll()
  323. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  324. self.font_bold = False
  325. def on_italic_button(self):
  326. if self.font_italic_tb.isChecked():
  327. self.text_input_entry.selectAll()
  328. self.text_input_entry.setFontItalic(True)
  329. self.font_italic = True
  330. else:
  331. self.text_input_entry.selectAll()
  332. self.text_input_entry.setFontItalic(False)
  333. self.font_italic = False
  334. def hide_tool(self):
  335. self.text_tool_frame.hide()
  336. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  337. # self.app.ui.splitter.setSizes([0, 1])
  338. self.app.ui.notebook.setTabText(2, _("Tool"))
  339. class PaintOptionsTool(FlatCAMTool):
  340. """
  341. Inputs to specify how to paint the selected polygons.
  342. """
  343. toolName = "Paint Tool"
  344. def __init__(self, app, fcdraw):
  345. FlatCAMTool.__init__(self, app)
  346. self.app = app
  347. self.fcdraw = fcdraw
  348. self.decimals = self.app.decimals
  349. # Title
  350. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  351. title_label.setStyleSheet("""
  352. QLabel
  353. {
  354. font-size: 16px;
  355. font-weight: bold;
  356. }
  357. """)
  358. self.layout.addWidget(title_label)
  359. grid = QtWidgets.QGridLayout()
  360. self.layout.addLayout(grid)
  361. grid.setColumnStretch(0, 0)
  362. grid.setColumnStretch(1, 1)
  363. # Tool dia
  364. ptdlabel = QtWidgets.QLabel('%s:' % _('Tool dia'))
  365. ptdlabel.setToolTip(
  366. _("Diameter of the tool to be used in the operation.")
  367. )
  368. grid.addWidget(ptdlabel, 0, 0)
  369. self.painttooldia_entry = FCDoubleSpinner()
  370. self.painttooldia_entry.set_range(-9999.9999, 9999.9999)
  371. self.painttooldia_entry.set_precision(self.decimals)
  372. grid.addWidget(self.painttooldia_entry, 0, 1)
  373. # Overlap
  374. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  375. ovlabel.setToolTip(
  376. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  377. "Adjust the value starting with lower values\n"
  378. "and increasing it if areas that should be painted are still \n"
  379. "not painted.\n"
  380. "Lower values = faster processing, faster execution on CNC.\n"
  381. "Higher values = slow processing and slow execution on CNC\n"
  382. "due of too many paths.")
  383. )
  384. self.paintoverlap_entry = FCDoubleSpinner(suffix='%')
  385. self.paintoverlap_entry.set_range(0.0000, 99.9999)
  386. self.paintoverlap_entry.set_precision(self.decimals)
  387. self.paintoverlap_entry.setWrapping(True)
  388. self.paintoverlap_entry.setSingleStep(1)
  389. grid.addWidget(ovlabel, 1, 0)
  390. grid.addWidget(self.paintoverlap_entry, 1, 1)
  391. # Margin
  392. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  393. marginlabel.setToolTip(
  394. _("Distance by which to avoid\n"
  395. "the edges of the polygon to\n"
  396. "be painted.")
  397. )
  398. self.paintmargin_entry = FCDoubleSpinner()
  399. self.paintmargin_entry.set_range(-9999.9999, 9999.9999)
  400. self.paintmargin_entry.set_precision(self.decimals)
  401. grid.addWidget(marginlabel, 2, 0)
  402. grid.addWidget(self.paintmargin_entry, 2, 1)
  403. # Method
  404. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  405. methodlabel.setToolTip(
  406. _("Algorithm to paint the polygons:\n"
  407. "- Standard: Fixed step inwards.\n"
  408. "- Seed-based: Outwards from seed.\n"
  409. "- Line-based: Parallel lines.")
  410. )
  411. # self.paintmethod_combo = RadioSet([
  412. # {"label": _("Standard"), "value": "standard"},
  413. # {"label": _("Seed-based"), "value": "seed"},
  414. # {"label": _("Straight lines"), "value": "lines"}
  415. # ], orientation='vertical', stretch=False)
  416. self.paintmethod_combo = FCComboBox()
  417. self.paintmethod_combo.addItems(
  418. [_("Standard"), _("Seed"), _("Lines")]
  419. )
  420. grid.addWidget(methodlabel, 3, 0)
  421. grid.addWidget(self.paintmethod_combo, 3, 1)
  422. # Connect lines
  423. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  424. pathconnectlabel.setToolTip(
  425. _("Draw lines between resulting\n"
  426. "segments to minimize tool lifts.")
  427. )
  428. self.pathconnect_cb = FCCheckBox()
  429. grid.addWidget(pathconnectlabel, 4, 0)
  430. grid.addWidget(self.pathconnect_cb, 4, 1)
  431. contourlabel = QtWidgets.QLabel(_("Contour:"))
  432. contourlabel.setToolTip(
  433. _("Cut around the perimeter of the polygon\n"
  434. "to trim rough edges.")
  435. )
  436. self.paintcontour_cb = FCCheckBox()
  437. grid.addWidget(contourlabel, 5, 0)
  438. grid.addWidget(self.paintcontour_cb, 5, 1)
  439. # Buttons
  440. hlay = QtWidgets.QHBoxLayout()
  441. self.layout.addLayout(hlay)
  442. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  443. hlay.addWidget(self.paint_button)
  444. self.layout.addStretch()
  445. # Signals
  446. self.paint_button.clicked.connect(self.on_paint)
  447. self.set_tool_ui()
  448. def run(self):
  449. self.app.report_usage("Geo Editor ToolPaint()")
  450. FlatCAMTool.run(self)
  451. # if the splitter us hidden, display it
  452. if self.app.ui.splitter.sizes()[0] == 0:
  453. self.app.ui.splitter.setSizes([1, 1])
  454. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  455. def set_tool_ui(self):
  456. # Init GUI
  457. if self.app.defaults["tools_painttooldia"]:
  458. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  459. else:
  460. self.painttooldia_entry.set_value(0.0)
  461. if self.app.defaults["tools_paintoverlap"]:
  462. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  463. else:
  464. self.paintoverlap_entry.set_value(0.0)
  465. if self.app.defaults["tools_paintmargin"]:
  466. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  467. else:
  468. self.paintmargin_entry.set_value(0.0)
  469. if self.app.defaults["tools_paintmethod"]:
  470. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  471. else:
  472. self.paintmethod_combo.set_value(_("Seed"))
  473. if self.app.defaults["tools_pathconnect"]:
  474. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  475. else:
  476. self.pathconnect_cb.set_value(False)
  477. if self.app.defaults["tools_paintcontour"]:
  478. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  479. else:
  480. self.paintcontour_cb.set_value(False)
  481. def on_paint(self):
  482. if not self.fcdraw.selected:
  483. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Paint cancelled. No shape selected."))
  484. return
  485. tooldia = self.painttooldia_entry.get_value()
  486. overlap = self.paintoverlap_entry.get_value() / 100.0
  487. margin = self.paintmargin_entry.get_value()
  488. method = self.paintmethod_combo.get_value()
  489. contour = self.paintcontour_cb.get_value()
  490. connect = self.pathconnect_cb.get_value()
  491. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  492. self.fcdraw.select_tool("select")
  493. self.app.ui.notebook.setTabText(2, _("Tools"))
  494. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  495. self.app.ui.splitter.setSizes([0, 1])
  496. class TransformEditorTool(FlatCAMTool):
  497. """
  498. Inputs to specify how to paint the selected polygons.
  499. """
  500. toolName = _("Transform Tool")
  501. rotateName = _("Rotate")
  502. skewName = _("Skew/Shear")
  503. scaleName = _("Scale")
  504. flipName = _("Mirror (Flip)")
  505. offsetName = _("Offset")
  506. def __init__(self, app, draw_app):
  507. FlatCAMTool.__init__(self, app)
  508. self.app = app
  509. self.draw_app = draw_app
  510. self.decimals = self.app.decimals
  511. self.transform_lay = QtWidgets.QVBoxLayout()
  512. self.layout.addLayout(self.transform_lay)
  513. # ## Title
  514. title_label = QtWidgets.QLabel("%s %s" % (_('Editor'), str(self.toolName)))
  515. title_label.setStyleSheet("""
  516. QLabel
  517. {
  518. font-size: 16px;
  519. font-weight: bold;
  520. }
  521. """)
  522. self.transform_lay.addWidget(title_label)
  523. self.empty_label = QtWidgets.QLabel("")
  524. self.empty_label.setMinimumWidth(50)
  525. self.empty_label1 = QtWidgets.QLabel("")
  526. self.empty_label1.setMinimumWidth(70)
  527. self.empty_label2 = QtWidgets.QLabel("")
  528. self.empty_label2.setMinimumWidth(70)
  529. self.empty_label3 = QtWidgets.QLabel("")
  530. self.empty_label3.setMinimumWidth(70)
  531. self.empty_label4 = QtWidgets.QLabel("")
  532. self.empty_label4.setMinimumWidth(70)
  533. self.transform_lay.addWidget(self.empty_label)
  534. # Rotate Title
  535. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  536. self.transform_lay.addWidget(rotate_title_label)
  537. # Layout
  538. form_layout = QtWidgets.QFormLayout()
  539. self.transform_lay.addLayout(form_layout)
  540. form_child = QtWidgets.QHBoxLayout()
  541. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  542. self.rotate_label.setToolTip(
  543. _("Angle for Rotation action, in degrees.\n"
  544. "Float number between -360 and 359.\n"
  545. "Positive numbers for CW motion.\n"
  546. "Negative numbers for CCW motion.")
  547. )
  548. self.rotate_label.setFixedWidth(50)
  549. self.rotate_entry = FCDoubleSpinner()
  550. self.rotate_entry.set_precision(self.decimals)
  551. self.rotate_entry.set_range(-360.0000, 360.0000)
  552. self.rotate_entry.setSingleStep(0.1)
  553. self.rotate_entry.setWrapping(True)
  554. self.rotate_button = FCButton()
  555. self.rotate_button.set_value(_("Rotate"))
  556. self.rotate_button.setToolTip(
  557. _("Rotate the selected shape(s).\n"
  558. "The point of reference is the middle of\n"
  559. "the bounding box for all selected shapes.")
  560. )
  561. self.rotate_button.setFixedWidth(60)
  562. form_child.addWidget(self.rotate_entry)
  563. form_child.addWidget(self.rotate_button)
  564. form_layout.addRow(self.rotate_label, form_child)
  565. self.transform_lay.addWidget(self.empty_label1)
  566. # Skew Title
  567. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  568. self.transform_lay.addWidget(skew_title_label)
  569. # Form Layout
  570. form1_layout = QtWidgets.QFormLayout()
  571. self.transform_lay.addLayout(form1_layout)
  572. form1_child_1 = QtWidgets.QHBoxLayout()
  573. form1_child_2 = QtWidgets.QHBoxLayout()
  574. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  575. self.skewx_label.setToolTip(
  576. _("Angle for Skew action, in degrees.\n"
  577. "Float number between -360 and 359.")
  578. )
  579. self.skewx_label.setFixedWidth(50)
  580. self.skewx_entry = FCDoubleSpinner()
  581. self.skewx_entry.set_precision(self.decimals)
  582. self.skewx_entry.set_range(-360.0000, 360.0000)
  583. self.skewx_entry.setSingleStep(0.1)
  584. self.skewx_entry.setWrapping(True)
  585. self.skewx_button = FCButton()
  586. self.skewx_button.set_value(_("Skew X"))
  587. self.skewx_button.setToolTip(
  588. _("Skew/shear the selected shape(s).\n"
  589. "The point of reference is the middle of\n"
  590. "the bounding box for all selected shapes."))
  591. self.skewx_button.setFixedWidth(60)
  592. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  593. self.skewy_label.setToolTip(
  594. _("Angle for Skew action, in degrees.\n"
  595. "Float number between -360 and 359.")
  596. )
  597. self.skewy_label.setFixedWidth(50)
  598. self.skewy_entry = FCDoubleSpinner()
  599. self.skewy_entry.set_precision(self.decimals)
  600. self.skewy_entry.set_range(-360.0000, 360.0000)
  601. self.skewy_entry.setSingleStep(0.1)
  602. self.skewy_entry.setWrapping(True)
  603. self.skewy_button = FCButton()
  604. self.skewy_button.set_value(_("Skew Y"))
  605. self.skewy_button.setToolTip(
  606. _("Skew/shear the selected shape(s).\n"
  607. "The point of reference is the middle of\n"
  608. "the bounding box for all selected shapes."))
  609. self.skewy_button.setFixedWidth(60)
  610. form1_child_1.addWidget(self.skewx_entry)
  611. form1_child_1.addWidget(self.skewx_button)
  612. form1_child_2.addWidget(self.skewy_entry)
  613. form1_child_2.addWidget(self.skewy_button)
  614. form1_layout.addRow(self.skewx_label, form1_child_1)
  615. form1_layout.addRow(self.skewy_label, form1_child_2)
  616. self.transform_lay.addWidget(self.empty_label2)
  617. # Scale Title
  618. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  619. self.transform_lay.addWidget(scale_title_label)
  620. # Form Layout
  621. form2_layout = QtWidgets.QFormLayout()
  622. self.transform_lay.addLayout(form2_layout)
  623. form2_child_1 = QtWidgets.QHBoxLayout()
  624. form2_child_2 = QtWidgets.QHBoxLayout()
  625. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  626. self.scalex_label.setToolTip(
  627. _("Factor for Scale action over X axis.")
  628. )
  629. self.scalex_label.setFixedWidth(50)
  630. self.scalex_entry = FCDoubleSpinner()
  631. self.scalex_entry.set_precision(self.decimals)
  632. self.scalex_entry.set_range(0.0000, 9999.9999)
  633. self.scalex_entry.setSingleStep(0.1)
  634. self.scalex_entry.setWrapping(True)
  635. self.scalex_button = FCButton()
  636. self.scalex_button.set_value(_("Scale X"))
  637. self.scalex_button.setToolTip(
  638. _("Scale the selected shape(s).\n"
  639. "The point of reference depends on \n"
  640. "the Scale reference checkbox state."))
  641. self.scalex_button.setFixedWidth(60)
  642. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  643. self.scaley_label.setToolTip(
  644. _("Factor for Scale action over Y axis.")
  645. )
  646. self.scaley_label.setFixedWidth(50)
  647. self.scaley_entry = FCDoubleSpinner()
  648. self.scaley_entry.set_precision(self.decimals)
  649. self.scaley_entry.set_range(0.0000, 9999.9999)
  650. self.scaley_entry.setSingleStep(0.1)
  651. self.scaley_entry.setWrapping(True)
  652. self.scaley_button = FCButton()
  653. self.scaley_button.set_value(_("Scale Y"))
  654. self.scaley_button.setToolTip(
  655. _("Scale the selected shape(s).\n"
  656. "The point of reference depends on \n"
  657. "the Scale reference checkbox state."))
  658. self.scaley_button.setFixedWidth(60)
  659. self.scale_link_cb = FCCheckBox()
  660. self.scale_link_cb.set_value(True)
  661. self.scale_link_cb.setText(_("Link"))
  662. self.scale_link_cb.setToolTip(
  663. _("Scale the selected shape(s)\n"
  664. "using the Scale Factor X for both axis."))
  665. self.scale_link_cb.setFixedWidth(50)
  666. self.scale_zero_ref_cb = FCCheckBox()
  667. self.scale_zero_ref_cb.set_value(True)
  668. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  669. self.scale_zero_ref_cb.setToolTip(
  670. _("Scale the selected shape(s)\n"
  671. "using the origin reference when checked,\n"
  672. "and the center of the biggest bounding box\n"
  673. "of the selected shapes when unchecked."))
  674. form2_child_1.addWidget(self.scalex_entry)
  675. form2_child_1.addWidget(self.scalex_button)
  676. form2_child_2.addWidget(self.scaley_entry)
  677. form2_child_2.addWidget(self.scaley_button)
  678. form2_layout.addRow(self.scalex_label, form2_child_1)
  679. form2_layout.addRow(self.scaley_label, form2_child_2)
  680. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  681. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  682. self.transform_lay.addWidget(self.empty_label3)
  683. # Offset Title
  684. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  685. self.transform_lay.addWidget(offset_title_label)
  686. # Form Layout
  687. form3_layout = QtWidgets.QFormLayout()
  688. self.transform_lay.addLayout(form3_layout)
  689. form3_child_1 = QtWidgets.QHBoxLayout()
  690. form3_child_2 = QtWidgets.QHBoxLayout()
  691. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  692. self.offx_label.setToolTip(
  693. _("Value for Offset action on X axis.")
  694. )
  695. self.offx_label.setFixedWidth(50)
  696. self.offx_entry = FCDoubleSpinner()
  697. self.offx_entry.set_precision(self.decimals)
  698. self.offx_entry.set_range(-9999.9999, 9999.9999)
  699. self.offx_entry.setSingleStep(0.1)
  700. self.offx_entry.setWrapping(True)
  701. self.offx_button = FCButton()
  702. self.offx_button.set_value(_("Offset X"))
  703. self.offx_button.setToolTip(
  704. _("Offset the selected shape(s).\n"
  705. "The point of reference is the middle of\n"
  706. "the bounding box for all selected shapes.\n")
  707. )
  708. self.offx_button.setFixedWidth(60)
  709. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  710. self.offy_label.setToolTip(
  711. _("Value for Offset action on Y axis.")
  712. )
  713. self.offy_label.setFixedWidth(50)
  714. self.offy_entry = FCDoubleSpinner()
  715. self.offy_entry.set_precision(self.decimals)
  716. self.offy_entry.set_range(-9999.9999, 9999.9999)
  717. self.offy_entry.setSingleStep(0.1)
  718. self.offy_entry.setWrapping(True)
  719. self.offy_button = FCButton()
  720. self.offy_button.set_value(_("Offset Y"))
  721. self.offy_button.setToolTip(
  722. _("Offset the selected shape(s).\n"
  723. "The point of reference is the middle of\n"
  724. "the bounding box for all selected shapes.\n")
  725. )
  726. self.offy_button.setFixedWidth(60)
  727. form3_child_1.addWidget(self.offx_entry)
  728. form3_child_1.addWidget(self.offx_button)
  729. form3_child_2.addWidget(self.offy_entry)
  730. form3_child_2.addWidget(self.offy_button)
  731. form3_layout.addRow(self.offx_label, form3_child_1)
  732. form3_layout.addRow(self.offy_label, form3_child_2)
  733. self.transform_lay.addWidget(self.empty_label4)
  734. # Flip Title
  735. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  736. self.transform_lay.addWidget(flip_title_label)
  737. # Form Layout
  738. form4_layout = QtWidgets.QFormLayout()
  739. form4_child_hlay = QtWidgets.QHBoxLayout()
  740. self.transform_lay.addLayout(form4_child_hlay)
  741. self.transform_lay.addLayout(form4_layout)
  742. form4_child_1 = QtWidgets.QHBoxLayout()
  743. self.flipx_button = FCButton()
  744. self.flipx_button.set_value(_("Flip on X"))
  745. self.flipx_button.setToolTip(
  746. _("Flip the selected shape(s) over the X axis.\n"
  747. "Does not create a new shape.")
  748. )
  749. self.flipy_button = FCButton()
  750. self.flipy_button.set_value(_("Flip on Y"))
  751. self.flipy_button.setToolTip(
  752. _("Flip the selected shape(s) over the X axis.\n"
  753. "Does not create a new shape.")
  754. )
  755. self.flip_ref_cb = FCCheckBox()
  756. self.flip_ref_cb.set_value(True)
  757. self.flip_ref_cb.setText(_("Ref Pt"))
  758. self.flip_ref_cb.setToolTip(
  759. _("Flip the selected shape(s)\n"
  760. "around the point in Point Entry Field.\n"
  761. "\n"
  762. "The point coordinates can be captured by\n"
  763. "left click on canvas together with pressing\n"
  764. "SHIFT key. \n"
  765. "Then click Add button to insert coordinates.\n"
  766. "Or enter the coords in format (x, y) in the\n"
  767. "Point Entry field and click Flip on X(Y)")
  768. )
  769. self.flip_ref_cb.setFixedWidth(50)
  770. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  771. self.flip_ref_label.setToolTip(
  772. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  773. "The 'x' in (x, y) will be used when using Flip on X and\n"
  774. "the 'y' in (x, y) will be used when using Flip on Y.")
  775. )
  776. self.flip_ref_label.setFixedWidth(50)
  777. self.flip_ref_entry = FCEntry("(0, 0)")
  778. self.flip_ref_button = FCButton()
  779. self.flip_ref_button.set_value(_("Add"))
  780. self.flip_ref_button.setToolTip(
  781. _("The point coordinates can be captured by\n"
  782. "left click on canvas together with pressing\n"
  783. "SHIFT key. Then click Add button to insert.")
  784. )
  785. self.flip_ref_button.setFixedWidth(60)
  786. form4_child_hlay.addWidget(self.flipx_button)
  787. form4_child_hlay.addWidget(self.flipy_button)
  788. form4_child_1.addWidget(self.flip_ref_entry)
  789. form4_child_1.addWidget(self.flip_ref_button)
  790. form4_layout.addRow(self.flip_ref_cb)
  791. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  792. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  793. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  794. self.transform_lay.addStretch()
  795. # Signals
  796. self.rotate_button.clicked.connect(self.on_rotate)
  797. self.skewx_button.clicked.connect(self.on_skewx)
  798. self.skewy_button.clicked.connect(self.on_skewy)
  799. self.scalex_button.clicked.connect(self.on_scalex)
  800. self.scaley_button.clicked.connect(self.on_scaley)
  801. self.offx_button.clicked.connect(self.on_offx)
  802. self.offy_button.clicked.connect(self.on_offy)
  803. self.flipx_button.clicked.connect(self.on_flipx)
  804. self.flipy_button.clicked.connect(self.on_flipy)
  805. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  806. self.rotate_entry.editingFinished.connect(self.on_rotate)
  807. self.skewx_entry.editingFinished.connect(self.on_skewx)
  808. self.skewy_entry.editingFinished.connect(self.on_skewy)
  809. self.scalex_entry.editingFinished.connect(self.on_scalex)
  810. self.scaley_entry.editingFinished.connect(self.on_scaley)
  811. self.offx_entry.editingFinished.connect(self.on_offx)
  812. self.offy_entry.editingFinished.connect(self.on_offy)
  813. self.set_tool_ui()
  814. def run(self):
  815. self.app.report_usage("Geo Editor Transform Tool()")
  816. FlatCAMTool.run(self)
  817. self.set_tool_ui()
  818. # if the splitter us hidden, display it
  819. if self.app.ui.splitter.sizes()[0] == 0:
  820. self.app.ui.splitter.setSizes([1, 1])
  821. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  822. def install(self, icon=None, separator=None, **kwargs):
  823. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  824. def set_tool_ui(self):
  825. # Initialize form
  826. if self.app.defaults["tools_transform_rotate"]:
  827. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  828. else:
  829. self.rotate_entry.set_value(0.0)
  830. if self.app.defaults["tools_transform_skew_x"]:
  831. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  832. else:
  833. self.skewx_entry.set_value(0.0)
  834. if self.app.defaults["tools_transform_skew_y"]:
  835. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  836. else:
  837. self.skewy_entry.set_value(0.0)
  838. if self.app.defaults["tools_transform_scale_x"]:
  839. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  840. else:
  841. self.scalex_entry.set_value(1.0)
  842. if self.app.defaults["tools_transform_scale_y"]:
  843. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  844. else:
  845. self.scaley_entry.set_value(1.0)
  846. if self.app.defaults["tools_transform_scale_link"]:
  847. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  848. else:
  849. self.scale_link_cb.set_value(True)
  850. if self.app.defaults["tools_transform_scale_reference"]:
  851. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  852. else:
  853. self.scale_zero_ref_cb.set_value(True)
  854. if self.app.defaults["tools_transform_offset_x"]:
  855. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  856. else:
  857. self.offx_entry.set_value(0.0)
  858. if self.app.defaults["tools_transform_offset_y"]:
  859. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  860. else:
  861. self.offy_entry.set_value(0.0)
  862. if self.app.defaults["tools_transform_mirror_reference"]:
  863. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  864. else:
  865. self.flip_ref_cb.set_value(False)
  866. if self.app.defaults["tools_transform_mirror_point"]:
  867. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  868. else:
  869. self.flip_ref_entry.set_value((0, 0))
  870. def template(self):
  871. if not self.fcdraw.selected:
  872. self.app.inform.emit('[WARNING_NOTCL] %s' %
  873. _("Transformation cancelled. No shape selected."))
  874. return
  875. self.draw_app.select_tool("select")
  876. self.app.ui.notebook.setTabText(2, "Tools")
  877. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  878. self.app.ui.splitter.setSizes([0, 1])
  879. def on_rotate(self, sig=None, val=None):
  880. if val:
  881. value = val
  882. else:
  883. try:
  884. value = float(self.rotate_entry.get_value())
  885. except ValueError:
  886. # try to convert comma to decimal point. if it's still not working error message and return
  887. try:
  888. value = float(self.rotate_entry.get_value().replace(',', '.'))
  889. except ValueError:
  890. self.app.inform.emit('[ERROR_NOTCL] %s' %
  891. _("Wrong value format entered, use a number."))
  892. return
  893. self.app.worker_task.emit({'fcn': self.on_rotate_action, 'params': [value]})
  894. def on_flipx(self):
  895. # self.on_flip("Y")
  896. axis = 'Y'
  897. self.app.worker_task.emit({'fcn': self.on_flip,
  898. 'params': [axis]})
  899. return
  900. def on_flipy(self):
  901. # self.on_flip("X")
  902. axis = 'X'
  903. self.app.worker_task.emit({'fcn': self.on_flip,
  904. 'params': [axis]})
  905. return
  906. def on_flip_add_coords(self):
  907. val = self.app.clipboard.text()
  908. self.flip_ref_entry.set_value(val)
  909. def on_skewx(self, sig=None, val=None):
  910. if val:
  911. value = val
  912. else:
  913. try:
  914. value = float(self.skewx_entry.get_value())
  915. except ValueError:
  916. # try to convert comma to decimal point. if it's still not working error message and return
  917. try:
  918. value = float(self.skewx_entry.get_value().replace(',', '.'))
  919. except ValueError:
  920. self.app.inform.emit('[ERROR_NOTCL] %s' %
  921. _("Wrong value format entered, use a number."))
  922. return
  923. # self.on_skew("X", value)
  924. axis = 'X'
  925. self.app.worker_task.emit({'fcn': self.on_skew,
  926. 'params': [axis, value]})
  927. return
  928. def on_skewy(self, sig=None, val=None):
  929. if val:
  930. value = val
  931. else:
  932. try:
  933. value = float(self.skewy_entry.get_value())
  934. except ValueError:
  935. # try to convert comma to decimal point. if it's still not working error message and return
  936. try:
  937. value = float(self.skewy_entry.get_value().replace(',', '.'))
  938. except ValueError:
  939. self.app.inform.emit('[ERROR_NOTCL] %s' %
  940. _("Wrong value format entered, use a number."))
  941. return
  942. # self.on_skew("Y", value)
  943. axis = 'Y'
  944. self.app.worker_task.emit({'fcn': self.on_skew,
  945. 'params': [axis, value]})
  946. return
  947. def on_scalex(self, sig=None, val=None):
  948. if val:
  949. xvalue = val
  950. else:
  951. try:
  952. xvalue = float(self.scalex_entry.get_value())
  953. except ValueError:
  954. # try to convert comma to decimal point. if it's still not working error message and return
  955. try:
  956. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  957. except ValueError:
  958. self.app.inform.emit('[ERROR_NOTCL] %s' %
  959. _("Wrong value format entered, use a number."))
  960. return
  961. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  962. if xvalue == 0:
  963. xvalue = 1
  964. if self.scale_link_cb.get_value():
  965. yvalue = xvalue
  966. else:
  967. yvalue = 1
  968. axis = 'X'
  969. point = (0, 0)
  970. if self.scale_zero_ref_cb.get_value():
  971. self.app.worker_task.emit({'fcn': self.on_scale,
  972. 'params': [axis, xvalue, yvalue, point]})
  973. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  974. else:
  975. # self.on_scale("X", xvalue, yvalue)
  976. self.app.worker_task.emit({'fcn': self.on_scale,
  977. 'params': [axis, xvalue, yvalue]})
  978. return
  979. def on_scaley(self, sig=None, val=None):
  980. xvalue = 1
  981. if val:
  982. yvalue = val
  983. else:
  984. try:
  985. yvalue = float(self.scaley_entry.get_value())
  986. except ValueError:
  987. # try to convert comma to decimal point. if it's still not working error message and return
  988. try:
  989. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  990. except ValueError:
  991. self.app.inform.emit('[ERROR_NOTCL] %s' %
  992. _("Wrong value format entered, use a number."))
  993. return
  994. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  995. if yvalue == 0:
  996. yvalue = 1
  997. axis = 'Y'
  998. point = (0, 0)
  999. if self.scale_zero_ref_cb.get_value():
  1000. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue, point]})
  1001. else:
  1002. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue]})
  1003. return
  1004. def on_offx(self, sig=None, val=None):
  1005. if val:
  1006. value = val
  1007. else:
  1008. try:
  1009. value = float(self.offx_entry.get_value())
  1010. except ValueError:
  1011. # try to convert comma to decimal point. if it's still not working error message and return
  1012. try:
  1013. value = float(self.offx_entry.get_value().replace(',', '.'))
  1014. except ValueError:
  1015. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1016. _("Wrong value format entered, use a number."))
  1017. return
  1018. # self.on_offset("X", value)
  1019. axis = 'X'
  1020. self.app.worker_task.emit({'fcn': self.on_offset,
  1021. 'params': [axis, value]})
  1022. return
  1023. def on_offy(self, sig=None, val=None):
  1024. if val:
  1025. value = val
  1026. else:
  1027. try:
  1028. value = float(self.offy_entry.get_value())
  1029. except ValueError:
  1030. # try to convert comma to decimal point. if it's still not working error message and return
  1031. try:
  1032. value = float(self.offy_entry.get_value().replace(',', '.'))
  1033. except ValueError:
  1034. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1035. _("Wrong value format entered, use a number."))
  1036. return
  1037. # self.on_offset("Y", value)
  1038. axis = 'Y'
  1039. self.app.worker_task.emit({'fcn': self.on_offset,
  1040. 'params': [axis, value]})
  1041. return
  1042. def on_rotate_action(self, num):
  1043. shape_list = self.draw_app.selected
  1044. xminlist = []
  1045. yminlist = []
  1046. xmaxlist = []
  1047. ymaxlist = []
  1048. if not shape_list:
  1049. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1050. _("No shape selected. Please Select a shape to rotate!"))
  1051. return
  1052. else:
  1053. with self.app.proc_container.new(_("Appying Rotate")):
  1054. try:
  1055. # first get a bounding box to fit all
  1056. for sha in shape_list:
  1057. xmin, ymin, xmax, ymax = sha.bounds()
  1058. xminlist.append(xmin)
  1059. yminlist.append(ymin)
  1060. xmaxlist.append(xmax)
  1061. ymaxlist.append(ymax)
  1062. # get the minimum x,y and maximum x,y for all objects selected
  1063. xminimal = min(xminlist)
  1064. yminimal = min(yminlist)
  1065. xmaximal = max(xmaxlist)
  1066. ymaximal = max(ymaxlist)
  1067. for sel_sha in shape_list:
  1068. px = 0.5 * (xminimal + xmaximal)
  1069. py = 0.5 * (yminimal + ymaximal)
  1070. sel_sha.rotate(-num, point=(px, py))
  1071. self.draw_app.replot()
  1072. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1073. # self.draw_app.transform_complete.emit()
  1074. self.app.inform.emit('[success] %s' % _("Done. Rotate completed."))
  1075. except Exception as e:
  1076. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation action was not executed"), str(e)))
  1077. return
  1078. def on_flip(self, axis):
  1079. shape_list = self.draw_app.selected
  1080. xminlist = []
  1081. yminlist = []
  1082. xmaxlist = []
  1083. ymaxlist = []
  1084. if not shape_list:
  1085. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1086. _("No shape selected. Please Select a shape to flip!"))
  1087. return
  1088. else:
  1089. with self.app.proc_container.new(_("Applying Flip")):
  1090. try:
  1091. # get mirroring coords from the point entry
  1092. if self.flip_ref_cb.isChecked():
  1093. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1094. # get mirroring coords from the center of an all-enclosing bounding box
  1095. else:
  1096. # first get a bounding box to fit all
  1097. for sha in shape_list:
  1098. xmin, ymin, xmax, ymax = sha.bounds()
  1099. xminlist.append(xmin)
  1100. yminlist.append(ymin)
  1101. xmaxlist.append(xmax)
  1102. ymaxlist.append(ymax)
  1103. # get the minimum x,y and maximum x,y for all objects selected
  1104. xminimal = min(xminlist)
  1105. yminimal = min(yminlist)
  1106. xmaximal = max(xmaxlist)
  1107. ymaximal = max(ymaxlist)
  1108. px = 0.5 * (xminimal + xmaximal)
  1109. py = 0.5 * (yminimal + ymaximal)
  1110. # execute mirroring
  1111. for sha in shape_list:
  1112. if axis == 'X':
  1113. sha.mirror('X', (px, py))
  1114. self.app.inform.emit('[success] %s...' %
  1115. _('Flip on the Y axis done'))
  1116. elif axis == 'Y':
  1117. sha.mirror('Y', (px, py))
  1118. self.app.inform.emit('[success] %s' %
  1119. _('Flip on the X axis done'))
  1120. self.draw_app.replot()
  1121. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1122. #
  1123. # self.draw_app.transform_complete.emit()
  1124. except Exception as e:
  1125. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed"), str(e)))
  1126. return
  1127. def on_skew(self, axis, num):
  1128. shape_list = self.draw_app.selected
  1129. xminlist = []
  1130. yminlist = []
  1131. if not shape_list:
  1132. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1133. _("No shape selected. Please Select a shape to shear/skew!"))
  1134. return
  1135. else:
  1136. with self.app.proc_container.new(_("Applying Skew")):
  1137. try:
  1138. # first get a bounding box to fit all
  1139. for sha in shape_list:
  1140. xmin, ymin, xmax, ymax = sha.bounds()
  1141. xminlist.append(xmin)
  1142. yminlist.append(ymin)
  1143. # get the minimum x,y and maximum x,y for all objects selected
  1144. xminimal = min(xminlist)
  1145. yminimal = min(yminlist)
  1146. for sha in shape_list:
  1147. if axis == 'X':
  1148. sha.skew(num, 0, point=(xminimal, yminimal))
  1149. elif axis == 'Y':
  1150. sha.skew(0, num, point=(xminimal, yminimal))
  1151. self.draw_app.replot()
  1152. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1153. #
  1154. # self.draw_app.transform_complete.emit()
  1155. if axis == 'X':
  1156. self.app.inform.emit('[success] %s...' % _('Skew on the X axis done'))
  1157. else:
  1158. self.app.inform.emit('[success] %s...' % _('Skew on the Y axis done'))
  1159. except Exception as e:
  1160. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Skew action was not executed"), str(e)))
  1161. return
  1162. def on_scale(self, axis, xfactor, yfactor, point=None):
  1163. shape_list = self.draw_app.selected
  1164. xminlist = []
  1165. yminlist = []
  1166. xmaxlist = []
  1167. ymaxlist = []
  1168. if not shape_list:
  1169. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected. Please Select a shape to scale!"))
  1170. return
  1171. else:
  1172. with self.app.proc_container.new(_("Applying Scale")):
  1173. try:
  1174. # first get a bounding box to fit all
  1175. for sha in shape_list:
  1176. xmin, ymin, xmax, ymax = sha.bounds()
  1177. xminlist.append(xmin)
  1178. yminlist.append(ymin)
  1179. xmaxlist.append(xmax)
  1180. ymaxlist.append(ymax)
  1181. # get the minimum x,y and maximum x,y for all objects selected
  1182. xminimal = min(xminlist)
  1183. yminimal = min(yminlist)
  1184. xmaximal = max(xmaxlist)
  1185. ymaximal = max(ymaxlist)
  1186. if point is None:
  1187. px = 0.5 * (xminimal + xmaximal)
  1188. py = 0.5 * (yminimal + ymaximal)
  1189. else:
  1190. px = 0
  1191. py = 0
  1192. for sha in shape_list:
  1193. sha.scale(xfactor, yfactor, point=(px, py))
  1194. self.draw_app.replot()
  1195. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1196. #
  1197. # self.draw_app.transform_complete.emit()
  1198. if str(axis) == 'X':
  1199. self.app.inform.emit('[success] %s...' % _('Scale on the X axis done'))
  1200. else:
  1201. self.app.inform.emit('[success] %s...' % _('Scale on the Y axis done'))
  1202. except Exception as e:
  1203. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Scale action was not executed"), str(e)))
  1204. return
  1205. def on_offset(self, axis, num):
  1206. shape_list = self.draw_app.selected
  1207. xminlist = []
  1208. yminlist = []
  1209. if not shape_list:
  1210. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1211. _("No shape selected. Please Select a shape to offset!"))
  1212. return
  1213. else:
  1214. with self.app.proc_container.new(_("Applying Offset")):
  1215. try:
  1216. for sha in shape_list:
  1217. if axis == 'X':
  1218. sha.offset((num, 0))
  1219. elif axis == 'Y':
  1220. sha.offset((0, num))
  1221. self.draw_app.replot()
  1222. if axis == 'X':
  1223. self.app.inform.emit('[success] %s...' % _('Offset on the X axis done'))
  1224. else:
  1225. self.app.inform.emit('[success] %s...' % _('Offset on the Y axis done'))
  1226. except Exception as e:
  1227. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Offset action was not executed"), str(e)))
  1228. return
  1229. def on_rotate_key(self):
  1230. val_box = FCInputDialog(title=_("Rotate ..."),
  1231. text='%s:' % _('Enter an Angle Value (degrees)'),
  1232. min=-359.9999, max=360.0000, decimals=self.decimals,
  1233. init_val=float(self.app.defaults['tools_transform_rotate']))
  1234. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/rotate.png'))
  1235. val, ok = val_box.get_value()
  1236. if ok:
  1237. self.on_rotate(val=val)
  1238. self.app.inform.emit('[success] %s...' %
  1239. _("Geometry shape rotate done"))
  1240. return
  1241. else:
  1242. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1243. _("Geometry shape rotate cancelled"))
  1244. def on_offx_key(self):
  1245. units = self.app.defaults['units'].lower()
  1246. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1247. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1248. min=-9999.9999, max=10000.0000, decimals=self.decimals,
  1249. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1250. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsetx32.png'))
  1251. val, ok = val_box.get_value()
  1252. if ok:
  1253. self.on_offx(val=val)
  1254. self.app.inform.emit('[success] %s' %
  1255. _("Geometry shape offset on X axis done"))
  1256. return
  1257. else:
  1258. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1259. _("Geometry shape offset X cancelled"))
  1260. def on_offy_key(self):
  1261. units = self.app.defaults['units'].lower()
  1262. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1263. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1264. min=-9999.9999, max=10000.0000, decimals=self.decimals,
  1265. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1266. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsety32.png'))
  1267. val, ok = val_box.get_value()
  1268. if ok:
  1269. self.on_offx(val=val)
  1270. self.app.inform.emit('[success] %s...' %
  1271. _("Geometry shape offset on Y axis done"))
  1272. return
  1273. else:
  1274. self.app.inform.emit('[success] %s...' %
  1275. _("Geometry shape offset on Y axis canceled"))
  1276. def on_skewx_key(self):
  1277. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1278. text='%s:' % _('Enter an Angle Value (degrees)'),
  1279. min=-359.9999, max=360.0000, decimals=self.decimals,
  1280. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1281. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewX.png'))
  1282. val, ok = val_box.get_value()
  1283. if ok:
  1284. self.on_skewx(val=val)
  1285. self.app.inform.emit('[success] %s...' %
  1286. _("Geometry shape skew on X axis done"))
  1287. return
  1288. else:
  1289. self.app.inform.emit('[success] %s...' %
  1290. _("Geometry shape skew on X axis canceled"))
  1291. def on_skewy_key(self):
  1292. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1293. text='%s:' % _('Enter an Angle Value (degrees)'),
  1294. min=-359.9999, max=360.0000, decimals=self.decimals,
  1295. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1296. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewY.png'))
  1297. val, ok = val_box.get_value()
  1298. if ok:
  1299. self.on_skewx(val=val)
  1300. self.app.inform.emit('[success] %s...' %
  1301. _("Geometry shape skew on Y axis done"))
  1302. return
  1303. else:
  1304. self.app.inform.emit('[success] %s...' %
  1305. _("Geometry shape skew on Y axis canceled"))
  1306. class DrawToolShape(object):
  1307. """
  1308. Encapsulates "shapes" under a common class.
  1309. """
  1310. tolerance = None
  1311. @staticmethod
  1312. def get_pts(o):
  1313. """
  1314. Returns a list of all points in the object, where
  1315. the object can be a Polygon, Not a polygon, or a list
  1316. of such. Search is done recursively.
  1317. :param: geometric object
  1318. :return: List of points
  1319. :rtype: list
  1320. """
  1321. pts = []
  1322. # Iterable: descend into each item.
  1323. try:
  1324. for subo in o:
  1325. pts += DrawToolShape.get_pts(subo)
  1326. # Non-iterable
  1327. except TypeError:
  1328. if o is not None:
  1329. # DrawToolShape: descend into .geo.
  1330. if isinstance(o, DrawToolShape):
  1331. pts += DrawToolShape.get_pts(o.geo)
  1332. # Descend into .exerior and .interiors
  1333. elif type(o) == Polygon:
  1334. pts += DrawToolShape.get_pts(o.exterior)
  1335. for i in o.interiors:
  1336. pts += DrawToolShape.get_pts(i)
  1337. elif type(o) == MultiLineString:
  1338. for line in o:
  1339. pts += DrawToolShape.get_pts(line)
  1340. # Has .coords: list them.
  1341. else:
  1342. if DrawToolShape.tolerance is not None:
  1343. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1344. else:
  1345. pts += list(o.coords)
  1346. else:
  1347. return
  1348. return pts
  1349. def __init__(self, geo=[]):
  1350. # Shapely type or list of such
  1351. self.geo = geo
  1352. self.utility = False
  1353. def get_all_points(self):
  1354. return DrawToolShape.get_pts(self)
  1355. def bounds(self):
  1356. """
  1357. Returns coordinates of rectangular bounds
  1358. of geometry: (xmin, ymin, xmax, ymax).
  1359. """
  1360. # fixed issue of getting bounds only for one level lists of objects
  1361. # now it can get bounds for nested lists of objects
  1362. def bounds_rec(shape_el):
  1363. if type(shape_el) is list:
  1364. minx = np.Inf
  1365. miny = np.Inf
  1366. maxx = -np.Inf
  1367. maxy = -np.Inf
  1368. for k in shape_el:
  1369. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1370. minx = min(minx, minx_)
  1371. miny = min(miny, miny_)
  1372. maxx = max(maxx, maxx_)
  1373. maxy = max(maxy, maxy_)
  1374. return minx, miny, maxx, maxy
  1375. else:
  1376. # it's a Shapely object, return it's bounds
  1377. return shape_el.bounds
  1378. bounds_coords = bounds_rec(self.geo)
  1379. return bounds_coords
  1380. def mirror(self, axis, point):
  1381. """
  1382. Mirrors the shape around a specified axis passing through
  1383. the given point.
  1384. :param axis: "X" or "Y" indicates around which axis to mirror.
  1385. :type axis: str
  1386. :param point: [x, y] point belonging to the mirror axis.
  1387. :type point: list
  1388. :return: None
  1389. """
  1390. px, py = point
  1391. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1392. def mirror_geom(shape_el):
  1393. if type(shape_el) is list:
  1394. new_obj = []
  1395. for g in shape_el:
  1396. new_obj.append(mirror_geom(g))
  1397. return new_obj
  1398. else:
  1399. return affinity.scale(shape_el, xscale, yscale, origin=(px, py))
  1400. try:
  1401. self.geo = mirror_geom(self.geo)
  1402. except AttributeError:
  1403. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1404. def rotate(self, angle, point):
  1405. """
  1406. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1407. Parameters
  1408. ----------
  1409. The angle of rotation are specified in degrees (default). Positive angles are
  1410. counter-clockwise and negative are clockwise rotations.
  1411. The point of origin can be a keyword 'center' for the bounding box
  1412. center (default), 'centroid' for the geometry's centroid, a Point object
  1413. or a coordinate tuple (x0, y0).
  1414. See shapely manual for more information:
  1415. http://toblerity.org/shapely/manual.html#affine-transformations
  1416. """
  1417. px, py = point
  1418. def rotate_geom(shape_el):
  1419. if type(shape_el) is list:
  1420. new_obj = []
  1421. for g in shape_el:
  1422. new_obj.append(rotate_geom(g))
  1423. return new_obj
  1424. else:
  1425. return affinity.rotate(shape_el, angle, origin=(px, py))
  1426. try:
  1427. self.geo = rotate_geom(self.geo)
  1428. except AttributeError:
  1429. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1430. def skew(self, angle_x, angle_y, point):
  1431. """
  1432. Shear/Skew a shape by angles along x and y dimensions.
  1433. Parameters
  1434. ----------
  1435. angle_x, angle_y : float, float
  1436. The shear angle(s) for the x and y axes respectively. These can be
  1437. specified in either degrees (default) or radians by setting
  1438. use_radians=True.
  1439. point: tuple of coordinates (x,y)
  1440. See shapely manual for more information:
  1441. http://toblerity.org/shapely/manual.html#affine-transformations
  1442. """
  1443. px, py = point
  1444. def skew_geom(shape_el):
  1445. if type(shape_el) is list:
  1446. new_obj = []
  1447. for g in shape_el:
  1448. new_obj.append(skew_geom(g))
  1449. return new_obj
  1450. else:
  1451. return affinity.skew(shape_el, angle_x, angle_y, origin=(px, py))
  1452. try:
  1453. self.geo = skew_geom(self.geo)
  1454. except AttributeError:
  1455. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1456. def offset(self, vect):
  1457. """
  1458. Offsets all shapes by a given vector/
  1459. :param vect: (x, y) vector by which to offset the shape geometry
  1460. :type vect: tuple
  1461. :return: None
  1462. :rtype: None
  1463. """
  1464. try:
  1465. dx, dy = vect
  1466. except TypeError:
  1467. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1468. "Probable you entered only one value in the Offset field.")
  1469. return
  1470. def translate_recursion(geom):
  1471. if type(geom) == list:
  1472. geoms = []
  1473. for local_geom in geom:
  1474. geoms.append(translate_recursion(local_geom))
  1475. return geoms
  1476. else:
  1477. return affinity.translate(geom, xoff=dx, yoff=dy)
  1478. try:
  1479. self.geo = translate_recursion(self.geo)
  1480. except AttributeError:
  1481. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1482. def scale(self, xfactor, yfactor=None, point=None):
  1483. """
  1484. Scales all shape geometry by a given factor.
  1485. :param xfactor: Factor by which to scale the shape's geometry/
  1486. :type xfactor: float
  1487. :param yfactor: Factor by which to scale the shape's geometry/
  1488. :type yfactor: float
  1489. :return: None
  1490. :rtype: None
  1491. """
  1492. try:
  1493. xfactor = float(xfactor)
  1494. except Exception:
  1495. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1496. return
  1497. if yfactor is None:
  1498. yfactor = xfactor
  1499. else:
  1500. try:
  1501. yfactor = float(yfactor)
  1502. except Exception:
  1503. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1504. return
  1505. if point is None:
  1506. px = 0
  1507. py = 0
  1508. else:
  1509. px, py = point
  1510. def scale_recursion(geom):
  1511. if type(geom) == list:
  1512. geoms = []
  1513. for local_geom in geom:
  1514. geoms.append(scale_recursion(local_geom))
  1515. return geoms
  1516. else:
  1517. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1518. try:
  1519. self.geo = scale_recursion(self.geo)
  1520. except AttributeError:
  1521. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1522. class DrawToolUtilityShape(DrawToolShape):
  1523. """
  1524. Utility shapes are temporary geometry in the editor
  1525. to assist in the creation of shapes. For example it
  1526. will show the outline of a rectangle from the first
  1527. point to the current mouse pointer before the second
  1528. point is clicked and the final geometry is created.
  1529. """
  1530. def __init__(self, geo=[]):
  1531. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1532. self.utility = True
  1533. class DrawTool(object):
  1534. """
  1535. Abstract Class representing a tool in the drawing
  1536. program. Can generate geometry, including temporary
  1537. utility geometry that is updated on user clicks
  1538. and mouse motion.
  1539. """
  1540. def __init__(self, draw_app):
  1541. self.draw_app = draw_app
  1542. self.complete = False
  1543. self.points = []
  1544. self.geometry = None # DrawToolShape or None
  1545. def click(self, point):
  1546. """
  1547. :param point: [x, y] Coordinate pair.
  1548. """
  1549. return ""
  1550. def click_release(self, point):
  1551. """
  1552. :param point: [x, y] Coordinate pair.
  1553. """
  1554. return ""
  1555. def on_key(self, key):
  1556. # Jump to coords
  1557. if key == QtCore.Qt.Key_J or key == 'J':
  1558. self.draw_app.app.on_jump_to()
  1559. return
  1560. def utility_geometry(self, data=None):
  1561. return None
  1562. def bounds(self, obj):
  1563. def bounds_rec(o):
  1564. if type(o) is list:
  1565. minx = np.Inf
  1566. miny = np.Inf
  1567. maxx = -np.Inf
  1568. maxy = -np.Inf
  1569. for k in o:
  1570. try:
  1571. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1572. except Exception as e:
  1573. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1574. return
  1575. minx = min(minx, minx_)
  1576. miny = min(miny, miny_)
  1577. maxx = max(maxx, maxx_)
  1578. maxy = max(maxy, maxy_)
  1579. return minx, miny, maxx, maxy
  1580. else:
  1581. # it's a Shapely object, return it's bounds
  1582. return o.geo.bounds
  1583. bounds_coords = bounds_rec(obj)
  1584. return bounds_coords
  1585. class FCShapeTool(DrawTool):
  1586. """
  1587. Abstract class for tools that create a shape.
  1588. """
  1589. def __init__(self, draw_app):
  1590. DrawTool.__init__(self, draw_app)
  1591. def make(self):
  1592. pass
  1593. class FCCircle(FCShapeTool):
  1594. """
  1595. Resulting type: Polygon
  1596. """
  1597. def __init__(self, draw_app):
  1598. DrawTool.__init__(self, draw_app)
  1599. self.name = 'circle'
  1600. self.draw_app = draw_app
  1601. try:
  1602. QtGui.QGuiApplication.restoreOverrideCursor()
  1603. except Exception:
  1604. pass
  1605. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_circle_geo.png'))
  1606. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1607. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1608. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1609. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1610. def click(self, point):
  1611. try:
  1612. self.draw_app.app.jump_signal.disconnect()
  1613. except (TypeError, AttributeError):
  1614. pass
  1615. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1616. self.points.append(point)
  1617. if len(self.points) == 1:
  1618. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1619. return "Click on perimeter to complete ..."
  1620. if len(self.points) == 2:
  1621. self.make()
  1622. return "Done."
  1623. return ""
  1624. def utility_geometry(self, data=None):
  1625. if len(self.points) == 1:
  1626. p1 = self.points[0]
  1627. p2 = data
  1628. radius = np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1629. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1630. return None
  1631. def make(self):
  1632. try:
  1633. QtGui.QGuiApplication.restoreOverrideCursor()
  1634. except Exception:
  1635. pass
  1636. p1 = self.points[0]
  1637. p2 = self.points[1]
  1638. radius = distance(p1, p2)
  1639. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1640. self.complete = True
  1641. self.draw_app.app.jump_signal.disconnect()
  1642. self.draw_app.app.inform.emit('[success] %s' % _("Done. Adding Circle completed."))
  1643. def clean_up(self):
  1644. self.draw_app.selected = []
  1645. self.draw_app.plot_all()
  1646. try:
  1647. self.draw_app.app.jump_signal.disconnect()
  1648. except (TypeError, AttributeError):
  1649. pass
  1650. class FCArc(FCShapeTool):
  1651. def __init__(self, draw_app):
  1652. DrawTool.__init__(self, draw_app)
  1653. self.name = 'arc'
  1654. self.draw_app = draw_app
  1655. try:
  1656. QtGui.QGuiApplication.restoreOverrideCursor()
  1657. except Exception:
  1658. pass
  1659. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_arc.png'))
  1660. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1661. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1662. # Direction of rotation between point 1 and 2.
  1663. # 'cw' or 'ccw'. Switch direction by hitting the
  1664. # 'o' key.
  1665. self.direction = "cw"
  1666. # Mode
  1667. # C12 = Center, p1, p2
  1668. # 12C = p1, p2, Center
  1669. # 132 = p1, p3, p2
  1670. self.mode = "c12" # Center, p1, p2
  1671. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1672. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1673. def click(self, point):
  1674. try:
  1675. self.draw_app.app.jump_signal.disconnect()
  1676. except (TypeError, AttributeError):
  1677. pass
  1678. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1679. self.points.append(point)
  1680. if len(self.points) == 1:
  1681. if self.mode == 'c12':
  1682. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1683. elif self.mode == '132':
  1684. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1685. else:
  1686. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1687. return "Click on 1st point ..."
  1688. if len(self.points) == 2:
  1689. if self.mode == 'c12':
  1690. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1691. elif self.mode == '132':
  1692. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1693. else:
  1694. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1695. return "Click on 2nd point to complete ..."
  1696. if len(self.points) == 3:
  1697. self.make()
  1698. return "Done."
  1699. return ""
  1700. def on_key(self, key):
  1701. if key == 'D' or key == QtCore.Qt.Key_D:
  1702. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1703. return _('Direction: %s') % self.direction.upper()
  1704. # Jump to coords
  1705. if key == QtCore.Qt.Key_J or key == 'J':
  1706. self.draw_app.app.on_jump_to()
  1707. if key == 'M' or key == QtCore.Qt.Key_M:
  1708. # delete the possible points made before this action; we want to start anew
  1709. self.points[:] = []
  1710. # and delete the utility geometry made up until this point
  1711. self.draw_app.delete_utility_geometry()
  1712. if self.mode == 'c12':
  1713. self.mode = '12c'
  1714. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1715. elif self.mode == '12c':
  1716. self.mode = '132'
  1717. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1718. else:
  1719. self.mode = 'c12'
  1720. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1721. def utility_geometry(self, data=None):
  1722. if len(self.points) == 1: # Show the radius
  1723. center = self.points[0]
  1724. p1 = data
  1725. return DrawToolUtilityShape(LineString([center, p1]))
  1726. if len(self.points) == 2: # Show the arc
  1727. if self.mode == 'c12':
  1728. center = self.points[0]
  1729. p1 = self.points[1]
  1730. p2 = data
  1731. radius = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1732. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1733. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1734. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1735. self.direction, self.steps_per_circ)),
  1736. Point(center)])
  1737. elif self.mode == '132':
  1738. p1 = np.array(self.points[0])
  1739. p3 = np.array(self.points[1])
  1740. p2 = np.array(data)
  1741. try:
  1742. center, radius, t = three_point_circle(p1, p2, p3)
  1743. except TypeError:
  1744. return
  1745. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1746. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1747. stopangle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1748. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1749. direction, self.steps_per_circ)),
  1750. Point(center), Point(p1), Point(p3)])
  1751. else: # '12c'
  1752. p1 = np.array(self.points[0])
  1753. p2 = np.array(self.points[1])
  1754. # Midpoint
  1755. a = (p1 + p2) / 2.0
  1756. # Parallel vector
  1757. c = p2 - p1
  1758. # Perpendicular vector
  1759. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1760. b /= numpy_norm(b)
  1761. # Distance
  1762. t = distance(data, a)
  1763. # Which side? Cross product with c.
  1764. # cross(M-A, B-A), where line is AB and M is test point.
  1765. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1766. t *= np.sign(side)
  1767. # Center = a + bt
  1768. center = a + b * t
  1769. radius = numpy_norm(center - p1)
  1770. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1771. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1772. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1773. self.direction, self.steps_per_circ)),
  1774. Point(center)])
  1775. return None
  1776. def make(self):
  1777. if self.mode == 'c12':
  1778. center = self.points[0]
  1779. p1 = self.points[1]
  1780. p2 = self.points[2]
  1781. radius = distance(center, p1)
  1782. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1783. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1784. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1785. self.direction, self.steps_per_circ)))
  1786. elif self.mode == '132':
  1787. p1 = np.array(self.points[0])
  1788. p3 = np.array(self.points[1])
  1789. p2 = np.array(self.points[2])
  1790. center, radius, t = three_point_circle(p1, p2, p3)
  1791. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1792. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1793. stopangle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1794. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1795. direction, self.steps_per_circ)))
  1796. else: # self.mode == '12c'
  1797. p1 = np.array(self.points[0])
  1798. p2 = np.array(self.points[1])
  1799. pc = np.array(self.points[2])
  1800. # Midpoint
  1801. a = (p1 + p2) / 2.0
  1802. # Parallel vector
  1803. c = p2 - p1
  1804. # Perpendicular vector
  1805. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1806. b /= numpy_norm(b)
  1807. # Distance
  1808. t = distance(pc, a)
  1809. # Which side? Cross product with c.
  1810. # cross(M-A, B-A), where line is AB and M is test point.
  1811. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1812. t *= np.sign(side)
  1813. # Center = a + bt
  1814. center = a + b * t
  1815. radius = numpy_norm(center - p1)
  1816. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1817. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1818. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1819. self.direction, self.steps_per_circ)))
  1820. self.complete = True
  1821. self.draw_app.app.jump_signal.disconnect()
  1822. self.draw_app.app.inform.emit('[success] %s' % _("Done. Arc completed."))
  1823. def clean_up(self):
  1824. self.draw_app.selected = []
  1825. self.draw_app.plot_all()
  1826. try:
  1827. self.draw_app.app.jump_signal.disconnect()
  1828. except (TypeError, AttributeError):
  1829. pass
  1830. class FCRectangle(FCShapeTool):
  1831. """
  1832. Resulting type: Polygon
  1833. """
  1834. def __init__(self, draw_app):
  1835. DrawTool.__init__(self, draw_app)
  1836. self.name = 'rectangle'
  1837. self.draw_app = draw_app
  1838. try:
  1839. QtGui.QGuiApplication.restoreOverrideCursor()
  1840. except Exception:
  1841. pass
  1842. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero.png'))
  1843. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1844. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1845. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1846. def click(self, point):
  1847. try:
  1848. self.draw_app.app.jump_signal.disconnect()
  1849. except (TypeError, AttributeError):
  1850. pass
  1851. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1852. self.points.append(point)
  1853. if len(self.points) == 1:
  1854. self.draw_app.app.inform.emit(_("Click on opposite corner to complete ..."))
  1855. return "Click on opposite corner to complete ..."
  1856. if len(self.points) == 2:
  1857. self.make()
  1858. return "Done."
  1859. return ""
  1860. def utility_geometry(self, data=None):
  1861. if len(self.points) == 1:
  1862. p1 = self.points[0]
  1863. p2 = data
  1864. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1865. return None
  1866. def make(self):
  1867. try:
  1868. QtGui.QGuiApplication.restoreOverrideCursor()
  1869. except Exception:
  1870. pass
  1871. p1 = self.points[0]
  1872. p2 = self.points[1]
  1873. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1874. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1875. self.complete = True
  1876. self.draw_app.app.jump_signal.disconnect()
  1877. self.draw_app.app.inform.emit('[success] %s' % _("Done. Rectangle completed."))
  1878. def clean_up(self):
  1879. self.draw_app.selected = []
  1880. self.draw_app.plot_all()
  1881. try:
  1882. self.draw_app.app.jump_signal.disconnect()
  1883. except (TypeError, AttributeError):
  1884. pass
  1885. class FCPolygon(FCShapeTool):
  1886. """
  1887. Resulting type: Polygon
  1888. """
  1889. def __init__(self, draw_app):
  1890. DrawTool.__init__(self, draw_app)
  1891. self.name = 'polygon'
  1892. self.draw_app = draw_app
  1893. try:
  1894. QtGui.QGuiApplication.restoreOverrideCursor()
  1895. except Exception:
  1896. pass
  1897. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero.png'))
  1898. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1899. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1900. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1901. def click(self, point):
  1902. try:
  1903. self.draw_app.app.jump_signal.disconnect()
  1904. except (TypeError, AttributeError):
  1905. pass
  1906. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1907. self.draw_app.in_action = True
  1908. self.points.append(point)
  1909. if len(self.points) > 0:
  1910. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1911. return "Click on next point or hit ENTER to complete ..."
  1912. return ""
  1913. def utility_geometry(self, data=None):
  1914. if len(self.points) == 1:
  1915. temp_points = [x for x in self.points]
  1916. temp_points.append(data)
  1917. return DrawToolUtilityShape(LineString(temp_points))
  1918. if len(self.points) > 1:
  1919. temp_points = [x for x in self.points]
  1920. temp_points.append(data)
  1921. return DrawToolUtilityShape(LinearRing(temp_points))
  1922. return None
  1923. def make(self):
  1924. try:
  1925. QtGui.QGuiApplication.restoreOverrideCursor()
  1926. except Exception:
  1927. pass
  1928. # self.geometry = LinearRing(self.points)
  1929. self.geometry = DrawToolShape(Polygon(self.points))
  1930. self.draw_app.in_action = False
  1931. self.complete = True
  1932. self.draw_app.app.jump_signal.disconnect()
  1933. self.draw_app.app.inform.emit('[success] %s' % _("Done. Polygon completed."))
  1934. def on_key(self, key):
  1935. # Jump to coords
  1936. if key == QtCore.Qt.Key_J or key == 'J':
  1937. self.draw_app.app.on_jump_to()
  1938. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1939. if len(self.points) > 0:
  1940. self.points = self.points[0:-1]
  1941. # Remove any previous utility shape
  1942. self.draw_app.tool_shape.clear(update=False)
  1943. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1944. self.draw_app.draw_utility_geometry(geo=geo)
  1945. return _("Backtracked one point ...")
  1946. def clean_up(self):
  1947. self.draw_app.selected = []
  1948. self.draw_app.plot_all()
  1949. try:
  1950. self.draw_app.app.jump_signal.disconnect()
  1951. except (TypeError, AttributeError):
  1952. pass
  1953. class FCPath(FCPolygon):
  1954. """
  1955. Resulting type: LineString
  1956. """
  1957. def __init__(self, draw_app):
  1958. FCPolygon.__init__(self, draw_app)
  1959. self.draw_app = draw_app
  1960. try:
  1961. QtGui.QGuiApplication.restoreOverrideCursor()
  1962. except Exception:
  1963. pass
  1964. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path5.png'))
  1965. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1966. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1967. def make(self):
  1968. self.geometry = DrawToolShape(LineString(self.points))
  1969. self.name = 'path'
  1970. try:
  1971. QtGui.QGuiApplication.restoreOverrideCursor()
  1972. except Exception as e:
  1973. pass
  1974. self.draw_app.in_action = False
  1975. self.complete = True
  1976. self.draw_app.app.jump_signal.disconnect()
  1977. self.draw_app.app.inform.emit('[success] %s' % _("Done. Path completed."))
  1978. def utility_geometry(self, data=None):
  1979. if len(self.points) > 0:
  1980. temp_points = [x for x in self.points]
  1981. temp_points.append(data)
  1982. return DrawToolUtilityShape(LineString(temp_points))
  1983. return None
  1984. def on_key(self, key):
  1985. # Jump to coords
  1986. if key == QtCore.Qt.Key_J or key == 'J':
  1987. self.draw_app.app.on_jump_to()
  1988. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1989. if len(self.points) > 0:
  1990. self.points = self.points[0:-1]
  1991. # Remove any previous utility shape
  1992. self.draw_app.tool_shape.clear(update=False)
  1993. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1994. self.draw_app.draw_utility_geometry(geo=geo)
  1995. return _("Backtracked one point ...")
  1996. def clean_up(self):
  1997. self.draw_app.selected = []
  1998. self.draw_app.plot_all()
  1999. try:
  2000. self.draw_app.app.jump_signal.disconnect()
  2001. except (TypeError, AttributeError):
  2002. pass
  2003. class FCSelect(DrawTool):
  2004. def __init__(self, draw_app):
  2005. DrawTool.__init__(self, draw_app)
  2006. self.name = 'select'
  2007. self.draw_app = draw_app
  2008. try:
  2009. QtGui.QGuiApplication.restoreOverrideCursor()
  2010. except Exception as e:
  2011. pass
  2012. self.storage = self.draw_app.storage
  2013. # self.shape_buffer = self.draw_app.shape_buffer
  2014. # self.selected = self.draw_app.selected
  2015. def click_release(self, point):
  2016. # list where we store the overlapped shapes under our mouse left click position
  2017. over_shape_list = []
  2018. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  2019. for obj_shape in self.storage.get_objects():
  2020. # first method of click selection -> inconvenient
  2021. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  2022. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  2023. # over_shape_list.append(obj_shape)
  2024. # second method of click selection -> slow
  2025. # outside = obj_shape.geo.buffer(0.1)
  2026. # inside = obj_shape.geo.buffer(-0.1)
  2027. # shape_band = outside.difference(inside)
  2028. # if Point(pos).within(shape_band):
  2029. # over_shape_list.append(obj_shape)
  2030. # 3rd method of click selection -> inconvenient
  2031. try:
  2032. _, closest_shape = self.storage.nearest(point)
  2033. except StopIteration:
  2034. return ""
  2035. over_shape_list.append(closest_shape)
  2036. try:
  2037. # if there is no shape under our click then deselect all shapes
  2038. # it will not work for 3rd method of click selection
  2039. if not over_shape_list:
  2040. self.draw_app.selected = []
  2041. FlatCAMGeoEditor.draw_shape_idx = -1
  2042. else:
  2043. # if there are shapes under our click then advance through the list of them, one at the time in a
  2044. # circular way
  2045. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2046. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2047. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2048. if key_modifier == QtCore.Qt.ShiftModifier:
  2049. mod_key = 'Shift'
  2050. elif key_modifier == QtCore.Qt.ControlModifier:
  2051. mod_key = 'Control'
  2052. else:
  2053. mod_key = None
  2054. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  2055. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2056. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2057. if obj_to_add in self.draw_app.selected:
  2058. self.draw_app.selected.remove(obj_to_add)
  2059. else:
  2060. self.draw_app.selected.append(obj_to_add)
  2061. else:
  2062. self.draw_app.selected = []
  2063. self.draw_app.selected.append(obj_to_add)
  2064. except Exception as e:
  2065. log.error("[ERROR] FlatCAMGeoEditor.FCSelect.click_release() -> Something went bad. %s" % str(e))
  2066. # if selection is done on canvas update the Tree in Selected Tab with the selection
  2067. try:
  2068. self.draw_app.tw.itemSelectionChanged.disconnect(self.draw_app.on_tree_selection_change)
  2069. except (AttributeError, TypeError):
  2070. pass
  2071. self.draw_app.tw.selectionModel().clearSelection()
  2072. for sel_shape in self.draw_app.selected:
  2073. iterator = QtWidgets.QTreeWidgetItemIterator(self.draw_app.tw)
  2074. while iterator.value():
  2075. item = iterator.value()
  2076. try:
  2077. if int(item.text(1)) == id(sel_shape):
  2078. item.setSelected(True)
  2079. except ValueError:
  2080. pass
  2081. iterator += 1
  2082. self.draw_app.tw.itemSelectionChanged.connect(self.draw_app.on_tree_selection_change)
  2083. return ""
  2084. def clean_up(self):
  2085. pass
  2086. class FCExplode(FCShapeTool):
  2087. def __init__(self, draw_app):
  2088. FCShapeTool.__init__(self, draw_app)
  2089. self.name = 'explode'
  2090. self.draw_app = draw_app
  2091. try:
  2092. QtGui.QGuiApplication.restoreOverrideCursor()
  2093. except Exception:
  2094. pass
  2095. self.storage = self.draw_app.storage
  2096. self.origin = (0, 0)
  2097. self.destination = None
  2098. self.draw_app.active_tool = self
  2099. if len(self.draw_app.get_selected()) == 0:
  2100. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' % ("No shape selected. Select a shape to explode"))
  2101. else:
  2102. self.make()
  2103. def make(self):
  2104. to_be_deleted_list = []
  2105. lines = []
  2106. for shape in self.draw_app.get_selected():
  2107. to_be_deleted_list.append(shape)
  2108. geo = shape.geo
  2109. ext_coords = list(geo.exterior.coords)
  2110. for c in range(len(ext_coords)):
  2111. if c < len(ext_coords) - 1:
  2112. lines.append(LineString([ext_coords[c], ext_coords[c + 1]]))
  2113. for int_geo in geo.interiors:
  2114. int_coords = list(int_geo.coords)
  2115. for c in range(len(int_coords)):
  2116. if c < len(int_coords):
  2117. lines.append(LineString([int_coords[c], int_coords[c + 1]]))
  2118. for shape in to_be_deleted_list:
  2119. self.draw_app.storage.remove(shape)
  2120. if shape in self.draw_app.selected:
  2121. self.draw_app.selected.remove(shape)
  2122. geo_list = []
  2123. for line in lines:
  2124. geo_list.append(DrawToolShape(line))
  2125. self.geometry = geo_list
  2126. self.draw_app.on_shape_complete()
  2127. self.draw_app.app.inform.emit('[success] %s...' % _("Done. Polygons exploded into lines."))
  2128. def clean_up(self):
  2129. self.draw_app.selected = []
  2130. self.draw_app.plot_all()
  2131. try:
  2132. self.draw_app.app.jump_signal.disconnect()
  2133. except (TypeError, AttributeError):
  2134. pass
  2135. class FCMove(FCShapeTool):
  2136. def __init__(self, draw_app):
  2137. FCShapeTool.__init__(self, draw_app)
  2138. self.name = 'move'
  2139. self.draw_app = draw_app
  2140. try:
  2141. QtGui.QGuiApplication.restoreOverrideCursor()
  2142. except Exception as e:
  2143. pass
  2144. self.storage = self.draw_app.storage
  2145. self.origin = None
  2146. self.destination = None
  2147. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2148. self.selection_shape = self.selection_bbox()
  2149. if len(self.draw_app.get_selected()) == 0:
  2150. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' %
  2151. _("MOVE: No shape selected. Select a shape to move"))
  2152. return
  2153. else:
  2154. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2155. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2156. def set_origin(self, origin):
  2157. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2158. self.origin = origin
  2159. def click(self, point):
  2160. try:
  2161. self.draw_app.app.jump_signal.disconnect()
  2162. except (TypeError, AttributeError):
  2163. pass
  2164. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2165. if len(self.draw_app.get_selected()) == 0:
  2166. # self.complete = True
  2167. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2168. self.select_shapes(point)
  2169. self.draw_app.replot()
  2170. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2171. return
  2172. if self.origin is None:
  2173. self.set_origin(point)
  2174. self.selection_shape = self.selection_bbox()
  2175. return "Click on final location."
  2176. else:
  2177. self.destination = point
  2178. self.make()
  2179. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2180. # 'params': []}))
  2181. return "Done."
  2182. def make(self):
  2183. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2184. # Create new geometry
  2185. dx = self.destination[0] - self.origin[0]
  2186. dy = self.destination[1] - self.origin[1]
  2187. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2188. for geom in self.draw_app.get_selected()]
  2189. # Delete old
  2190. self.draw_app.delete_selected()
  2191. self.complete = True
  2192. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Move completed."))
  2193. try:
  2194. self.draw_app.app.jump_signal.disconnect()
  2195. except TypeError:
  2196. pass
  2197. def selection_bbox(self):
  2198. geo_list = []
  2199. for select_shape in self.draw_app.get_selected():
  2200. geometric_data = select_shape.geo
  2201. try:
  2202. for g in geometric_data:
  2203. geo_list.append(g)
  2204. except TypeError:
  2205. geo_list.append(geometric_data)
  2206. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2207. pt1 = (xmin, ymin)
  2208. pt2 = (xmax, ymin)
  2209. pt3 = (xmax, ymax)
  2210. pt4 = (xmin, ymax)
  2211. return Polygon([pt1, pt2, pt3, pt4])
  2212. def utility_geometry(self, data=None):
  2213. """
  2214. Temporary geometry on screen while using this tool.
  2215. :param data:
  2216. :return:
  2217. """
  2218. geo_list = []
  2219. if self.origin is None:
  2220. return None
  2221. if len(self.draw_app.get_selected()) == 0:
  2222. return None
  2223. dx = data[0] - self.origin[0]
  2224. dy = data[1] - self.origin[1]
  2225. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2226. try:
  2227. for geom in self.draw_app.get_selected():
  2228. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2229. except AttributeError:
  2230. self.draw_app.select_tool('select')
  2231. self.draw_app.selected = []
  2232. return
  2233. return DrawToolUtilityShape(geo_list)
  2234. else:
  2235. try:
  2236. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2237. except ValueError:
  2238. ss_el = None
  2239. return DrawToolUtilityShape(ss_el)
  2240. def select_shapes(self, pos):
  2241. # list where we store the overlapped shapes under our mouse left click position
  2242. over_shape_list = []
  2243. try:
  2244. _, closest_shape = self.storage.nearest(pos)
  2245. except StopIteration:
  2246. return ""
  2247. over_shape_list.append(closest_shape)
  2248. try:
  2249. # if there is no shape under our click then deselect all shapes
  2250. # it will not work for 3rd method of click selection
  2251. if not over_shape_list:
  2252. self.draw_app.selected = []
  2253. self.draw_app.draw_shape_idx = -1
  2254. else:
  2255. # if there are shapes under our click then advance through the list of them, one at the time in a
  2256. # circular way
  2257. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2258. try:
  2259. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2260. except IndexError:
  2261. return
  2262. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2263. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2264. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2265. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2266. if key_modifier == Qt.ControlModifier:
  2267. if obj_to_add in self.draw_app.selected:
  2268. self.draw_app.selected.remove(obj_to_add)
  2269. else:
  2270. self.draw_app.selected.append(obj_to_add)
  2271. else:
  2272. self.draw_app.selected = []
  2273. self.draw_app.selected.append(obj_to_add)
  2274. else:
  2275. if key_modifier == Qt.ShiftModifier:
  2276. if obj_to_add in self.draw_app.selected:
  2277. self.draw_app.selected.remove(obj_to_add)
  2278. else:
  2279. self.draw_app.selected.append(obj_to_add)
  2280. else:
  2281. self.draw_app.selected = []
  2282. self.draw_app.selected.append(obj_to_add)
  2283. except Exception as e:
  2284. log.error("[ERROR] Something went bad. %s" % str(e))
  2285. raise
  2286. def clean_up(self):
  2287. self.draw_app.selected = []
  2288. self.draw_app.plot_all()
  2289. try:
  2290. self.draw_app.app.jump_signal.disconnect()
  2291. except (TypeError, AttributeError):
  2292. pass
  2293. class FCCopy(FCMove):
  2294. def __init__(self, draw_app):
  2295. FCMove.__init__(self, draw_app)
  2296. self.name = 'copy'
  2297. def make(self):
  2298. # Create new geometry
  2299. dx = self.destination[0] - self.origin[0]
  2300. dy = self.destination[1] - self.origin[1]
  2301. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2302. for geom in self.draw_app.get_selected()]
  2303. self.complete = True
  2304. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Copy completed."))
  2305. try:
  2306. self.draw_app.app.jump_signal.disconnect()
  2307. except (TypeError, AttributeError):
  2308. pass
  2309. def clean_up(self):
  2310. self.draw_app.selected = []
  2311. self.draw_app.plot_all()
  2312. try:
  2313. self.draw_app.app.jump_signal.disconnect()
  2314. except (TypeError, AttributeError):
  2315. pass
  2316. class FCText(FCShapeTool):
  2317. def __init__(self, draw_app):
  2318. FCShapeTool.__init__(self, draw_app)
  2319. self.name = 'text'
  2320. self.draw_app = draw_app
  2321. try:
  2322. QtGui.QGuiApplication.restoreOverrideCursor()
  2323. except Exception:
  2324. pass
  2325. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_text.png'))
  2326. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2327. self.app = draw_app.app
  2328. self.draw_app.app.inform.emit(_("Click on 1st point ..."))
  2329. self.origin = (0, 0)
  2330. self.text_gui = TextInputTool(app=self.app)
  2331. self.text_gui.run()
  2332. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2333. def click(self, point):
  2334. try:
  2335. self.draw_app.app.jump_signal.disconnect()
  2336. except (TypeError, AttributeError):
  2337. pass
  2338. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2339. # Create new geometry
  2340. dx = point[0]
  2341. dy = point[1]
  2342. if self.text_gui.text_path:
  2343. try:
  2344. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2345. except Exception as e:
  2346. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2347. self.draw_app.app.inform.emit('[ERROR] %s: %s' %
  2348. (_("Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2349. "supported. Error"), str(e)))
  2350. self.text_gui.text_path = []
  2351. self.text_gui.hide_tool()
  2352. self.draw_app.select_tool('select')
  2353. self.draw_app.app.jump_signal.disconnect()
  2354. return
  2355. else:
  2356. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' % _("No text to add."))
  2357. try:
  2358. self.draw_app.app.jump_signal.disconnect()
  2359. except (TypeError, AttributeError):
  2360. pass
  2361. return
  2362. self.text_gui.text_path = []
  2363. self.text_gui.hide_tool()
  2364. self.complete = True
  2365. self.draw_app.app.inform.emit('[success]%s' % _(" Done. Adding Text completed."))
  2366. def utility_geometry(self, data=None):
  2367. """
  2368. Temporary geometry on screen while using this tool.
  2369. :param data: mouse position coords
  2370. :return:
  2371. """
  2372. dx = data[0] - self.origin[0]
  2373. dy = data[1] - self.origin[1]
  2374. try:
  2375. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2376. except Exception:
  2377. return
  2378. def clean_up(self):
  2379. self.draw_app.selected = []
  2380. self.draw_app.plot_all()
  2381. try:
  2382. self.draw_app.app.jump_signal.disconnect()
  2383. except (TypeError, AttributeError):
  2384. pass
  2385. class FCBuffer(FCShapeTool):
  2386. def __init__(self, draw_app):
  2387. FCShapeTool.__init__(self, draw_app)
  2388. self.name = 'buffer'
  2389. # self.shape_buffer = self.draw_app.shape_buffer
  2390. self.draw_app = draw_app
  2391. self.app = draw_app.app
  2392. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2393. self.origin = (0, 0)
  2394. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2395. self.buff_tool.run()
  2396. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2397. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2398. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2399. self.activate()
  2400. def on_buffer(self):
  2401. if not self.draw_app.selected:
  2402. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Buffer cancelled. No shape selected."))
  2403. return
  2404. try:
  2405. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2406. except ValueError:
  2407. # try to convert comma to decimal point. if it's still not working error message and return
  2408. try:
  2409. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2410. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2411. except ValueError:
  2412. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2413. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2414. return
  2415. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2416. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2417. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2418. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2419. self.app.ui.notebook.setTabText(2, _("Tools"))
  2420. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2421. self.disactivate()
  2422. if ret_val == 'fail':
  2423. return
  2424. self.draw_app.app.inform.emit('[success] %s' % _("Done. Buffer Tool completed."))
  2425. def on_buffer_int(self):
  2426. if not self.draw_app.selected:
  2427. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Buffer cancelled. No shape selected."))
  2428. return
  2429. try:
  2430. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2431. except ValueError:
  2432. # try to convert comma to decimal point. if it's still not working error message and return
  2433. try:
  2434. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2435. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2436. except ValueError:
  2437. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2438. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2439. return
  2440. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2441. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2442. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2443. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2444. self.app.ui.notebook.setTabText(2, _("Tools"))
  2445. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2446. self.disactivate()
  2447. if ret_val == 'fail':
  2448. return
  2449. self.draw_app.app.inform.emit('[success] %s' % _("Done. Buffer Int Tool completed."))
  2450. def on_buffer_ext(self):
  2451. if not self.draw_app.selected:
  2452. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Buffer cancelled. No shape selected."))
  2453. return
  2454. try:
  2455. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2456. except ValueError:
  2457. # try to convert comma to decimal point. if it's still not working error message and return
  2458. try:
  2459. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2460. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2461. except ValueError:
  2462. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2463. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2464. return
  2465. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2466. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2467. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2468. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2469. self.app.ui.notebook.setTabText(2, _("Tools"))
  2470. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2471. self.disactivate()
  2472. if ret_val == 'fail':
  2473. return
  2474. self.draw_app.app.inform.emit('[success] %s' % _("Done. Buffer Ext Tool completed."))
  2475. def activate(self):
  2476. self.buff_tool.buffer_button.clicked.disconnect()
  2477. self.buff_tool.buffer_int_button.clicked.disconnect()
  2478. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2479. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2480. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2481. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2482. def disactivate(self):
  2483. self.buff_tool.buffer_button.clicked.disconnect()
  2484. self.buff_tool.buffer_int_button.clicked.disconnect()
  2485. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2486. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2487. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2488. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2489. self.complete = True
  2490. self.draw_app.select_tool("select")
  2491. self.buff_tool.hide_tool()
  2492. try:
  2493. self.draw_app.app.jump_signal.disconnect()
  2494. except (TypeError, AttributeError):
  2495. pass
  2496. def clean_up(self):
  2497. self.draw_app.selected = []
  2498. self.draw_app.plot_all()
  2499. try:
  2500. self.draw_app.app.jump_signal.disconnect()
  2501. except (TypeError, AttributeError):
  2502. pass
  2503. class FCEraser(FCShapeTool):
  2504. def __init__(self, draw_app):
  2505. DrawTool.__init__(self, draw_app)
  2506. self.name = 'eraser'
  2507. self.draw_app = draw_app
  2508. self.origin = None
  2509. self.destination = None
  2510. if len(self.draw_app.get_selected()) == 0:
  2511. if self.draw_app.launched_from_shortcuts is True:
  2512. self.draw_app.launched_from_shortcuts = False
  2513. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2514. else:
  2515. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2516. self.geometry = []
  2517. self.storage = self.draw_app.storage
  2518. # Switch notebook to Selected page
  2519. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2520. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2521. def set_origin(self, origin):
  2522. self.origin = origin
  2523. def click(self, point):
  2524. try:
  2525. self.draw_app.app.jump_signal.disconnect()
  2526. except (TypeError, AttributeError):
  2527. pass
  2528. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2529. if len(self.draw_app.get_selected()) == 0:
  2530. for obj_shape in self.storage.get_objects():
  2531. try:
  2532. __, closest_shape = self.storage.nearest(point)
  2533. self.draw_app.selected.append(closest_shape)
  2534. except StopIteration:
  2535. if len(self.draw_app.selected) > 0:
  2536. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2537. return ""
  2538. if len(self.draw_app.get_selected()) == 0:
  2539. return "Nothing to ersase."
  2540. else:
  2541. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2542. if self.origin is None:
  2543. self.set_origin(point)
  2544. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2545. return
  2546. else:
  2547. self.destination = point
  2548. self.make()
  2549. # self.draw_app.select_tool("select")
  2550. return
  2551. def make(self):
  2552. eraser_sel_shapes = []
  2553. # create the eraser shape from selection
  2554. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2555. temp_shape = eraser_shape.buffer(0.0000001)
  2556. temp_shape = Polygon(temp_shape.exterior)
  2557. eraser_sel_shapes.append(temp_shape)
  2558. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2559. for obj_shape in self.storage.get_objects():
  2560. try:
  2561. geometric_data = obj_shape.geo
  2562. if eraser_sel_shapes.intersects(geometric_data):
  2563. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2564. except KeyError:
  2565. pass
  2566. self.draw_app.delete_utility_geometry()
  2567. self.draw_app.plot_all()
  2568. self.draw_app.app.inform.emit('[success] %s' % _("Done. Eraser tool action completed."))
  2569. try:
  2570. self.draw_app.app.jump_signal.disconnect()
  2571. except (TypeError, AttributeError):
  2572. pass
  2573. def utility_geometry(self, data=None):
  2574. """
  2575. Temporary geometry on screen while using this tool.
  2576. :param data:
  2577. :return:
  2578. """
  2579. geo_list = []
  2580. if self.origin is None:
  2581. return None
  2582. if len(self.draw_app.get_selected()) == 0:
  2583. return None
  2584. dx = data[0] - self.origin[0]
  2585. dy = data[1] - self.origin[1]
  2586. try:
  2587. for geom in self.draw_app.get_selected():
  2588. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2589. except AttributeError:
  2590. self.draw_app.select_tool('select')
  2591. self.draw_app.selected = []
  2592. return
  2593. return DrawToolUtilityShape(geo_list)
  2594. def clean_up(self):
  2595. self.draw_app.selected = []
  2596. self.draw_app.plot_all()
  2597. try:
  2598. self.draw_app.app.jump_signal.disconnect()
  2599. except (TypeError, AttributeError):
  2600. pass
  2601. class FCPaint(FCShapeTool):
  2602. def __init__(self, draw_app):
  2603. FCShapeTool.__init__(self, draw_app)
  2604. self.name = 'paint'
  2605. self.draw_app = draw_app
  2606. self.app = draw_app.app
  2607. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2608. self.origin = (0, 0)
  2609. self.draw_app.paint_tool.run()
  2610. class FCTransform(FCShapeTool):
  2611. def __init__(self, draw_app):
  2612. FCShapeTool.__init__(self, draw_app)
  2613. self.name = 'transformation'
  2614. self.draw_app = draw_app
  2615. self.app = draw_app.app
  2616. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2617. self.origin = (0, 0)
  2618. self.draw_app.transform_tool.run()
  2619. # ###############################################
  2620. # ################ Main Application #############
  2621. # ###############################################
  2622. class FlatCAMGeoEditor(QtCore.QObject):
  2623. # will emit the name of the object that was just selected
  2624. item_selected = QtCore.pyqtSignal(str)
  2625. transform_complete = QtCore.pyqtSignal()
  2626. draw_shape_idx = -1
  2627. def __init__(self, app, disabled=False):
  2628. assert isinstance(app, FlatCAMApp.App), \
  2629. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2630. super(FlatCAMGeoEditor, self).__init__()
  2631. self.app = app
  2632. self.canvas = app.plotcanvas
  2633. self.decimals = app.decimals
  2634. self.geo_edit_widget = QtWidgets.QWidget()
  2635. # ## Box for custom widgets
  2636. # This gets populated in offspring implementations.
  2637. layout = QtWidgets.QVBoxLayout()
  2638. self.geo_edit_widget.setLayout(layout)
  2639. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  2640. # this way I can hide/show the frame
  2641. self.geo_frame = QtWidgets.QFrame()
  2642. self.geo_frame.setContentsMargins(0, 0, 0, 0)
  2643. layout.addWidget(self.geo_frame)
  2644. self.tools_box = QtWidgets.QVBoxLayout()
  2645. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2646. self.geo_frame.setLayout(self.tools_box)
  2647. # ## Page Title box (spacing between children)
  2648. self.title_box = QtWidgets.QHBoxLayout()
  2649. self.tools_box.addLayout(self.title_box)
  2650. # ## Page Title icon
  2651. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  2652. self.icon = QtWidgets.QLabel()
  2653. self.icon.setPixmap(pixmap)
  2654. self.title_box.addWidget(self.icon, stretch=0)
  2655. # ## Title label
  2656. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Geometry Editor'))
  2657. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  2658. self.title_box.addWidget(self.title_label, stretch=1)
  2659. self.title_box.addWidget(QtWidgets.QLabel(''))
  2660. self.tw = FCTree(columns=3, header_hidden=False, protected_column=[0, 1], extended_sel=True)
  2661. self.tw.setHeaderLabels(["ID", _("Type"), _("Name")])
  2662. self.tw.setIndentation(0)
  2663. self.tw.header().setStretchLastSection(True)
  2664. self.tw.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2665. self.tools_box.addWidget(self.tw)
  2666. self.geo_font = QtGui.QFont()
  2667. self.geo_font.setBold(True)
  2668. self.geo_parent = self.tw.invisibleRootItem()
  2669. # ## Toolbar events and properties
  2670. self.tools = {
  2671. "select": {"button": self.app.ui.geo_select_btn, "constructor": FCSelect},
  2672. "arc": {"button": self.app.ui.geo_add_arc_btn, "constructor": FCArc},
  2673. "circle": {"button": self.app.ui.geo_add_circle_btn, "constructor": FCCircle},
  2674. "path": {"button": self.app.ui.geo_add_path_btn, "constructor": FCPath},
  2675. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn, "constructor": FCRectangle},
  2676. "polygon": {"button": self.app.ui.geo_add_polygon_btn, "constructor": FCPolygon},
  2677. "text": {"button": self.app.ui.geo_add_text_btn, "constructor": FCText},
  2678. "buffer": {"button": self.app.ui.geo_add_buffer_btn, "constructor": FCBuffer},
  2679. "paint": {"button": self.app.ui.geo_add_paint_btn, "constructor": FCPaint},
  2680. "eraser": {"button": self.app.ui.geo_eraser_btn, "constructor": FCEraser},
  2681. "move": {"button": self.app.ui.geo_move_btn, "constructor": FCMove},
  2682. "transform": {"button": self.app.ui.geo_transform_btn, "constructor": FCTransform},
  2683. "copy": {"button": self.app.ui.geo_copy_btn, "constructor": FCCopy},
  2684. "explode": {"button": self.app.ui.geo_explode_btn, "constructor": FCExplode}
  2685. }
  2686. # # ## Data
  2687. self.active_tool = None
  2688. self.storage = FlatCAMGeoEditor.make_storage()
  2689. self.utility = []
  2690. # VisPy visuals
  2691. self.fcgeometry = None
  2692. if self.app.is_legacy is False:
  2693. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2694. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2695. else:
  2696. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2697. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='shapes_geo_editor')
  2698. self.tool_shape = ShapeCollectionLegacy(obj=self, app=self.app, name='tool_shapes_geo_editor')
  2699. self.app.pool_recreated.connect(self.pool_recreated)
  2700. # Remove from scene
  2701. self.shapes.enabled = False
  2702. self.tool_shape.enabled = False
  2703. # List of selected shapes.
  2704. self.selected = []
  2705. self.flat_geo = []
  2706. self.move_timer = QtCore.QTimer()
  2707. self.move_timer.setSingleShot(True)
  2708. # this var will store the state of the toolbar before starting the editor
  2709. self.toolbar_old_state = False
  2710. self.key = None # Currently pressed key
  2711. self.geo_key_modifiers = None
  2712. self.x = None # Current mouse cursor pos
  2713. self.y = None
  2714. # if we edit a multigeo geometry store here the tool number
  2715. self.multigeo_tool = None
  2716. # Current snapped mouse pos
  2717. self.snap_x = None
  2718. self.snap_y = None
  2719. self.pos = None
  2720. # signal that there is an action active like polygon or path
  2721. self.in_action = False
  2722. self.units = None
  2723. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2724. self.launched_from_shortcuts = False
  2725. def make_callback(thetool):
  2726. def f():
  2727. self.on_tool_select(thetool)
  2728. return f
  2729. for tool in self.tools:
  2730. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2731. self.tools[tool]["button"].setCheckable(True) # Checkable
  2732. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2733. self.app.ui.corner_snap_btn.setCheckable(True)
  2734. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2735. self.options = {
  2736. "global_gridx": 0.1,
  2737. "global_gridy": 0.1,
  2738. "global_snap_max": 0.05,
  2739. "grid_snap": True,
  2740. "corner_snap": False,
  2741. "grid_gap_link": True
  2742. }
  2743. self.options.update(self.app.options)
  2744. for option in self.options:
  2745. if option in self.app.options:
  2746. self.options[option] = self.app.options[option]
  2747. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2748. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2749. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2750. self.app.ui.grid_gap_link_cb.setChecked(True)
  2751. self.rtree_index = rtindex.Index()
  2752. def entry2option(option, entry):
  2753. try:
  2754. self.options[option] = float(entry.text())
  2755. except Exception as e:
  2756. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2757. return
  2758. def gridx_changed(goption, gentry):
  2759. entry2option(option=goption, entry=gentry)
  2760. # if the grid link is checked copy the value in the GridX field to GridY
  2761. try:
  2762. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2763. except ValueError:
  2764. return
  2765. units = self.app.defaults['units'].upper()
  2766. if self.app.ui.grid_gap_link_cb.isChecked():
  2767. self.app.ui.grid_gap_y_entry.set_value(val, decimals=self.decimals)
  2768. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2769. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2770. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2771. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2772. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2773. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2774. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2775. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2776. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2777. # if using Paint store here the tool diameter used
  2778. self.paint_tooldia = None
  2779. self.paint_tool = PaintOptionsTool(self.app, self)
  2780. self.transform_tool = TransformEditorTool(self.app, self)
  2781. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2782. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2783. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2784. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2785. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2786. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2787. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2788. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2789. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2790. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2791. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2792. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2793. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2794. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2795. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2796. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2797. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2798. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2799. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2800. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2801. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2802. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2803. self.transform_complete.connect(self.on_transform_complete)
  2804. # Event signals disconnect id holders
  2805. self.mp = None
  2806. self.mm = None
  2807. self.mr = None
  2808. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2809. self.editor_active = False
  2810. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2811. def pool_recreated(self, pool):
  2812. self.shapes.pool = pool
  2813. self.tool_shape.pool = pool
  2814. def on_transform_complete(self):
  2815. self.delete_selected()
  2816. self.replot()
  2817. def set_ui(self):
  2818. # updated units
  2819. self.units = self.app.defaults['units'].upper()
  2820. self.decimals = self.app.decimals
  2821. # Remove anything else in the GUI Selected Tab
  2822. self.app.ui.selected_scroll_area.takeWidget()
  2823. # Put ourselves in the GUI Selected Tab
  2824. self.app.ui.selected_scroll_area.setWidget(self.geo_edit_widget)
  2825. # Switch notebook to Selected page
  2826. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2827. def build_ui(self, first_run=None):
  2828. # try:
  2829. # # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2830. # self.apertures_table.itemChanged.disconnect()
  2831. # except (TypeError, AttributeError):
  2832. # pass
  2833. iterator = QtWidgets.QTreeWidgetItemIterator(self.geo_parent)
  2834. to_delete = []
  2835. while iterator.value():
  2836. item = iterator.value()
  2837. to_delete.append(item)
  2838. iterator += 1
  2839. for it in to_delete:
  2840. self.geo_parent.removeChild(it)
  2841. for elem in self.storage.get_objects():
  2842. geo_type = type(elem.geo)
  2843. el_type = None
  2844. if geo_type is LinearRing:
  2845. el_type = _('Ring')
  2846. elif geo_type is LineString:
  2847. el_type = _('Line')
  2848. elif geo_type is Polygon:
  2849. el_type = _('Polygon')
  2850. elif geo_type is MultiLineString:
  2851. el_type = _('Multi-Line')
  2852. elif geo_type is MultiPolygon:
  2853. el_type = _('Multi-Polygon')
  2854. self.tw.addParentEditable(
  2855. self.geo_parent,
  2856. [
  2857. str(id(elem)),
  2858. '%s' % el_type,
  2859. _("Geo Elem")
  2860. ],
  2861. font=self.geo_font,
  2862. font_items=2,
  2863. # color=QtGui.QColor("#FF0000"),
  2864. editable=True
  2865. )
  2866. self.tw.resize_sig.emit()
  2867. def on_geo_elem_selected(self):
  2868. pass
  2869. def on_tree_selection_change(self):
  2870. self.selected = []
  2871. selected_tree_items = self.tw.selectedItems()
  2872. for sel in selected_tree_items:
  2873. for obj_shape in self.storage.get_objects():
  2874. try:
  2875. if id(obj_shape) == int(sel.text(0)):
  2876. self.selected.append(obj_shape)
  2877. except ValueError:
  2878. pass
  2879. self.replot()
  2880. def activate(self):
  2881. # adjust the status of the menu entries related to the editor
  2882. self.app.ui.menueditedit.setDisabled(True)
  2883. self.app.ui.menueditok.setDisabled(False)
  2884. # adjust the visibility of some of the canvas context menu
  2885. self.app.ui.popmenu_edit.setVisible(False)
  2886. self.app.ui.popmenu_save.setVisible(True)
  2887. self.connect_canvas_event_handlers()
  2888. # initialize working objects
  2889. self.storage = FlatCAMGeoEditor.make_storage()
  2890. self.utility = []
  2891. self.selected = []
  2892. self.shapes.enabled = True
  2893. self.tool_shape.enabled = True
  2894. self.app.app_cursor.enabled = True
  2895. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2896. self.app.ui.corner_snap_btn.setEnabled(True)
  2897. self.app.ui.snap_magnet.setVisible(True)
  2898. self.app.ui.corner_snap_btn.setVisible(True)
  2899. self.app.ui.geo_editor_menu.setDisabled(False)
  2900. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2901. self.app.ui.update_obj_btn.setEnabled(True)
  2902. self.app.ui.g_editor_cmenu.setEnabled(True)
  2903. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2904. self.app.ui.geo_edit_toolbar.setVisible(True)
  2905. self.app.ui.snap_toolbar.setDisabled(False)
  2906. self.app.ui.popmenu_disable.setVisible(False)
  2907. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2908. self.app.ui.popmenu_properties.setVisible(False)
  2909. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2910. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2911. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2912. # for w in sel_tab_widget_list:
  2913. # w.setEnabled(False)
  2914. # Tell the App that the editor is active
  2915. self.editor_active = True
  2916. self.item_selected.connect(self.on_geo_elem_selected)
  2917. # ## GUI Events
  2918. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  2919. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2920. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2921. self.geo_frame.show()
  2922. log.debug("Finished activating the Geometry Editor...")
  2923. def deactivate(self):
  2924. try:
  2925. QtGui.QGuiApplication.restoreOverrideCursor()
  2926. except Exception:
  2927. pass
  2928. # adjust the status of the menu entries related to the editor
  2929. self.app.ui.menueditedit.setDisabled(False)
  2930. self.app.ui.menueditok.setDisabled(True)
  2931. # adjust the visibility of some of the canvas context menu
  2932. self.app.ui.popmenu_edit.setVisible(True)
  2933. self.app.ui.popmenu_save.setVisible(False)
  2934. self.disconnect_canvas_event_handlers()
  2935. self.clear()
  2936. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2937. settings = QSettings("Open Source", "FlatCAM")
  2938. if settings.contains("layout"):
  2939. layout = settings.value('layout', type=str)
  2940. if layout == 'standard':
  2941. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2942. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2943. self.app.ui.corner_snap_btn.setEnabled(False)
  2944. self.app.ui.snap_magnet.setVisible(False)
  2945. self.app.ui.corner_snap_btn.setVisible(False)
  2946. elif layout == 'compact':
  2947. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2948. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2949. self.app.ui.corner_snap_btn.setEnabled(False)
  2950. else:
  2951. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2952. self.app.ui.snap_magnet.setVisible(False)
  2953. self.app.ui.corner_snap_btn.setVisible(False)
  2954. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2955. self.app.ui.corner_snap_btn.setEnabled(False)
  2956. # set the Editor Toolbar visibility to what was before entering in the Editor
  2957. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2958. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2959. # Disable visuals
  2960. self.shapes.enabled = False
  2961. self.tool_shape.enabled = False
  2962. self.app.ui.geo_editor_menu.setDisabled(True)
  2963. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2964. self.app.ui.update_obj_btn.setEnabled(False)
  2965. self.app.ui.g_editor_cmenu.setEnabled(False)
  2966. self.app.ui.e_editor_cmenu.setEnabled(False)
  2967. # Tell the app that the editor is no longer active
  2968. self.editor_active = False
  2969. self.app.ui.popmenu_disable.setVisible(True)
  2970. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2971. self.app.ui.popmenu_properties.setVisible(True)
  2972. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2973. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2974. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2975. try:
  2976. self.item_selected.disconnect()
  2977. except (AttributeError, TypeError):
  2978. pass
  2979. try:
  2980. # ## GUI Events
  2981. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  2982. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2983. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2984. except (AttributeError, TypeError):
  2985. pass
  2986. # try:
  2987. # # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2988. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2989. # for w in sel_tab_widget_list:
  2990. # w.setEnabled(True)
  2991. # except Exception as e:
  2992. # log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2993. # Show original geometry
  2994. if self.fcgeometry:
  2995. self.fcgeometry.visible = True
  2996. # clear the Tree
  2997. self.tw.clear()
  2998. self.geo_parent = self.tw.invisibleRootItem()
  2999. # hide the UI
  3000. self.geo_frame.hide()
  3001. log.debug("Finished deactivating the Geometry Editor...")
  3002. def connect_canvas_event_handlers(self):
  3003. # Canvas events
  3004. # first connect to new, then disconnect the old handlers
  3005. # don't ask why but if there is nothing connected I've seen issues
  3006. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  3007. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  3008. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_geo_click_release)
  3009. if self.app.is_legacy is False:
  3010. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  3011. # but those from FlatCAMGeoEditor
  3012. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  3013. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  3014. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  3015. self.app.plotcanvas.graph_event_disconnect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  3016. else:
  3017. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  3018. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  3019. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  3020. self.app.plotcanvas.graph_event_disconnect(self.app.mdc)
  3021. # self.app.collection.view.clicked.disconnect()
  3022. self.app.ui.popmenu_copy.triggered.disconnect()
  3023. self.app.ui.popmenu_delete.triggered.disconnect()
  3024. self.app.ui.popmenu_move.triggered.disconnect()
  3025. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  3026. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  3027. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  3028. # Geometry Editor
  3029. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  3030. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  3031. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  3032. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  3033. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  3034. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  3035. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  3036. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  3037. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  3038. self.app.ui.draw_union.triggered.connect(self.union)
  3039. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  3040. self.app.ui.draw_substract.triggered.connect(self.subtract)
  3041. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  3042. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  3043. self.app.ui.draw_move.triggered.connect(self.on_move)
  3044. def disconnect_canvas_event_handlers(self):
  3045. # we restore the key and mouse control to FlatCAMApp method
  3046. # first connect to new, then disconnect the old handlers
  3047. # don't ask why but if there is nothing connected I've seen issues
  3048. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  3049. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  3050. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  3051. self.app.on_mouse_click_release_over_plot)
  3052. self.app.mdc = self.app.plotcanvas.graph_event_connect('mouse_double_click',
  3053. self.app.on_mouse_double_click_over_plot)
  3054. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  3055. if self.app.is_legacy is False:
  3056. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  3057. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  3058. self.canvas.graph_event_disconnect('mouse_release', self.on_geo_click_release)
  3059. else:
  3060. self.canvas.graph_event_disconnect(self.mp)
  3061. self.canvas.graph_event_disconnect(self.mm)
  3062. self.canvas.graph_event_disconnect(self.mr)
  3063. try:
  3064. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  3065. except (TypeError, AttributeError):
  3066. pass
  3067. try:
  3068. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  3069. except (TypeError, AttributeError):
  3070. pass
  3071. try:
  3072. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  3073. except (TypeError, AttributeError):
  3074. pass
  3075. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_command)
  3076. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  3077. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  3078. # Geometry Editor
  3079. try:
  3080. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  3081. except (TypeError, AttributeError):
  3082. pass
  3083. try:
  3084. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  3085. except (TypeError, AttributeError):
  3086. pass
  3087. try:
  3088. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  3089. except (TypeError, AttributeError):
  3090. pass
  3091. try:
  3092. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  3093. except (TypeError, AttributeError):
  3094. pass
  3095. try:
  3096. self.app.ui.draw_circle.triggered.disconnect()
  3097. except (TypeError, AttributeError):
  3098. pass
  3099. try:
  3100. self.app.ui.draw_poly.triggered.disconnect()
  3101. except (TypeError, AttributeError):
  3102. pass
  3103. try:
  3104. self.app.ui.draw_arc.triggered.disconnect()
  3105. except (TypeError, AttributeError):
  3106. pass
  3107. try:
  3108. self.app.ui.draw_text.triggered.disconnect()
  3109. except (TypeError, AttributeError):
  3110. pass
  3111. try:
  3112. self.app.ui.draw_buffer.triggered.disconnect()
  3113. except (TypeError, AttributeError):
  3114. pass
  3115. try:
  3116. self.app.ui.draw_paint.triggered.disconnect()
  3117. except (TypeError, AttributeError):
  3118. pass
  3119. try:
  3120. self.app.ui.draw_eraser.triggered.disconnect()
  3121. except (TypeError, AttributeError):
  3122. pass
  3123. try:
  3124. self.app.ui.draw_union.triggered.disconnect(self.union)
  3125. except (TypeError, AttributeError):
  3126. pass
  3127. try:
  3128. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  3129. except (TypeError, AttributeError):
  3130. pass
  3131. try:
  3132. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  3133. except (TypeError, AttributeError):
  3134. pass
  3135. try:
  3136. self.app.ui.draw_transform.triggered.disconnect()
  3137. except (TypeError, AttributeError):
  3138. pass
  3139. try:
  3140. self.app.jump_signal.disconnect()
  3141. except (TypeError, AttributeError):
  3142. pass
  3143. def add_shape(self, shape):
  3144. """
  3145. Adds a shape to the shape storage.
  3146. :param shape: Shape to be added.
  3147. :type shape: DrawToolShape
  3148. :return: None
  3149. """
  3150. if shape is None:
  3151. return
  3152. # List of DrawToolShape?
  3153. if isinstance(shape, list):
  3154. for subshape in shape:
  3155. self.add_shape(subshape)
  3156. return
  3157. assert isinstance(shape, DrawToolShape), "Expected a DrawToolShape, got %s" % type(shape)
  3158. assert shape.geo is not None, "Shape object has empty geometry (None)"
  3159. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  3160. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  3161. if isinstance(shape, DrawToolUtilityShape):
  3162. self.utility.append(shape)
  3163. else:
  3164. self.storage.insert(shape) # TODO: Check performance
  3165. self.build_ui()
  3166. def delete_utility_geometry(self):
  3167. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3168. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3169. for_deletion = [shape for shape in self.utility]
  3170. for shape in for_deletion:
  3171. self.delete_shape(shape)
  3172. self.tool_shape.clear(update=True)
  3173. self.tool_shape.redraw()
  3174. def toolbar_tool_toggle(self, key):
  3175. self.options[key] = self.sender().isChecked()
  3176. return 1 if self.options[key] == True else 0
  3177. def clear(self):
  3178. self.active_tool = None
  3179. # self.shape_buffer = []
  3180. self.selected = []
  3181. self.shapes.clear(update=True)
  3182. self.tool_shape.clear(update=True)
  3183. # self.storage = FlatCAMGeoEditor.make_storage()
  3184. self.replot()
  3185. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  3186. """
  3187. Imports the geometry from the given FlatCAM Geometry object
  3188. into the editor.
  3189. :param fcgeometry: FlatCAMGeometry
  3190. :param multigeo_tool: a tool for the case of multigeo
  3191. :return: None
  3192. """
  3193. assert isinstance(fcgeometry, Geometry), \
  3194. "Expected a Geometry, got %s" % type(fcgeometry)
  3195. self.deactivate()
  3196. self.activate()
  3197. self.set_ui()
  3198. # Hide original geometry
  3199. self.fcgeometry = fcgeometry
  3200. fcgeometry.visible = False
  3201. # Set selection tolerance
  3202. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3203. self.select_tool("select")
  3204. if self.app.defaults['geometry_spindledir'] == 'CW':
  3205. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3206. milling_type = 1 # CCW motion = climb milling (spindle is rotating CW)
  3207. else:
  3208. milling_type = -1 # CW motion = conventional milling (spindle is rotating CW)
  3209. else:
  3210. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3211. milling_type = -1 # CCW motion = climb milling (spindle is rotating CCW)
  3212. else:
  3213. milling_type = 1 # CW motion = conventional milling (spindle is rotating CCW)
  3214. # Link shapes into editor.
  3215. if multigeo_tool:
  3216. self.multigeo_tool = multigeo_tool
  3217. geo_to_edit = self.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'],
  3218. orient_val=milling_type)
  3219. self.app.inform.emit(
  3220. '[WARNING_NOTCL] %s: %s %s: %s' % (
  3221. _("Editing MultiGeo Geometry, tool"),
  3222. str(self.multigeo_tool),
  3223. _("with diameter"),
  3224. str(fcgeometry.tools[self.multigeo_tool]['tooldia'])
  3225. )
  3226. )
  3227. else:
  3228. geo_to_edit = self.flatten(geometry=fcgeometry.solid_geometry, orient_val=milling_type)
  3229. for shape in geo_to_edit:
  3230. if shape is not None: # TODO: Make flatten never create a None
  3231. if type(shape) == Polygon:
  3232. self.add_shape(DrawToolShape(shape.exterior))
  3233. for inter in shape.interiors:
  3234. self.add_shape(DrawToolShape(inter))
  3235. else:
  3236. self.add_shape(DrawToolShape(shape))
  3237. self.replot()
  3238. # updated units
  3239. self.units = self.app.defaults['units'].upper()
  3240. self.decimals = self.app.decimals
  3241. # start with GRID toolbar activated
  3242. if self.app.ui.grid_snap_btn.isChecked() is False:
  3243. self.app.ui.grid_snap_btn.trigger()
  3244. self.app.on_grid_snap_triggered(state=True)
  3245. def on_buffer_tool(self):
  3246. buff_tool = BufferSelectionTool(self.app, self)
  3247. buff_tool.run()
  3248. def on_paint_tool(self):
  3249. paint_tool = PaintOptionsTool(self.app, self)
  3250. paint_tool.run()
  3251. def on_tool_select(self, tool):
  3252. """
  3253. Behavior of the toolbar. Tool initialization.
  3254. :rtype : None
  3255. """
  3256. self.app.log.debug("on_tool_select('%s')" % tool)
  3257. # This is to make the group behave as radio group
  3258. if tool in self.tools:
  3259. if self.tools[tool]["button"].isChecked():
  3260. self.app.log.debug("%s is checked." % tool)
  3261. for t in self.tools:
  3262. if t != tool:
  3263. self.tools[t]["button"].setChecked(False)
  3264. self.active_tool = self.tools[tool]["constructor"](self)
  3265. else:
  3266. self.app.log.debug("%s is NOT checked." % tool)
  3267. for t in self.tools:
  3268. self.tools[t]["button"].setChecked(False)
  3269. self.select_tool('select')
  3270. self.active_tool = FCSelect(self)
  3271. def draw_tool_path(self):
  3272. self.select_tool('path')
  3273. return
  3274. def draw_tool_rectangle(self):
  3275. self.select_tool('rectangle')
  3276. return
  3277. def on_grid_toggled(self):
  3278. self.toolbar_tool_toggle("grid_snap")
  3279. # make sure that the cursor shape is enabled/disabled, too
  3280. if self.options['grid_snap'] is True:
  3281. self.app.app_cursor.enabled = True
  3282. else:
  3283. self.app.app_cursor.enabled = False
  3284. def on_canvas_click(self, event):
  3285. """
  3286. event.x and .y have canvas coordinates
  3287. event.xdaya and .ydata have plot coordinates
  3288. :param event: Event object dispatched by Matplotlib
  3289. :return: None
  3290. """
  3291. if self.app.is_legacy is False:
  3292. event_pos = event.pos
  3293. else:
  3294. event_pos = (event.xdata, event.ydata)
  3295. self.pos = self.canvas.translate_coords(event_pos)
  3296. if self.app.grid_status():
  3297. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  3298. else:
  3299. self.pos = (self.pos[0], self.pos[1])
  3300. if event.button == 1:
  3301. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3302. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3303. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3304. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3305. if modifiers == QtCore.Qt.ShiftModifier:
  3306. self.app.clipboard.setText(
  3307. self.app.defaults["global_point_clipboard_format"] %
  3308. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  3309. )
  3310. return
  3311. # Selection with left mouse button
  3312. if self.active_tool is not None and event.button == 1:
  3313. # Dispatch event to active_tool
  3314. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3315. # If it is a shape generating tool
  3316. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3317. self.on_shape_complete()
  3318. if isinstance(self.active_tool, FCText):
  3319. self.select_tool("select")
  3320. else:
  3321. self.select_tool(self.active_tool.name)
  3322. if isinstance(self.active_tool, FCSelect):
  3323. # self.app.log.debug("Replotting after click.")
  3324. self.replot()
  3325. else:
  3326. self.app.log.debug("No active tool to respond to click!")
  3327. def on_canvas_move(self, event):
  3328. """
  3329. Called on 'mouse_move' event
  3330. event.pos have canvas screen coordinates
  3331. :param event: Event object dispatched by VisPy SceneCavas
  3332. :return: None
  3333. """
  3334. if self.app.is_legacy is False:
  3335. event_pos = event.pos
  3336. event_is_dragging = event.is_dragging
  3337. right_button = 2
  3338. else:
  3339. event_pos = (event.xdata, event.ydata)
  3340. event_is_dragging = self.app.plotcanvas.is_dragging
  3341. right_button = 3
  3342. pos = self.canvas.translate_coords(event_pos)
  3343. event.xdata, event.ydata = pos[0], pos[1]
  3344. self.x = event.xdata
  3345. self.y = event.ydata
  3346. self.app.ui.popMenu.mouse_is_panning = False
  3347. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3348. if event.button == right_button:
  3349. if event_is_dragging:
  3350. self.app.ui.popMenu.mouse_is_panning = True
  3351. # return
  3352. else:
  3353. self.app.ui.popMenu.mouse_is_panning = False
  3354. if self.active_tool is None:
  3355. return
  3356. try:
  3357. x = float(event.xdata)
  3358. y = float(event.ydata)
  3359. except TypeError:
  3360. return
  3361. # ### Snap coordinates ###
  3362. if self.app.grid_status():
  3363. x, y = self.snap(x, y)
  3364. # Update cursor
  3365. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3366. edge_width=self.app.defaults["global_cursor_width"],
  3367. size=self.app.defaults["global_cursor_size"])
  3368. self.snap_x = x
  3369. self.snap_y = y
  3370. self.app.mouse = [x, y]
  3371. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3372. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3373. "<b>Y</b>: %.4f" % (x, y))
  3374. if self.pos is None:
  3375. self.pos = (0, 0)
  3376. dx = x - self.pos[0]
  3377. dy = y - self.pos[1]
  3378. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3379. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3380. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3381. if event.button == 1 and event_is_dragging and isinstance(self.active_tool, FCEraser):
  3382. pass
  3383. else:
  3384. self.update_utility_geometry(data=(x, y))
  3385. # ### Selection area on canvas section ###
  3386. dx = pos[0] - self.pos[0]
  3387. if event_is_dragging and event.button == 1:
  3388. self.app.delete_selection_shape()
  3389. if dx < 0:
  3390. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3391. color=self.app.defaults["global_alt_sel_line"],
  3392. face_color=self.app.defaults['global_alt_sel_fill'])
  3393. self.app.selection_type = False
  3394. else:
  3395. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3396. self.app.selection_type = True
  3397. else:
  3398. self.app.selection_type = None
  3399. def update_utility_geometry(self, data):
  3400. # ### Utility geometry (animated) ###
  3401. geo = self.active_tool.utility_geometry(data=data)
  3402. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3403. # Remove any previous utility shape
  3404. self.tool_shape.clear(update=True)
  3405. self.draw_utility_geometry(geo=geo)
  3406. def on_geo_click_release(self, event):
  3407. if self.app.is_legacy is False:
  3408. event_pos = event.pos
  3409. event_is_dragging = event.is_dragging
  3410. right_button = 2
  3411. else:
  3412. event_pos = (event.xdata, event.ydata)
  3413. event_is_dragging = self.app.plotcanvas.is_dragging
  3414. right_button = 3
  3415. pos_canvas = self.canvas.translate_coords(event_pos)
  3416. if self.app.grid_status() == True:
  3417. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3418. else:
  3419. pos = (pos_canvas[0], pos_canvas[1])
  3420. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3421. # canvas menu
  3422. try:
  3423. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3424. # selection and then select a type of selection ("enclosing" or "touching")
  3425. if event.button == 1: # left click
  3426. if self.app.selection_type is not None:
  3427. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3428. self.app.selection_type = None
  3429. elif isinstance(self.active_tool, FCSelect):
  3430. # Dispatch event to active_tool
  3431. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3432. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3433. # self.app.inform.emit(msg)
  3434. self.replot()
  3435. elif event.button == right_button: # right click
  3436. if self.app.ui.popMenu.mouse_is_panning is False:
  3437. if self.in_action is False:
  3438. try:
  3439. QtGui.QGuiApplication.restoreOverrideCursor()
  3440. except Exception:
  3441. pass
  3442. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3443. self.active_tool.complete = True
  3444. self.in_action = False
  3445. self.delete_utility_geometry()
  3446. self.app.inform.emit('[success] %s' % _("Done."))
  3447. self.select_tool('select')
  3448. else:
  3449. self.app.cursor = QtGui.QCursor()
  3450. self.app.populate_cmenu_grids()
  3451. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3452. else:
  3453. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3454. # right mouse click will finish the action
  3455. if isinstance(self.active_tool, FCShapeTool):
  3456. self.active_tool.click(self.snap(self.x, self.y))
  3457. self.active_tool.make()
  3458. if self.active_tool.complete:
  3459. self.on_shape_complete()
  3460. self.app.inform.emit('[success] %s' % _("Done."))
  3461. self.select_tool(self.active_tool.name)
  3462. except Exception as e:
  3463. log.warning("FLatCAMGeoEditor.on_geo_click_release() --> Error: %s" % str(e))
  3464. return
  3465. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3466. """
  3467. :param start_pos: mouse position when the selection LMB click was done
  3468. :param end_pos: mouse position when the left mouse button is released
  3469. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3470. :return:
  3471. """
  3472. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3473. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3474. if key_modifier == QtCore.Qt.ShiftModifier:
  3475. mod_key = 'Shift'
  3476. elif key_modifier == QtCore.Qt.ControlModifier:
  3477. mod_key = 'Control'
  3478. else:
  3479. mod_key = None
  3480. self.app.delete_selection_shape()
  3481. sel_objects_list = []
  3482. for obj in self.storage.get_objects():
  3483. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3484. poly_selection.intersects(obj.geo)):
  3485. sel_objects_list.append(obj)
  3486. if mod_key == self.app.defaults["global_mselect_key"]:
  3487. for obj in sel_objects_list:
  3488. if obj in self.selected:
  3489. self.selected.remove(obj)
  3490. else:
  3491. # add the object to the selected shapes
  3492. self.selected.append(obj)
  3493. else:
  3494. self.selected = []
  3495. self.selected = sel_objects_list
  3496. # if selection is done on canvas update the Tree in Selected Tab with the selection
  3497. try:
  3498. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  3499. except (AttributeError, TypeError):
  3500. pass
  3501. self.tw.selectionModel().clearSelection()
  3502. for sel_shape in self.selected:
  3503. iterator = QtWidgets.QTreeWidgetItemIterator(self.tw)
  3504. while iterator.value():
  3505. item = iterator.value()
  3506. try:
  3507. if int(item.text(1)) == id(sel_shape):
  3508. item.setSelected(True)
  3509. except ValueError:
  3510. pass
  3511. iterator += 1
  3512. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  3513. self.replot()
  3514. def draw_utility_geometry(self, geo):
  3515. # Add the new utility shape
  3516. try:
  3517. # this case is for the Font Parse
  3518. for el in list(geo.geo):
  3519. if type(el) == MultiPolygon:
  3520. for poly in el:
  3521. self.tool_shape.add(
  3522. shape=poly,
  3523. color=(self.app.defaults["global_draw_color"] + '80'),
  3524. update=False,
  3525. layer=0,
  3526. tolerance=None
  3527. )
  3528. elif type(el) == MultiLineString:
  3529. for linestring in el:
  3530. self.tool_shape.add(
  3531. shape=linestring,
  3532. color=(self.app.defaults["global_draw_color"] + '80'),
  3533. update=False,
  3534. layer=0,
  3535. tolerance=None
  3536. )
  3537. else:
  3538. self.tool_shape.add(
  3539. shape=el,
  3540. color=(self.app.defaults["global_draw_color"] + '80'),
  3541. update=False,
  3542. layer=0,
  3543. tolerance=None
  3544. )
  3545. except TypeError:
  3546. self.tool_shape.add(
  3547. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3548. update=False, layer=0, tolerance=None)
  3549. self.tool_shape.redraw()
  3550. def on_delete_btn(self):
  3551. self.delete_selected()
  3552. self.replot()
  3553. def delete_selected(self):
  3554. tempref = [s for s in self.selected]
  3555. for shape in tempref:
  3556. self.delete_shape(shape)
  3557. self.selected = []
  3558. self.build_ui()
  3559. def delete_shape(self, shape):
  3560. if shape in self.utility:
  3561. self.utility.remove(shape)
  3562. return
  3563. self.storage.remove(shape)
  3564. if shape in self.selected:
  3565. self.selected.remove(shape) # TODO: Check performance
  3566. def on_move(self):
  3567. # if not self.selected:
  3568. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3569. # return
  3570. self.app.ui.geo_move_btn.setChecked(True)
  3571. self.on_tool_select('move')
  3572. def on_move_click(self):
  3573. self.on_move()
  3574. self.active_tool.set_origin(self.snap(self.x, self.y))
  3575. def on_copy_click(self):
  3576. if not self.selected:
  3577. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3578. _("Copy cancelled. No shape selected."))
  3579. return
  3580. self.app.ui.geo_copy_btn.setChecked(True)
  3581. self.app.geo_editor.on_tool_select('copy')
  3582. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3583. self.app.geo_editor.x, self.app.geo_editor.y))
  3584. self.app.inform.emit(_("Click on target point."))
  3585. def on_corner_snap(self):
  3586. self.app.ui.corner_snap_btn.trigger()
  3587. def get_selected(self):
  3588. """
  3589. Returns list of shapes that are selected in the editor.
  3590. :return: List of shapes.
  3591. """
  3592. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3593. return self.selected
  3594. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3595. """
  3596. Plots a geometric object or list of objects without rendering. Plotted objects
  3597. are returned as a list. This allows for efficient/animated rendering.
  3598. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3599. :param color: Shape color
  3600. :param linewidth: Width of lines in # of pixels.
  3601. :return: List of plotted elements.
  3602. """
  3603. plot_elements = []
  3604. if geometry is None:
  3605. geometry = self.active_tool.geometry
  3606. try:
  3607. for geo in geometry:
  3608. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3609. # Non-iterable
  3610. except TypeError:
  3611. # DrawToolShape
  3612. if isinstance(geometry, DrawToolShape):
  3613. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3614. # Polygon: Descend into exterior and each interior.
  3615. if type(geometry) == Polygon:
  3616. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3617. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3618. if type(geometry) == LineString or type(geometry) == LinearRing:
  3619. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3620. tolerance=self.fcgeometry.drawing_tolerance,
  3621. linewidth=linewidth))
  3622. if type(geometry) == Point:
  3623. pass
  3624. return plot_elements
  3625. def plot_all(self):
  3626. """
  3627. Plots all shapes in the editor.
  3628. :return: None
  3629. :rtype: None
  3630. """
  3631. # self.app.log.debug("plot_all()")
  3632. self.shapes.clear(update=True)
  3633. for shape in self.storage.get_objects():
  3634. if shape.geo is None: # TODO: This shouldn't have happened
  3635. continue
  3636. if shape in self.selected:
  3637. self.plot_shape(geometry=shape.geo,
  3638. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3639. linewidth=2)
  3640. continue
  3641. self.plot_shape(geometry=shape.geo,
  3642. color=self.app.defaults['global_draw_color'] + "FF")
  3643. for shape in self.utility:
  3644. self.plot_shape(geometry=shape.geo,
  3645. linewidth=1)
  3646. continue
  3647. self.shapes.redraw()
  3648. def replot(self):
  3649. self.plot_all()
  3650. def on_shape_complete(self):
  3651. self.app.log.debug("on_shape_complete()")
  3652. geom = []
  3653. try:
  3654. for shape in self.active_tool.geometry:
  3655. geom.append(shape.geo)
  3656. except TypeError:
  3657. geom = self.active_tool.geometry.geo
  3658. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3659. # reverse the geometry coordinates direction to allow creation of Gcode for climb milling
  3660. try:
  3661. pl = []
  3662. for p in geom:
  3663. if p is not None:
  3664. if isinstance(p, Polygon):
  3665. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3666. elif isinstance(p, LinearRing):
  3667. pl.append(Polygon(p.coords[::-1]))
  3668. elif isinstance(p, LineString):
  3669. pl.append(LineString(p.coords[::-1]))
  3670. try:
  3671. geom = MultiPolygon(pl)
  3672. except TypeError:
  3673. # this may happen if the geom elements are made out of LineStrings because you can't create a
  3674. # MultiPolygon out of LineStrings
  3675. pass
  3676. except TypeError:
  3677. if isinstance(geom, Polygon) and geom is not None:
  3678. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3679. elif isinstance(geom, LinearRing) and geom is not None:
  3680. geom = Polygon(geom.coords[::-1])
  3681. elif isinstance(geom, LineString) and geom is not None:
  3682. geom = LineString(geom.coords[::-1])
  3683. else:
  3684. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> Unexpected Geometry %s" %
  3685. type(geom))
  3686. except Exception as e:
  3687. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> %s" % str(e))
  3688. return 'fail'
  3689. shape_list = []
  3690. try:
  3691. for geo in geom:
  3692. shape_list.append(DrawToolShape(geo))
  3693. except TypeError:
  3694. shape_list.append(DrawToolShape(geom))
  3695. # Add shape
  3696. self.add_shape(shape_list)
  3697. # Remove any utility shapes
  3698. self.delete_utility_geometry()
  3699. self.tool_shape.clear(update=True)
  3700. # Replot and reset tool.
  3701. self.replot()
  3702. # self.active_tool = type(self.active_tool)(self)
  3703. @staticmethod
  3704. def make_storage():
  3705. # Shape storage.
  3706. storage = FlatCAMRTreeStorage()
  3707. storage.get_points = DrawToolShape.get_pts
  3708. return storage
  3709. def select_tool(self, toolname):
  3710. """
  3711. Selects a drawing tool. Impacts the object and GUI.
  3712. :param toolname: Name of the tool.
  3713. :return: None
  3714. """
  3715. self.tools[toolname]["button"].setChecked(True)
  3716. self.on_tool_select(toolname)
  3717. def set_selected(self, shape):
  3718. # Remove and add to the end.
  3719. if shape in self.selected:
  3720. self.selected.remove(shape)
  3721. self.selected.append(shape)
  3722. def set_unselected(self, shape):
  3723. if shape in self.selected:
  3724. self.selected.remove(shape)
  3725. def snap(self, x, y):
  3726. """
  3727. Adjusts coordinates to snap settings.
  3728. :param x: Input coordinate X
  3729. :param y: Input coordinate Y
  3730. :return: Snapped (x, y)
  3731. """
  3732. snap_x, snap_y = (x, y)
  3733. snap_distance = np.Inf
  3734. # # ## Object (corner?) snap
  3735. # # ## No need for the objects, just the coordinates
  3736. # # ## in the index.
  3737. if self.options["corner_snap"]:
  3738. try:
  3739. nearest_pt, shape = self.storage.nearest((x, y))
  3740. nearest_pt_distance = distance((x, y), nearest_pt)
  3741. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3742. snap_distance = nearest_pt_distance
  3743. snap_x, snap_y = nearest_pt
  3744. except (StopIteration, AssertionError):
  3745. pass
  3746. # # ## Grid snap
  3747. if self.options["grid_snap"]:
  3748. if self.options["global_gridx"] != 0:
  3749. try:
  3750. snap_x_ = round(x / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3751. except TypeError:
  3752. snap_x_ = x
  3753. else:
  3754. snap_x_ = x
  3755. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3756. # and it will use the snap distance from GridX entry
  3757. if self.app.ui.grid_gap_link_cb.isChecked():
  3758. if self.options["global_gridx"] != 0:
  3759. try:
  3760. snap_y_ = round(y / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3761. except TypeError:
  3762. snap_y_ = y
  3763. else:
  3764. snap_y_ = y
  3765. else:
  3766. if self.options["global_gridy"] != 0:
  3767. try:
  3768. snap_y_ = round(y / float(self.options["global_gridy"])) * float(self.options['global_gridy'])
  3769. except TypeError:
  3770. snap_y_ = y
  3771. else:
  3772. snap_y_ = y
  3773. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3774. if nearest_grid_distance < snap_distance:
  3775. snap_x, snap_y = (snap_x_, snap_y_)
  3776. return snap_x, snap_y
  3777. def update_fcgeometry(self, fcgeometry):
  3778. """
  3779. Transfers the geometry tool shape buffer to the selected geometry
  3780. object. The geometry already in the object are removed.
  3781. :param fcgeometry: FlatCAMGeometry
  3782. :return: None
  3783. """
  3784. if self.multigeo_tool:
  3785. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3786. # for shape in self.shape_buffer:
  3787. for shape in self.storage.get_objects():
  3788. new_geo = shape.geo
  3789. # simplify the MultiLineString
  3790. if isinstance(new_geo, MultiLineString):
  3791. new_geo = linemerge(new_geo)
  3792. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(new_geo)
  3793. self.multigeo_tool = None
  3794. fcgeometry.solid_geometry = []
  3795. # for shape in self.shape_buffer:
  3796. for shape in self.storage.get_objects():
  3797. new_geo = shape.geo
  3798. # simplify the MultiLineString
  3799. if isinstance(new_geo, MultiLineString):
  3800. new_geo = linemerge(new_geo)
  3801. fcgeometry.solid_geometry.append(new_geo)
  3802. def update_options(self, obj):
  3803. if self.paint_tooldia:
  3804. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3805. self.paint_tooldia = None
  3806. return True
  3807. else:
  3808. return False
  3809. def union(self):
  3810. """
  3811. Makes union of selected polygons. Original polygons
  3812. are deleted.
  3813. :return: None.
  3814. """
  3815. results = unary_union([t.geo for t in self.get_selected()])
  3816. # Delete originals.
  3817. for_deletion = [s for s in self.get_selected()]
  3818. for shape in for_deletion:
  3819. self.delete_shape(shape)
  3820. # Selected geometry is now gone!
  3821. self.selected = []
  3822. self.add_shape(DrawToolShape(results))
  3823. self.replot()
  3824. def intersection_2(self):
  3825. """
  3826. Makes intersection of selected polygons. Original polygons are deleted.
  3827. :return: None
  3828. """
  3829. geo_shapes = self.get_selected()
  3830. try:
  3831. results = geo_shapes[0].geo
  3832. except Exception as e:
  3833. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3834. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3835. _("A selection of at least 2 geo items is required to do Intersection."))
  3836. self.select_tool('select')
  3837. return
  3838. for shape_el in geo_shapes[1:]:
  3839. results = results.intersection(shape_el.geo)
  3840. # Delete originals.
  3841. for_deletion = [s for s in self.get_selected()]
  3842. for shape_el in for_deletion:
  3843. self.delete_shape(shape_el)
  3844. # Selected geometry is now gone!
  3845. self.selected = []
  3846. self.add_shape(DrawToolShape(results))
  3847. self.replot()
  3848. def intersection(self):
  3849. """
  3850. Makes intersection of selected polygons. Original polygons are deleted.
  3851. :return: None
  3852. """
  3853. geo_shapes = self.get_selected()
  3854. results = []
  3855. intact = []
  3856. try:
  3857. intersector = geo_shapes[0].geo
  3858. except Exception as e:
  3859. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3860. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3861. _("A selection of at least 2 geo items is required to do Intersection."))
  3862. self.select_tool('select')
  3863. return
  3864. for shape_el in geo_shapes[1:]:
  3865. if intersector.intersects(shape_el.geo):
  3866. results.append(intersector.intersection(shape_el.geo))
  3867. else:
  3868. intact.append(shape_el)
  3869. if len(results) != 0:
  3870. # Delete originals.
  3871. for_deletion = [s for s in self.get_selected()]
  3872. for shape_el in for_deletion:
  3873. if shape_el not in intact:
  3874. self.delete_shape(shape_el)
  3875. for geo in results:
  3876. self.add_shape(DrawToolShape(geo))
  3877. # Selected geometry is now gone!
  3878. self.selected = []
  3879. self.replot()
  3880. def subtract(self):
  3881. selected = self.get_selected()
  3882. try:
  3883. tools = selected[1:]
  3884. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3885. target = selected[0].geo
  3886. target = target.buffer(0.0000001)
  3887. result = target.difference(toolgeo)
  3888. for_deletion = [s for s in self.get_selected()]
  3889. for shape in for_deletion:
  3890. self.delete_shape(shape)
  3891. self.add_shape(DrawToolShape(result))
  3892. self.replot()
  3893. except Exception as e:
  3894. log.debug(str(e))
  3895. def subtract_2(self):
  3896. selected = self.get_selected()
  3897. try:
  3898. tools = selected[1:]
  3899. toolgeo = unary_union([shp.geo for shp in tools])
  3900. result = selected[0].geo.difference(toolgeo)
  3901. self.delete_shape(selected[0])
  3902. self.add_shape(DrawToolShape(result))
  3903. self.replot()
  3904. except Exception as e:
  3905. log.debug(str(e))
  3906. def cutpath(self):
  3907. selected = self.get_selected()
  3908. tools = selected[1:]
  3909. toolgeo = unary_union([shp.geo for shp in tools])
  3910. target = selected[0]
  3911. if type(target.geo) == Polygon:
  3912. for ring in poly2rings(target.geo):
  3913. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3914. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3915. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3916. elif type(target.geo) == MultiLineString:
  3917. try:
  3918. for linestring in target.geo:
  3919. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3920. except Exception as e:
  3921. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3922. else:
  3923. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3924. return
  3925. self.delete_shape(target)
  3926. self.replot()
  3927. def buffer(self, buf_distance, join_style):
  3928. selected = self.get_selected()
  3929. if buf_distance < 0:
  3930. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3931. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3932. "'inside' shape"))
  3933. # deselect everything
  3934. self.selected = []
  3935. self.replot()
  3936. return 'fail'
  3937. if len(selected) == 0:
  3938. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3939. _("Nothing selected for buffering."))
  3940. return 'fail'
  3941. if not isinstance(buf_distance, float):
  3942. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3943. _("Invalid distance for buffering."))
  3944. # deselect everything
  3945. self.selected = []
  3946. self.replot()
  3947. return 'fail'
  3948. results = []
  3949. for t in selected:
  3950. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3951. results.append(t.geo.exterior.buffer(
  3952. buf_distance - 1e-10,
  3953. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3954. join_style=join_style)
  3955. )
  3956. else:
  3957. results.append(t.geo.buffer(
  3958. buf_distance - 1e-10,
  3959. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3960. join_style=join_style)
  3961. )
  3962. if not results:
  3963. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3964. _("Failed, the result is empty. Choose a different buffer value."))
  3965. # deselect everything
  3966. self.selected = []
  3967. self.replot()
  3968. return 'fail'
  3969. for sha in results:
  3970. self.add_shape(DrawToolShape(sha))
  3971. self.replot()
  3972. self.app.inform.emit('[success] %s' %
  3973. _("Full buffer geometry created."))
  3974. def buffer_int(self, buf_distance, join_style):
  3975. selected = self.get_selected()
  3976. if buf_distance < 0:
  3977. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Negative buffer value is not accepted."))
  3978. # deselect everything
  3979. self.selected = []
  3980. self.replot()
  3981. return 'fail'
  3982. if len(selected) == 0:
  3983. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for buffering."))
  3984. return 'fail'
  3985. if not isinstance(buf_distance, float):
  3986. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Invalid distance for buffering."))
  3987. # deselect everything
  3988. self.selected = []
  3989. self.replot()
  3990. return 'fail'
  3991. results = []
  3992. for t in selected:
  3993. if isinstance(t.geo, LinearRing):
  3994. t.geo = Polygon(t.geo)
  3995. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3996. results.append(t.geo.buffer(
  3997. -buf_distance + 1e-10,
  3998. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3999. join_style=join_style)
  4000. )
  4001. if not results:
  4002. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4003. _("Failed, the result is empty. Choose a smaller buffer value."))
  4004. # deselect everything
  4005. self.selected = []
  4006. self.replot()
  4007. return 'fail'
  4008. for sha in results:
  4009. self.add_shape(DrawToolShape(sha))
  4010. self.replot()
  4011. self.app.inform.emit('[success] %s' % _("Interior buffer geometry created."))
  4012. def buffer_ext(self, buf_distance, join_style):
  4013. selected = self.get_selected()
  4014. if buf_distance < 0:
  4015. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4016. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  4017. "'inside' shape"))
  4018. # deselect everything
  4019. self.selected = []
  4020. self.replot()
  4021. return
  4022. if len(selected) == 0:
  4023. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4024. _("Nothing selected for buffering."))
  4025. return
  4026. if not isinstance(buf_distance, float):
  4027. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4028. _("Invalid distance for buffering."))
  4029. # deselect everything
  4030. self.selected = []
  4031. self.replot()
  4032. return
  4033. results = []
  4034. for t in selected:
  4035. if isinstance(t.geo, LinearRing):
  4036. t.geo = Polygon(t.geo)
  4037. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  4038. results.append(t.geo.buffer(
  4039. buf_distance,
  4040. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  4041. join_style=join_style)
  4042. )
  4043. if not results:
  4044. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4045. _("Failed, the result is empty. Choose a different buffer value."))
  4046. # deselect everything
  4047. self.selected = []
  4048. self.replot()
  4049. return
  4050. for sha in results:
  4051. self.add_shape(DrawToolShape(sha))
  4052. self.replot()
  4053. self.app.inform.emit('[success] %s' % _("Exterior buffer geometry created."))
  4054. def paint(self, tooldia, overlap, margin, connect, contour, method):
  4055. if overlap >= 100:
  4056. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4057. _("Could not do Paint. Overlap value has to be less than 100%%."))
  4058. return
  4059. self.paint_tooldia = tooldia
  4060. selected = self.get_selected()
  4061. if len(selected) == 0:
  4062. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for painting."))
  4063. return
  4064. for param in [tooldia, overlap, margin]:
  4065. if not isinstance(param, float):
  4066. param_name = [k for k, v in locals().items() if v is param][0]
  4067. self.app.inform.emit('[WARNING] %s: %s' % (_("Invalid value for"), str(param)))
  4068. results = []
  4069. def recurse(geometry, reset=True):
  4070. """
  4071. Creates a list of non-iterable linear geometry objects.
  4072. Results are placed in self.flat_geometry
  4073. :param geometry: Shapely type or list or list of list of such.
  4074. :param reset: Clears the contents of self.flat_geometry.
  4075. """
  4076. if geometry is None:
  4077. return
  4078. if reset:
  4079. self.flat_geo = []
  4080. # If iterable, expand recursively.
  4081. try:
  4082. for geo_el in geometry:
  4083. if geo_el is not None:
  4084. recurse(geometry=geo_el, reset=False)
  4085. # Not iterable, do the actual indexing and add.
  4086. except TypeError:
  4087. self.flat_geo.append(geometry)
  4088. return self.flat_geo
  4089. for geo in selected:
  4090. local_results = []
  4091. for geo_obj in recurse(geo.geo):
  4092. try:
  4093. if type(geo_obj) == Polygon:
  4094. poly_buf = geo_obj.buffer(-margin)
  4095. else:
  4096. poly_buf = Polygon(geo_obj).buffer(-margin)
  4097. if method == _("Seed"):
  4098. cp = Geometry.clear_polygon2(self, polygon_to_clear=poly_buf, tooldia=tooldia,
  4099. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4100. overlap=overlap, contour=contour, connect=connect)
  4101. elif method == _("Lines"):
  4102. cp = Geometry.clear_polygon3(self, polygon=poly_buf, tooldia=tooldia,
  4103. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4104. overlap=overlap, contour=contour, connect=connect)
  4105. else:
  4106. cp = Geometry.clear_polygon(self, polygon=poly_buf, tooldia=tooldia,
  4107. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4108. overlap=overlap, contour=contour, connect=connect)
  4109. if cp is not None:
  4110. local_results += list(cp.get_objects())
  4111. except Exception as e:
  4112. log.debug("Could not Paint the polygons. %s" % str(e))
  4113. self.app.inform.emit(
  4114. '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  4115. "Or a different method of Paint"), str(e))
  4116. )
  4117. return
  4118. # add the result to the results list
  4119. results.append(cascaded_union(local_results))
  4120. # This is a dirty patch:
  4121. for r in results:
  4122. self.add_shape(DrawToolShape(r))
  4123. self.app.inform.emit('[success] %s' % _("Paint done."))
  4124. self.replot()
  4125. def flatten(self, geometry, orient_val=1, reset=True, pathonly=False):
  4126. """
  4127. Creates a list of non-iterable linear geometry objects.
  4128. Polygons are expanded into its exterior and interiors if specified.
  4129. Results are placed in self.flat_geometry
  4130. :param geometry: Shapely type or list or list of list of such.
  4131. :param orient_val: will orient the exterior coordinates CW if 1 and CCW for else (whatever else means ...)
  4132. https://shapely.readthedocs.io/en/stable/manual.html#polygons
  4133. :param reset: Clears the contents of self.flat_geometry.
  4134. :param pathonly: Expands polygons into linear elements.
  4135. """
  4136. if reset:
  4137. self.flat_geo = []
  4138. # ## If iterable, expand recursively.
  4139. try:
  4140. for geo in geometry:
  4141. if geo is not None:
  4142. self.flatten(geometry=geo,
  4143. orient_val=orient_val,
  4144. reset=False,
  4145. pathonly=pathonly)
  4146. # ## Not iterable, do the actual indexing and add.
  4147. except TypeError:
  4148. if type(geometry) == Polygon:
  4149. geometry = orient(geometry, orient_val)
  4150. if pathonly and type(geometry) == Polygon:
  4151. self.flat_geo.append(geometry.exterior)
  4152. self.flatten(geometry=geometry.interiors,
  4153. reset=False,
  4154. pathonly=True)
  4155. else:
  4156. self.flat_geo.append(geometry)
  4157. return self.flat_geo
  4158. def distance(pt1, pt2):
  4159. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4160. def mag(vec):
  4161. return np.sqrt(vec[0] ** 2 + vec[1] ** 2)
  4162. def poly2rings(poly):
  4163. return [poly.exterior] + [interior for interior in poly.interiors]
  4164. def get_shapely_list_bounds(geometry_list):
  4165. xmin = np.Inf
  4166. ymin = np.Inf
  4167. xmax = -np.Inf
  4168. ymax = -np.Inf
  4169. for gs in geometry_list:
  4170. try:
  4171. gxmin, gymin, gxmax, gymax = gs.bounds
  4172. xmin = min([xmin, gxmin])
  4173. ymin = min([ymin, gymin])
  4174. xmax = max([xmax, gxmax])
  4175. ymax = max([ymax, gymax])
  4176. except Exception as e:
  4177. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  4178. return [xmin, ymin, xmax, ymax]