FlatCAMGeoEditor.py 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148
  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 is 'X':
  1113. sha.mirror('X', (px, py))
  1114. self.app.inform.emit('[success] %s...' %
  1115. _('Flip on the Y axis done'))
  1116. elif axis is '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 is 'X':
  1148. sha.skew(num, 0, point=(xminimal, yminimal))
  1149. elif axis is '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 is 'X':
  1218. sha.offset((num, 0))
  1219. elif axis is '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,
  2672. "constructor": FCSelect},
  2673. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2674. "constructor": FCArc},
  2675. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2676. "constructor": FCCircle},
  2677. "path": {"button": self.app.ui.geo_add_path_btn,
  2678. "constructor": FCPath},
  2679. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2680. "constructor": FCRectangle},
  2681. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2682. "constructor": FCPolygon},
  2683. "text": {"button": self.app.ui.geo_add_text_btn,
  2684. "constructor": FCText},
  2685. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2686. "constructor": FCBuffer},
  2687. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2688. "constructor": FCPaint},
  2689. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2690. "constructor": FCEraser},
  2691. "move": {"button": self.app.ui.geo_move_btn,
  2692. "constructor": FCMove},
  2693. "transform": {"button": self.app.ui.geo_transform_btn,
  2694. "constructor": FCTransform},
  2695. "copy": {"button": self.app.ui.geo_copy_btn,
  2696. "constructor": FCCopy},
  2697. "explode": {"button": self.app.ui.geo_explode_btn,
  2698. "constructor": FCExplode}
  2699. }
  2700. # # ## Data
  2701. self.active_tool = None
  2702. self.storage = FlatCAMGeoEditor.make_storage()
  2703. self.utility = []
  2704. # VisPy visuals
  2705. self.fcgeometry = None
  2706. if self.app.is_legacy is False:
  2707. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2708. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2709. else:
  2710. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2711. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='shapes_geo_editor')
  2712. self.tool_shape = ShapeCollectionLegacy(obj=self, app=self.app, name='tool_shapes_geo_editor')
  2713. self.app.pool_recreated.connect(self.pool_recreated)
  2714. # Remove from scene
  2715. self.shapes.enabled = False
  2716. self.tool_shape.enabled = False
  2717. # List of selected shapes.
  2718. self.selected = []
  2719. self.flat_geo = []
  2720. self.move_timer = QtCore.QTimer()
  2721. self.move_timer.setSingleShot(True)
  2722. # this var will store the state of the toolbar before starting the editor
  2723. self.toolbar_old_state = False
  2724. self.key = None # Currently pressed key
  2725. self.geo_key_modifiers = None
  2726. self.x = None # Current mouse cursor pos
  2727. self.y = None
  2728. # if we edit a multigeo geometry store here the tool number
  2729. self.multigeo_tool = None
  2730. # Current snapped mouse pos
  2731. self.snap_x = None
  2732. self.snap_y = None
  2733. self.pos = None
  2734. # signal that there is an action active like polygon or path
  2735. self.in_action = False
  2736. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2737. self.launched_from_shortcuts = False
  2738. def make_callback(thetool):
  2739. def f():
  2740. self.on_tool_select(thetool)
  2741. return f
  2742. for tool in self.tools:
  2743. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2744. self.tools[tool]["button"].setCheckable(True) # Checkable
  2745. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2746. self.app.ui.corner_snap_btn.setCheckable(True)
  2747. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2748. self.options = {
  2749. "global_gridx": 0.1,
  2750. "global_gridy": 0.1,
  2751. "global_snap_max": 0.05,
  2752. "grid_snap": True,
  2753. "corner_snap": False,
  2754. "grid_gap_link": True
  2755. }
  2756. self.options.update(self.app.options)
  2757. for option in self.options:
  2758. if option in self.app.options:
  2759. self.options[option] = self.app.options[option]
  2760. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2761. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2762. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2763. self.app.ui.grid_gap_link_cb.setChecked(True)
  2764. self.rtree_index = rtindex.Index()
  2765. def entry2option(option, entry):
  2766. try:
  2767. self.options[option] = float(entry.text())
  2768. except Exception as e:
  2769. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2770. return
  2771. def gridx_changed(goption, gentry):
  2772. entry2option(option=goption, entry=gentry)
  2773. # if the grid link is checked copy the value in the GridX field to GridY
  2774. try:
  2775. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2776. except ValueError:
  2777. return
  2778. units = self.app.defaults['units'].upper()
  2779. if self.app.ui.grid_gap_link_cb.isChecked():
  2780. self.app.ui.grid_gap_y_entry.set_value(val, decimals=self.decimals)
  2781. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2782. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2783. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2784. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2785. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2786. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2787. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2788. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2789. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2790. # if using Paint store here the tool diameter used
  2791. self.paint_tooldia = None
  2792. self.paint_tool = PaintOptionsTool(self.app, self)
  2793. self.transform_tool = TransformEditorTool(self.app, self)
  2794. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2795. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2796. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2797. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2798. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2799. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2800. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2801. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2802. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2803. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2804. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2805. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2806. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2807. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2808. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2809. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2810. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2811. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2812. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2813. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2814. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2815. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2816. self.transform_complete.connect(self.on_transform_complete)
  2817. # Event signals disconnect id holders
  2818. self.mp = None
  2819. self.mm = None
  2820. self.mr = None
  2821. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2822. self.editor_active = False
  2823. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2824. def pool_recreated(self, pool):
  2825. self.shapes.pool = pool
  2826. self.tool_shape.pool = pool
  2827. def on_transform_complete(self):
  2828. self.delete_selected()
  2829. self.replot()
  2830. def set_ui(self):
  2831. # updated units
  2832. self.units = self.app.defaults['units'].upper()
  2833. self.decimals = self.app.decimals
  2834. # Remove anything else in the GUI Selected Tab
  2835. self.app.ui.selected_scroll_area.takeWidget()
  2836. # Put ourselves in the GUI Selected Tab
  2837. self.app.ui.selected_scroll_area.setWidget(self.geo_edit_widget)
  2838. # Switch notebook to Selected page
  2839. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2840. def build_ui(self, first_run=None):
  2841. # try:
  2842. # # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2843. # self.apertures_table.itemChanged.disconnect()
  2844. # except (TypeError, AttributeError):
  2845. # pass
  2846. iterator = QtWidgets.QTreeWidgetItemIterator(self.geo_parent)
  2847. to_delete = []
  2848. while iterator.value():
  2849. item = iterator.value()
  2850. to_delete.append(item)
  2851. iterator += 1
  2852. for it in to_delete:
  2853. self.geo_parent.removeChild(it)
  2854. for elem in self.storage.get_objects():
  2855. geo_type = type(elem.geo)
  2856. el_type = None
  2857. if geo_type is LinearRing:
  2858. el_type = _('Ring')
  2859. elif geo_type is LineString:
  2860. el_type = _('Line')
  2861. elif geo_type is Polygon:
  2862. el_type = _('Polygon')
  2863. elif geo_type is MultiLineString:
  2864. el_type = _('Multi-Line')
  2865. elif geo_type is MultiPolygon:
  2866. el_type = _('Multi-Polygon')
  2867. self.tw.addParentEditable(
  2868. self.geo_parent,
  2869. [
  2870. str(id(elem)),
  2871. '%s' % el_type,
  2872. _("Geo Elem")
  2873. ],
  2874. font=self.geo_font,
  2875. font_items=2,
  2876. # color=QtGui.QColor("#FF0000"),
  2877. editable=True
  2878. )
  2879. self.tw.resize_sig.emit()
  2880. def on_geo_elem_selected(self):
  2881. pass
  2882. def on_tree_selection_change(self):
  2883. self.selected = []
  2884. selected_tree_items = self.tw.selectedItems()
  2885. for sel in selected_tree_items:
  2886. for obj_shape in self.storage.get_objects():
  2887. try:
  2888. if id(obj_shape) == int(sel.text(0)):
  2889. self.selected.append(obj_shape)
  2890. except ValueError:
  2891. pass
  2892. self.replot()
  2893. def activate(self):
  2894. # adjust the status of the menu entries related to the editor
  2895. self.app.ui.menueditedit.setDisabled(True)
  2896. self.app.ui.menueditok.setDisabled(False)
  2897. # adjust the visibility of some of the canvas context menu
  2898. self.app.ui.popmenu_edit.setVisible(False)
  2899. self.app.ui.popmenu_save.setVisible(True)
  2900. self.connect_canvas_event_handlers()
  2901. # initialize working objects
  2902. self.storage = FlatCAMGeoEditor.make_storage()
  2903. self.utility = []
  2904. self.selected = []
  2905. self.shapes.enabled = True
  2906. self.tool_shape.enabled = True
  2907. self.app.app_cursor.enabled = True
  2908. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2909. self.app.ui.corner_snap_btn.setEnabled(True)
  2910. self.app.ui.snap_magnet.setVisible(True)
  2911. self.app.ui.corner_snap_btn.setVisible(True)
  2912. self.app.ui.geo_editor_menu.setDisabled(False)
  2913. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2914. self.app.ui.update_obj_btn.setEnabled(True)
  2915. self.app.ui.g_editor_cmenu.setEnabled(True)
  2916. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2917. self.app.ui.geo_edit_toolbar.setVisible(True)
  2918. self.app.ui.snap_toolbar.setDisabled(False)
  2919. self.app.ui.popmenu_disable.setVisible(False)
  2920. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2921. self.app.ui.popmenu_properties.setVisible(False)
  2922. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2923. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2924. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2925. # for w in sel_tab_widget_list:
  2926. # w.setEnabled(False)
  2927. # Tell the App that the editor is active
  2928. self.editor_active = True
  2929. self.item_selected.connect(self.on_geo_elem_selected)
  2930. # ## GUI Events
  2931. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  2932. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2933. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2934. self.geo_frame.show()
  2935. log.debug("Finished activating the Geometry Editor...")
  2936. def deactivate(self):
  2937. try:
  2938. QtGui.QGuiApplication.restoreOverrideCursor()
  2939. except Exception:
  2940. pass
  2941. # adjust the status of the menu entries related to the editor
  2942. self.app.ui.menueditedit.setDisabled(False)
  2943. self.app.ui.menueditok.setDisabled(True)
  2944. # adjust the visibility of some of the canvas context menu
  2945. self.app.ui.popmenu_edit.setVisible(True)
  2946. self.app.ui.popmenu_save.setVisible(False)
  2947. self.disconnect_canvas_event_handlers()
  2948. self.clear()
  2949. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2950. settings = QSettings("Open Source", "FlatCAM")
  2951. if settings.contains("layout"):
  2952. layout = settings.value('layout', type=str)
  2953. if layout == 'standard':
  2954. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2955. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2956. self.app.ui.corner_snap_btn.setEnabled(False)
  2957. self.app.ui.snap_magnet.setVisible(False)
  2958. self.app.ui.corner_snap_btn.setVisible(False)
  2959. elif layout == 'compact':
  2960. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2961. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2962. self.app.ui.corner_snap_btn.setEnabled(False)
  2963. else:
  2964. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2965. self.app.ui.snap_magnet.setVisible(False)
  2966. self.app.ui.corner_snap_btn.setVisible(False)
  2967. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2968. self.app.ui.corner_snap_btn.setEnabled(False)
  2969. # set the Editor Toolbar visibility to what was before entering in the Editor
  2970. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2971. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2972. # Disable visuals
  2973. self.shapes.enabled = False
  2974. self.tool_shape.enabled = False
  2975. self.app.ui.geo_editor_menu.setDisabled(True)
  2976. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2977. self.app.ui.update_obj_btn.setEnabled(False)
  2978. self.app.ui.g_editor_cmenu.setEnabled(False)
  2979. self.app.ui.e_editor_cmenu.setEnabled(False)
  2980. # Tell the app that the editor is no longer active
  2981. self.editor_active = False
  2982. self.app.ui.popmenu_disable.setVisible(True)
  2983. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2984. self.app.ui.popmenu_properties.setVisible(True)
  2985. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2986. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2987. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2988. try:
  2989. self.item_selected.disconnect()
  2990. except (AttributeError, TypeError):
  2991. pass
  2992. try:
  2993. # ## GUI Events
  2994. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  2995. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2996. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2997. except (AttributeError, TypeError):
  2998. pass
  2999. # try:
  3000. # # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  3001. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  3002. # for w in sel_tab_widget_list:
  3003. # w.setEnabled(True)
  3004. # except Exception as e:
  3005. # log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  3006. # Show original geometry
  3007. if self.fcgeometry:
  3008. self.fcgeometry.visible = True
  3009. # clear the Tree
  3010. self.tw.clear()
  3011. self.geo_parent = self.tw.invisibleRootItem()
  3012. # hide the UI
  3013. self.geo_frame.hide()
  3014. log.debug("Finished deactivating the Geometry Editor...")
  3015. def connect_canvas_event_handlers(self):
  3016. # Canvas events
  3017. # first connect to new, then disconnect the old handlers
  3018. # don't ask why but if there is nothing connected I've seen issues
  3019. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  3020. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  3021. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_geo_click_release)
  3022. if self.app.is_legacy is False:
  3023. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  3024. # but those from FlatCAMGeoEditor
  3025. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  3026. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  3027. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  3028. self.app.plotcanvas.graph_event_disconnect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  3029. else:
  3030. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  3031. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  3032. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  3033. self.app.plotcanvas.graph_event_disconnect(self.app.mdc)
  3034. # self.app.collection.view.clicked.disconnect()
  3035. self.app.ui.popmenu_copy.triggered.disconnect()
  3036. self.app.ui.popmenu_delete.triggered.disconnect()
  3037. self.app.ui.popmenu_move.triggered.disconnect()
  3038. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  3039. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  3040. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  3041. # Geometry Editor
  3042. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  3043. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  3044. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  3045. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  3046. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  3047. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  3048. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  3049. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  3050. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  3051. self.app.ui.draw_union.triggered.connect(self.union)
  3052. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  3053. self.app.ui.draw_substract.triggered.connect(self.subtract)
  3054. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  3055. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  3056. self.app.ui.draw_move.triggered.connect(self.on_move)
  3057. def disconnect_canvas_event_handlers(self):
  3058. # we restore the key and mouse control to FlatCAMApp method
  3059. # first connect to new, then disconnect the old handlers
  3060. # don't ask why but if there is nothing connected I've seen issues
  3061. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  3062. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  3063. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  3064. self.app.on_mouse_click_release_over_plot)
  3065. self.app.mdc = self.app.plotcanvas.graph_event_connect('mouse_double_click',
  3066. self.app.on_mouse_double_click_over_plot)
  3067. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  3068. if self.app.is_legacy is False:
  3069. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  3070. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  3071. self.canvas.graph_event_disconnect('mouse_release', self.on_geo_click_release)
  3072. else:
  3073. self.canvas.graph_event_disconnect(self.mp)
  3074. self.canvas.graph_event_disconnect(self.mm)
  3075. self.canvas.graph_event_disconnect(self.mr)
  3076. try:
  3077. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  3078. except (TypeError, AttributeError):
  3079. pass
  3080. try:
  3081. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  3082. except (TypeError, AttributeError):
  3083. pass
  3084. try:
  3085. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  3086. except (TypeError, AttributeError):
  3087. pass
  3088. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_command)
  3089. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  3090. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  3091. # Geometry Editor
  3092. try:
  3093. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  3094. except (TypeError, AttributeError):
  3095. pass
  3096. try:
  3097. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  3098. except (TypeError, AttributeError):
  3099. pass
  3100. try:
  3101. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  3102. except (TypeError, AttributeError):
  3103. pass
  3104. try:
  3105. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  3106. except (TypeError, AttributeError):
  3107. pass
  3108. try:
  3109. self.app.ui.draw_circle.triggered.disconnect()
  3110. except (TypeError, AttributeError):
  3111. pass
  3112. try:
  3113. self.app.ui.draw_poly.triggered.disconnect()
  3114. except (TypeError, AttributeError):
  3115. pass
  3116. try:
  3117. self.app.ui.draw_arc.triggered.disconnect()
  3118. except (TypeError, AttributeError):
  3119. pass
  3120. try:
  3121. self.app.ui.draw_text.triggered.disconnect()
  3122. except (TypeError, AttributeError):
  3123. pass
  3124. try:
  3125. self.app.ui.draw_buffer.triggered.disconnect()
  3126. except (TypeError, AttributeError):
  3127. pass
  3128. try:
  3129. self.app.ui.draw_paint.triggered.disconnect()
  3130. except (TypeError, AttributeError):
  3131. pass
  3132. try:
  3133. self.app.ui.draw_eraser.triggered.disconnect()
  3134. except (TypeError, AttributeError):
  3135. pass
  3136. try:
  3137. self.app.ui.draw_union.triggered.disconnect(self.union)
  3138. except (TypeError, AttributeError):
  3139. pass
  3140. try:
  3141. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  3142. except (TypeError, AttributeError):
  3143. pass
  3144. try:
  3145. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  3146. except (TypeError, AttributeError):
  3147. pass
  3148. try:
  3149. self.app.ui.draw_transform.triggered.disconnect()
  3150. except (TypeError, AttributeError):
  3151. pass
  3152. try:
  3153. self.app.jump_signal.disconnect()
  3154. except (TypeError, AttributeError):
  3155. pass
  3156. def add_shape(self, shape):
  3157. """
  3158. Adds a shape to the shape storage.
  3159. :param shape: Shape to be added.
  3160. :type shape: DrawToolShape
  3161. :return: None
  3162. """
  3163. if shape is None:
  3164. return
  3165. # List of DrawToolShape?
  3166. if isinstance(shape, list):
  3167. for subshape in shape:
  3168. self.add_shape(subshape)
  3169. return
  3170. assert isinstance(shape, DrawToolShape), "Expected a DrawToolShape, got %s" % type(shape)
  3171. assert shape.geo is not None, "Shape object has empty geometry (None)"
  3172. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  3173. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  3174. if isinstance(shape, DrawToolUtilityShape):
  3175. self.utility.append(shape)
  3176. else:
  3177. self.storage.insert(shape) # TODO: Check performance
  3178. self.build_ui()
  3179. def delete_utility_geometry(self):
  3180. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3181. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3182. for_deletion = [shape for shape in self.utility]
  3183. for shape in for_deletion:
  3184. self.delete_shape(shape)
  3185. self.tool_shape.clear(update=True)
  3186. self.tool_shape.redraw()
  3187. def toolbar_tool_toggle(self, key):
  3188. self.options[key] = self.sender().isChecked()
  3189. return 1 if self.options[key] == True else 0
  3190. def clear(self):
  3191. self.active_tool = None
  3192. # self.shape_buffer = []
  3193. self.selected = []
  3194. self.shapes.clear(update=True)
  3195. self.tool_shape.clear(update=True)
  3196. # self.storage = FlatCAMGeoEditor.make_storage()
  3197. self.replot()
  3198. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  3199. """
  3200. Imports the geometry from the given FlatCAM Geometry object
  3201. into the editor.
  3202. :param fcgeometry: FlatCAMGeometry
  3203. :param multigeo_tool: a tool for the case of multigeo
  3204. :return: None
  3205. """
  3206. assert isinstance(fcgeometry, Geometry), \
  3207. "Expected a Geometry, got %s" % type(fcgeometry)
  3208. self.deactivate()
  3209. self.activate()
  3210. self.set_ui()
  3211. # Hide original geometry
  3212. self.fcgeometry = fcgeometry
  3213. fcgeometry.visible = False
  3214. # Set selection tolerance
  3215. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3216. self.select_tool("select")
  3217. if self.app.defaults['geometry_spindledir'] == 'CW':
  3218. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3219. milling_type = 1 # CCW motion = climb milling (spindle is rotating CW)
  3220. else:
  3221. milling_type = -1 # CW motion = conventional milling (spindle is rotating CW)
  3222. else:
  3223. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3224. milling_type = -1 # CCW motion = climb milling (spindle is rotating CCW)
  3225. else:
  3226. milling_type = 1 # CW motion = conventional milling (spindle is rotating CCW)
  3227. # Link shapes into editor.
  3228. if multigeo_tool:
  3229. self.multigeo_tool = multigeo_tool
  3230. geo_to_edit = self.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'],
  3231. orient_val=milling_type)
  3232. self.app.inform.emit(
  3233. '[WARNING_NOTCL] %s: %s %s: %s' % (
  3234. _("Editing MultiGeo Geometry, tool"),
  3235. str(self.multigeo_tool),
  3236. _("with diameter"),
  3237. str(fcgeometry.tools[self.multigeo_tool]['tooldia'])
  3238. )
  3239. )
  3240. else:
  3241. geo_to_edit = self.flatten(geometry=fcgeometry.solid_geometry, orient_val=milling_type)
  3242. for shape in geo_to_edit:
  3243. if shape is not None: # TODO: Make flatten never create a None
  3244. if type(shape) == Polygon:
  3245. self.add_shape(DrawToolShape(shape.exterior))
  3246. for inter in shape.interiors:
  3247. self.add_shape(DrawToolShape(inter))
  3248. else:
  3249. self.add_shape(DrawToolShape(shape))
  3250. self.replot()
  3251. # updated units
  3252. self.units = self.app.defaults['units'].upper()
  3253. self.decimals = self.app.decimals
  3254. # start with GRID toolbar activated
  3255. if self.app.ui.grid_snap_btn.isChecked() is False:
  3256. self.app.ui.grid_snap_btn.trigger()
  3257. self.app.on_grid_snap_triggered(state=True)
  3258. def on_buffer_tool(self):
  3259. buff_tool = BufferSelectionTool(self.app, self)
  3260. buff_tool.run()
  3261. def on_paint_tool(self):
  3262. paint_tool = PaintOptionsTool(self.app, self)
  3263. paint_tool.run()
  3264. def on_tool_select(self, tool):
  3265. """
  3266. Behavior of the toolbar. Tool initialization.
  3267. :rtype : None
  3268. """
  3269. self.app.log.debug("on_tool_select('%s')" % tool)
  3270. # This is to make the group behave as radio group
  3271. if tool in self.tools:
  3272. if self.tools[tool]["button"].isChecked():
  3273. self.app.log.debug("%s is checked." % tool)
  3274. for t in self.tools:
  3275. if t != tool:
  3276. self.tools[t]["button"].setChecked(False)
  3277. self.active_tool = self.tools[tool]["constructor"](self)
  3278. else:
  3279. self.app.log.debug("%s is NOT checked." % tool)
  3280. for t in self.tools:
  3281. self.tools[t]["button"].setChecked(False)
  3282. self.select_tool('select')
  3283. self.active_tool = FCSelect(self)
  3284. def draw_tool_path(self):
  3285. self.select_tool('path')
  3286. return
  3287. def draw_tool_rectangle(self):
  3288. self.select_tool('rectangle')
  3289. return
  3290. def on_grid_toggled(self):
  3291. self.toolbar_tool_toggle("grid_snap")
  3292. # make sure that the cursor shape is enabled/disabled, too
  3293. if self.options['grid_snap'] is True:
  3294. self.app.app_cursor.enabled = True
  3295. else:
  3296. self.app.app_cursor.enabled = False
  3297. def on_canvas_click(self, event):
  3298. """
  3299. event.x and .y have canvas coordinates
  3300. event.xdaya and .ydata have plot coordinates
  3301. :param event: Event object dispatched by Matplotlib
  3302. :return: None
  3303. """
  3304. if self.app.is_legacy is False:
  3305. event_pos = event.pos
  3306. else:
  3307. event_pos = (event.xdata, event.ydata)
  3308. self.pos = self.canvas.translate_coords(event_pos)
  3309. if self.app.grid_status():
  3310. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  3311. else:
  3312. self.pos = (self.pos[0], self.pos[1])
  3313. if event.button == 1:
  3314. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3315. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3316. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3317. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3318. if modifiers == QtCore.Qt.ShiftModifier:
  3319. self.app.clipboard.setText(
  3320. self.app.defaults["global_point_clipboard_format"] %
  3321. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  3322. )
  3323. return
  3324. # Selection with left mouse button
  3325. if self.active_tool is not None and event.button == 1:
  3326. # Dispatch event to active_tool
  3327. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3328. # If it is a shape generating tool
  3329. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3330. self.on_shape_complete()
  3331. if isinstance(self.active_tool, FCText):
  3332. self.select_tool("select")
  3333. else:
  3334. self.select_tool(self.active_tool.name)
  3335. if isinstance(self.active_tool, FCSelect):
  3336. # self.app.log.debug("Replotting after click.")
  3337. self.replot()
  3338. else:
  3339. self.app.log.debug("No active tool to respond to click!")
  3340. def on_canvas_move(self, event):
  3341. """
  3342. Called on 'mouse_move' event
  3343. event.pos have canvas screen coordinates
  3344. :param event: Event object dispatched by VisPy SceneCavas
  3345. :return: None
  3346. """
  3347. if self.app.is_legacy is False:
  3348. event_pos = event.pos
  3349. event_is_dragging = event.is_dragging
  3350. right_button = 2
  3351. else:
  3352. event_pos = (event.xdata, event.ydata)
  3353. event_is_dragging = self.app.plotcanvas.is_dragging
  3354. right_button = 3
  3355. pos = self.canvas.translate_coords(event_pos)
  3356. event.xdata, event.ydata = pos[0], pos[1]
  3357. self.x = event.xdata
  3358. self.y = event.ydata
  3359. self.app.ui.popMenu.mouse_is_panning = False
  3360. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3361. if event.button == right_button:
  3362. if event_is_dragging:
  3363. self.app.ui.popMenu.mouse_is_panning = True
  3364. # return
  3365. else:
  3366. self.app.ui.popMenu.mouse_is_panning = False
  3367. if self.active_tool is None:
  3368. return
  3369. try:
  3370. x = float(event.xdata)
  3371. y = float(event.ydata)
  3372. except TypeError:
  3373. return
  3374. # ### Snap coordinates ###
  3375. if self.app.grid_status():
  3376. x, y = self.snap(x, y)
  3377. # Update cursor
  3378. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3379. edge_width=self.app.defaults["global_cursor_width"],
  3380. size=self.app.defaults["global_cursor_size"])
  3381. self.snap_x = x
  3382. self.snap_y = y
  3383. self.app.mouse = [x, y]
  3384. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3385. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3386. "<b>Y</b>: %.4f" % (x, y))
  3387. if self.pos is None:
  3388. self.pos = (0, 0)
  3389. dx = x - self.pos[0]
  3390. dy = y - self.pos[1]
  3391. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3392. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3393. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3394. if event.button == 1 and event_is_dragging and isinstance(self.active_tool, FCEraser):
  3395. pass
  3396. else:
  3397. self.update_utility_geometry(data=(x, y))
  3398. # ### Selection area on canvas section ###
  3399. dx = pos[0] - self.pos[0]
  3400. if event_is_dragging and event.button == 1:
  3401. self.app.delete_selection_shape()
  3402. if dx < 0:
  3403. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3404. color=self.app.defaults["global_alt_sel_line"],
  3405. face_color=self.app.defaults['global_alt_sel_fill'])
  3406. self.app.selection_type = False
  3407. else:
  3408. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3409. self.app.selection_type = True
  3410. else:
  3411. self.app.selection_type = None
  3412. def update_utility_geometry(self, data):
  3413. # ### Utility geometry (animated) ###
  3414. geo = self.active_tool.utility_geometry(data=data)
  3415. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3416. # Remove any previous utility shape
  3417. self.tool_shape.clear(update=True)
  3418. self.draw_utility_geometry(geo=geo)
  3419. def on_geo_click_release(self, event):
  3420. if self.app.is_legacy is False:
  3421. event_pos = event.pos
  3422. event_is_dragging = event.is_dragging
  3423. right_button = 2
  3424. else:
  3425. event_pos = (event.xdata, event.ydata)
  3426. event_is_dragging = self.app.plotcanvas.is_dragging
  3427. right_button = 3
  3428. pos_canvas = self.canvas.translate_coords(event_pos)
  3429. if self.app.grid_status() == True:
  3430. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3431. else:
  3432. pos = (pos_canvas[0], pos_canvas[1])
  3433. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3434. # canvas menu
  3435. try:
  3436. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3437. # selection and then select a type of selection ("enclosing" or "touching")
  3438. if event.button == 1: # left click
  3439. if self.app.selection_type is not None:
  3440. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3441. self.app.selection_type = None
  3442. elif isinstance(self.active_tool, FCSelect):
  3443. # Dispatch event to active_tool
  3444. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3445. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3446. # self.app.inform.emit(msg)
  3447. self.replot()
  3448. elif event.button == right_button: # right click
  3449. if self.app.ui.popMenu.mouse_is_panning is False:
  3450. if self.in_action is False:
  3451. try:
  3452. QtGui.QGuiApplication.restoreOverrideCursor()
  3453. except Exception:
  3454. pass
  3455. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3456. self.active_tool.complete = True
  3457. self.in_action = False
  3458. self.delete_utility_geometry()
  3459. self.app.inform.emit('[success] %s' % _("Done."))
  3460. self.select_tool('select')
  3461. else:
  3462. self.app.cursor = QtGui.QCursor()
  3463. self.app.populate_cmenu_grids()
  3464. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3465. else:
  3466. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3467. # right mouse click will finish the action
  3468. if isinstance(self.active_tool, FCShapeTool):
  3469. self.active_tool.click(self.snap(self.x, self.y))
  3470. self.active_tool.make()
  3471. if self.active_tool.complete:
  3472. self.on_shape_complete()
  3473. self.app.inform.emit('[success] %s' % _("Done."))
  3474. self.select_tool(self.active_tool.name)
  3475. except Exception as e:
  3476. log.warning("FLatCAMGeoEditor.on_geo_click_release() --> Error: %s" % str(e))
  3477. return
  3478. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3479. """
  3480. :param start_pos: mouse position when the selection LMB click was done
  3481. :param end_pos: mouse position when the left mouse button is released
  3482. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3483. :return:
  3484. """
  3485. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3486. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3487. if key_modifier == QtCore.Qt.ShiftModifier:
  3488. mod_key = 'Shift'
  3489. elif key_modifier == QtCore.Qt.ControlModifier:
  3490. mod_key = 'Control'
  3491. else:
  3492. mod_key = None
  3493. self.app.delete_selection_shape()
  3494. sel_objects_list = []
  3495. for obj in self.storage.get_objects():
  3496. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3497. poly_selection.intersects(obj.geo)):
  3498. sel_objects_list.append(obj)
  3499. if mod_key == self.app.defaults["global_mselect_key"]:
  3500. for obj in sel_objects_list:
  3501. if obj in self.selected:
  3502. self.selected.remove(obj)
  3503. else:
  3504. # add the object to the selected shapes
  3505. self.selected.append(obj)
  3506. else:
  3507. self.selected = []
  3508. self.selected = sel_objects_list
  3509. # if selection is done on canvas update the Tree in Selected Tab with the selection
  3510. try:
  3511. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  3512. except (AttributeError, TypeError):
  3513. pass
  3514. self.tw.selectionModel().clearSelection()
  3515. for sel_shape in self.selected:
  3516. iterator = QtWidgets.QTreeWidgetItemIterator(self.tw)
  3517. while iterator.value():
  3518. item = iterator.value()
  3519. try:
  3520. if int(item.text(1)) == id(sel_shape):
  3521. item.setSelected(True)
  3522. except ValueError:
  3523. pass
  3524. iterator += 1
  3525. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  3526. self.replot()
  3527. def draw_utility_geometry(self, geo):
  3528. # Add the new utility shape
  3529. try:
  3530. # this case is for the Font Parse
  3531. for el in list(geo.geo):
  3532. if type(el) == MultiPolygon:
  3533. for poly in el:
  3534. self.tool_shape.add(
  3535. shape=poly,
  3536. color=(self.app.defaults["global_draw_color"] + '80'),
  3537. update=False,
  3538. layer=0,
  3539. tolerance=None
  3540. )
  3541. elif type(el) == MultiLineString:
  3542. for linestring in el:
  3543. self.tool_shape.add(
  3544. shape=linestring,
  3545. color=(self.app.defaults["global_draw_color"] + '80'),
  3546. update=False,
  3547. layer=0,
  3548. tolerance=None
  3549. )
  3550. else:
  3551. self.tool_shape.add(
  3552. shape=el,
  3553. color=(self.app.defaults["global_draw_color"] + '80'),
  3554. update=False,
  3555. layer=0,
  3556. tolerance=None
  3557. )
  3558. except TypeError:
  3559. self.tool_shape.add(
  3560. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3561. update=False, layer=0, tolerance=None)
  3562. self.tool_shape.redraw()
  3563. def on_delete_btn(self):
  3564. self.delete_selected()
  3565. self.replot()
  3566. def delete_selected(self):
  3567. tempref = [s for s in self.selected]
  3568. for shape in tempref:
  3569. self.delete_shape(shape)
  3570. self.selected = []
  3571. self.build_ui()
  3572. def delete_shape(self, shape):
  3573. if shape in self.utility:
  3574. self.utility.remove(shape)
  3575. return
  3576. self.storage.remove(shape)
  3577. if shape in self.selected:
  3578. self.selected.remove(shape) # TODO: Check performance
  3579. def on_move(self):
  3580. # if not self.selected:
  3581. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3582. # return
  3583. self.app.ui.geo_move_btn.setChecked(True)
  3584. self.on_tool_select('move')
  3585. def on_move_click(self):
  3586. self.on_move()
  3587. self.active_tool.set_origin(self.snap(self.x, self.y))
  3588. def on_copy_click(self):
  3589. if not self.selected:
  3590. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3591. _("Copy cancelled. No shape selected."))
  3592. return
  3593. self.app.ui.geo_copy_btn.setChecked(True)
  3594. self.app.geo_editor.on_tool_select('copy')
  3595. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3596. self.app.geo_editor.x, self.app.geo_editor.y))
  3597. self.app.inform.emit(_("Click on target point."))
  3598. def on_corner_snap(self):
  3599. self.app.ui.corner_snap_btn.trigger()
  3600. def get_selected(self):
  3601. """
  3602. Returns list of shapes that are selected in the editor.
  3603. :return: List of shapes.
  3604. """
  3605. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3606. return self.selected
  3607. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3608. """
  3609. Plots a geometric object or list of objects without rendering. Plotted objects
  3610. are returned as a list. This allows for efficient/animated rendering.
  3611. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3612. :param color: Shape color
  3613. :param linewidth: Width of lines in # of pixels.
  3614. :return: List of plotted elements.
  3615. """
  3616. plot_elements = []
  3617. if geometry is None:
  3618. geometry = self.active_tool.geometry
  3619. try:
  3620. for geo in geometry:
  3621. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3622. # Non-iterable
  3623. except TypeError:
  3624. # DrawToolShape
  3625. if isinstance(geometry, DrawToolShape):
  3626. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3627. # Polygon: Descend into exterior and each interior.
  3628. if type(geometry) == Polygon:
  3629. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3630. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3631. if type(geometry) == LineString or type(geometry) == LinearRing:
  3632. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3633. tolerance=self.fcgeometry.drawing_tolerance,
  3634. linewidth=linewidth))
  3635. if type(geometry) == Point:
  3636. pass
  3637. return plot_elements
  3638. def plot_all(self):
  3639. """
  3640. Plots all shapes in the editor.
  3641. :return: None
  3642. :rtype: None
  3643. """
  3644. # self.app.log.debug("plot_all()")
  3645. self.shapes.clear(update=True)
  3646. for shape in self.storage.get_objects():
  3647. if shape.geo is None: # TODO: This shouldn't have happened
  3648. continue
  3649. if shape in self.selected:
  3650. self.plot_shape(geometry=shape.geo,
  3651. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3652. linewidth=2)
  3653. continue
  3654. self.plot_shape(geometry=shape.geo,
  3655. color=self.app.defaults['global_draw_color'] + "FF")
  3656. for shape in self.utility:
  3657. self.plot_shape(geometry=shape.geo,
  3658. linewidth=1)
  3659. continue
  3660. self.shapes.redraw()
  3661. def replot(self):
  3662. self.plot_all()
  3663. def on_shape_complete(self):
  3664. self.app.log.debug("on_shape_complete()")
  3665. geom = []
  3666. try:
  3667. for shape in self.active_tool.geometry:
  3668. geom.append(shape.geo)
  3669. except TypeError:
  3670. geom = self.active_tool.geometry.geo
  3671. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3672. # reverse the geometry coordinates direction to allow creation of Gcode for climb milling
  3673. try:
  3674. pl = []
  3675. for p in geom:
  3676. if p is not None:
  3677. if isinstance(p, Polygon):
  3678. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3679. elif isinstance(p, LinearRing):
  3680. pl.append(Polygon(p.coords[::-1]))
  3681. elif isinstance(p, LineString):
  3682. pl.append(LineString(p.coords[::-1]))
  3683. try:
  3684. geom = MultiPolygon(pl)
  3685. except TypeError:
  3686. # this may happen if the geom elements are made out of LineStrings because you can't create a
  3687. # MultiPolygon out of LineStrings
  3688. pass
  3689. except TypeError:
  3690. if isinstance(geom, Polygon) and geom is not None:
  3691. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3692. elif isinstance(geom, LinearRing) and geom is not None:
  3693. geom = Polygon(geom.coords[::-1])
  3694. elif isinstance(geom, LineString) and geom is not None:
  3695. geom = LineString(geom.coords[::-1])
  3696. else:
  3697. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> Unexpected Geometry %s" %
  3698. type(geom))
  3699. except Exception as e:
  3700. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> %s" % str(e))
  3701. return 'fail'
  3702. shape_list = []
  3703. try:
  3704. for geo in geom:
  3705. shape_list.append(DrawToolShape(geo))
  3706. except TypeError:
  3707. shape_list.append(DrawToolShape(geom))
  3708. # Add shape
  3709. self.add_shape(shape_list)
  3710. # Remove any utility shapes
  3711. self.delete_utility_geometry()
  3712. self.tool_shape.clear(update=True)
  3713. # Replot and reset tool.
  3714. self.replot()
  3715. # self.active_tool = type(self.active_tool)(self)
  3716. @staticmethod
  3717. def make_storage():
  3718. # Shape storage.
  3719. storage = FlatCAMRTreeStorage()
  3720. storage.get_points = DrawToolShape.get_pts
  3721. return storage
  3722. def select_tool(self, toolname):
  3723. """
  3724. Selects a drawing tool. Impacts the object and GUI.
  3725. :param toolname: Name of the tool.
  3726. :return: None
  3727. """
  3728. self.tools[toolname]["button"].setChecked(True)
  3729. self.on_tool_select(toolname)
  3730. def set_selected(self, shape):
  3731. # Remove and add to the end.
  3732. if shape in self.selected:
  3733. self.selected.remove(shape)
  3734. self.selected.append(shape)
  3735. def set_unselected(self, shape):
  3736. if shape in self.selected:
  3737. self.selected.remove(shape)
  3738. def snap(self, x, y):
  3739. """
  3740. Adjusts coordinates to snap settings.
  3741. :param x: Input coordinate X
  3742. :param y: Input coordinate Y
  3743. :return: Snapped (x, y)
  3744. """
  3745. snap_x, snap_y = (x, y)
  3746. snap_distance = np.Inf
  3747. # # ## Object (corner?) snap
  3748. # # ## No need for the objects, just the coordinates
  3749. # # ## in the index.
  3750. if self.options["corner_snap"]:
  3751. try:
  3752. nearest_pt, shape = self.storage.nearest((x, y))
  3753. nearest_pt_distance = distance((x, y), nearest_pt)
  3754. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3755. snap_distance = nearest_pt_distance
  3756. snap_x, snap_y = nearest_pt
  3757. except (StopIteration, AssertionError):
  3758. pass
  3759. # # ## Grid snap
  3760. if self.options["grid_snap"]:
  3761. if self.options["global_gridx"] != 0:
  3762. try:
  3763. snap_x_ = round(x / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3764. except TypeError:
  3765. snap_x_ = x
  3766. else:
  3767. snap_x_ = x
  3768. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3769. # and it will use the snap distance from GridX entry
  3770. if self.app.ui.grid_gap_link_cb.isChecked():
  3771. if self.options["global_gridx"] != 0:
  3772. try:
  3773. snap_y_ = round(y / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3774. except TypeError:
  3775. snap_y_ = y
  3776. else:
  3777. snap_y_ = y
  3778. else:
  3779. if self.options["global_gridy"] != 0:
  3780. try:
  3781. snap_y_ = round(y / float(self.options["global_gridy"])) * float(self.options['global_gridy'])
  3782. except TypeError:
  3783. snap_y_ = y
  3784. else:
  3785. snap_y_ = y
  3786. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3787. if nearest_grid_distance < snap_distance:
  3788. snap_x, snap_y = (snap_x_, snap_y_)
  3789. return snap_x, snap_y
  3790. def update_fcgeometry(self, fcgeometry):
  3791. """
  3792. Transfers the geometry tool shape buffer to the selected geometry
  3793. object. The geometry already in the object are removed.
  3794. :param fcgeometry: FlatCAMGeometry
  3795. :return: None
  3796. """
  3797. if self.multigeo_tool:
  3798. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3799. # for shape in self.shape_buffer:
  3800. for shape in self.storage.get_objects():
  3801. new_geo = shape.geo
  3802. # simplify the MultiLineString
  3803. if isinstance(new_geo, MultiLineString):
  3804. new_geo = linemerge(new_geo)
  3805. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(new_geo)
  3806. self.multigeo_tool = None
  3807. fcgeometry.solid_geometry = []
  3808. # for shape in self.shape_buffer:
  3809. for shape in self.storage.get_objects():
  3810. new_geo = shape.geo
  3811. # simplify the MultiLineString
  3812. if isinstance(new_geo, MultiLineString):
  3813. new_geo = linemerge(new_geo)
  3814. fcgeometry.solid_geometry.append(new_geo)
  3815. def update_options(self, obj):
  3816. if self.paint_tooldia:
  3817. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3818. self.paint_tooldia = None
  3819. return True
  3820. else:
  3821. return False
  3822. def union(self):
  3823. """
  3824. Makes union of selected polygons. Original polygons
  3825. are deleted.
  3826. :return: None.
  3827. """
  3828. results = unary_union([t.geo for t in self.get_selected()])
  3829. # Delete originals.
  3830. for_deletion = [s for s in self.get_selected()]
  3831. for shape in for_deletion:
  3832. self.delete_shape(shape)
  3833. # Selected geometry is now gone!
  3834. self.selected = []
  3835. self.add_shape(DrawToolShape(results))
  3836. self.replot()
  3837. def intersection_2(self):
  3838. """
  3839. Makes intersection of selected polygons. Original polygons are deleted.
  3840. :return: None
  3841. """
  3842. geo_shapes = self.get_selected()
  3843. try:
  3844. results = geo_shapes[0].geo
  3845. except Exception as e:
  3846. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3847. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3848. _("A selection of at least 2 geo items is required to do Intersection."))
  3849. self.select_tool('select')
  3850. return
  3851. for shape_el in geo_shapes[1:]:
  3852. results = results.intersection(shape_el.geo)
  3853. # Delete originals.
  3854. for_deletion = [s for s in self.get_selected()]
  3855. for shape_el in for_deletion:
  3856. self.delete_shape(shape_el)
  3857. # Selected geometry is now gone!
  3858. self.selected = []
  3859. self.add_shape(DrawToolShape(results))
  3860. self.replot()
  3861. def intersection(self):
  3862. """
  3863. Makes intersection of selected polygons. Original polygons are deleted.
  3864. :return: None
  3865. """
  3866. geo_shapes = self.get_selected()
  3867. results = []
  3868. intact = []
  3869. try:
  3870. intersector = geo_shapes[0].geo
  3871. except Exception as e:
  3872. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3873. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3874. _("A selection of at least 2 geo items is required to do Intersection."))
  3875. self.select_tool('select')
  3876. return
  3877. for shape_el in geo_shapes[1:]:
  3878. if intersector.intersects(shape_el.geo):
  3879. results.append(intersector.intersection(shape_el.geo))
  3880. else:
  3881. intact.append(shape_el)
  3882. if len(results) != 0:
  3883. # Delete originals.
  3884. for_deletion = [s for s in self.get_selected()]
  3885. for shape_el in for_deletion:
  3886. if shape_el not in intact:
  3887. self.delete_shape(shape_el)
  3888. for geo in results:
  3889. self.add_shape(DrawToolShape(geo))
  3890. # Selected geometry is now gone!
  3891. self.selected = []
  3892. self.replot()
  3893. def subtract(self):
  3894. selected = self.get_selected()
  3895. try:
  3896. tools = selected[1:]
  3897. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3898. target = selected[0].geo
  3899. target = target.buffer(0.0000001)
  3900. result = target.difference(toolgeo)
  3901. for_deletion = [s for s in self.get_selected()]
  3902. for shape in for_deletion:
  3903. self.delete_shape(shape)
  3904. self.add_shape(DrawToolShape(result))
  3905. self.replot()
  3906. except Exception as e:
  3907. log.debug(str(e))
  3908. def subtract_2(self):
  3909. selected = self.get_selected()
  3910. try:
  3911. tools = selected[1:]
  3912. toolgeo = unary_union([shp.geo for shp in tools])
  3913. result = selected[0].geo.difference(toolgeo)
  3914. self.delete_shape(selected[0])
  3915. self.add_shape(DrawToolShape(result))
  3916. self.replot()
  3917. except Exception as e:
  3918. log.debug(str(e))
  3919. def cutpath(self):
  3920. selected = self.get_selected()
  3921. tools = selected[1:]
  3922. toolgeo = unary_union([shp.geo for shp in tools])
  3923. target = selected[0]
  3924. if type(target.geo) == Polygon:
  3925. for ring in poly2rings(target.geo):
  3926. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3927. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3928. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3929. elif type(target.geo) == MultiLineString:
  3930. try:
  3931. for linestring in target.geo:
  3932. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3933. except Exception as e:
  3934. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3935. else:
  3936. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3937. return
  3938. self.delete_shape(target)
  3939. self.replot()
  3940. def buffer(self, buf_distance, join_style):
  3941. selected = self.get_selected()
  3942. if buf_distance < 0:
  3943. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3944. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3945. "'inside' shape"))
  3946. # deselect everything
  3947. self.selected = []
  3948. self.replot()
  3949. return 'fail'
  3950. if len(selected) == 0:
  3951. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3952. _("Nothing selected for buffering."))
  3953. return 'fail'
  3954. if not isinstance(buf_distance, float):
  3955. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3956. _("Invalid distance for buffering."))
  3957. # deselect everything
  3958. self.selected = []
  3959. self.replot()
  3960. return 'fail'
  3961. results = []
  3962. for t in selected:
  3963. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3964. results.append(t.geo.exterior.buffer(
  3965. buf_distance - 1e-10,
  3966. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3967. join_style=join_style)
  3968. )
  3969. else:
  3970. results.append(t.geo.buffer(
  3971. buf_distance - 1e-10,
  3972. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3973. join_style=join_style)
  3974. )
  3975. if not results:
  3976. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3977. _("Failed, the result is empty. Choose a different buffer value."))
  3978. # deselect everything
  3979. self.selected = []
  3980. self.replot()
  3981. return 'fail'
  3982. for sha in results:
  3983. self.add_shape(DrawToolShape(sha))
  3984. self.replot()
  3985. self.app.inform.emit('[success] %s' %
  3986. _("Full buffer geometry created."))
  3987. def buffer_int(self, buf_distance, join_style):
  3988. selected = self.get_selected()
  3989. if buf_distance < 0:
  3990. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Negative buffer value is not accepted."))
  3991. # deselect everything
  3992. self.selected = []
  3993. self.replot()
  3994. return 'fail'
  3995. if len(selected) == 0:
  3996. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for buffering."))
  3997. return 'fail'
  3998. if not isinstance(buf_distance, float):
  3999. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Invalid distance for buffering."))
  4000. # deselect everything
  4001. self.selected = []
  4002. self.replot()
  4003. return 'fail'
  4004. results = []
  4005. for t in selected:
  4006. if isinstance(t.geo, LinearRing):
  4007. t.geo = Polygon(t.geo)
  4008. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  4009. results.append(t.geo.buffer(
  4010. -buf_distance + 1e-10,
  4011. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  4012. join_style=join_style)
  4013. )
  4014. if not results:
  4015. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4016. _("Failed, the result is empty. Choose a smaller buffer value."))
  4017. # deselect everything
  4018. self.selected = []
  4019. self.replot()
  4020. return 'fail'
  4021. for sha in results:
  4022. self.add_shape(DrawToolShape(sha))
  4023. self.replot()
  4024. self.app.inform.emit('[success] %s' % _("Interior buffer geometry created."))
  4025. def buffer_ext(self, buf_distance, join_style):
  4026. selected = self.get_selected()
  4027. if buf_distance < 0:
  4028. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4029. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  4030. "'inside' shape"))
  4031. # deselect everything
  4032. self.selected = []
  4033. self.replot()
  4034. return
  4035. if len(selected) == 0:
  4036. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4037. _("Nothing selected for buffering."))
  4038. return
  4039. if not isinstance(buf_distance, float):
  4040. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4041. _("Invalid distance for buffering."))
  4042. # deselect everything
  4043. self.selected = []
  4044. self.replot()
  4045. return
  4046. results = []
  4047. for t in selected:
  4048. if isinstance(t.geo, LinearRing):
  4049. t.geo = Polygon(t.geo)
  4050. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  4051. results.append(t.geo.buffer(
  4052. buf_distance,
  4053. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  4054. join_style=join_style)
  4055. )
  4056. if not results:
  4057. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4058. _("Failed, the result is empty. Choose a different buffer value."))
  4059. # deselect everything
  4060. self.selected = []
  4061. self.replot()
  4062. return
  4063. for sha in results:
  4064. self.add_shape(DrawToolShape(sha))
  4065. self.replot()
  4066. self.app.inform.emit('[success] %s' % _("Exterior buffer geometry created."))
  4067. def paint(self, tooldia, overlap, margin, connect, contour, method):
  4068. if overlap >= 100:
  4069. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4070. _("Could not do Paint. Overlap value has to be less than 100%%."))
  4071. return
  4072. self.paint_tooldia = tooldia
  4073. selected = self.get_selected()
  4074. if len(selected) == 0:
  4075. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for painting."))
  4076. return
  4077. for param in [tooldia, overlap, margin]:
  4078. if not isinstance(param, float):
  4079. param_name = [k for k, v in locals().items() if v is param][0]
  4080. self.app.inform.emit('[WARNING] %s: %s' % (_("Invalid value for"), str(param)))
  4081. results = []
  4082. def recurse(geometry, reset=True):
  4083. """
  4084. Creates a list of non-iterable linear geometry objects.
  4085. Results are placed in self.flat_geometry
  4086. :param geometry: Shapely type or list or list of list of such.
  4087. :param reset: Clears the contents of self.flat_geometry.
  4088. """
  4089. if geometry is None:
  4090. return
  4091. if reset:
  4092. self.flat_geo = []
  4093. # If iterable, expand recursively.
  4094. try:
  4095. for geo_el in geometry:
  4096. if geo_el is not None:
  4097. recurse(geometry=geo_el, reset=False)
  4098. # Not iterable, do the actual indexing and add.
  4099. except TypeError:
  4100. self.flat_geo.append(geometry)
  4101. return self.flat_geo
  4102. for geo in selected:
  4103. local_results = []
  4104. for geo_obj in recurse(geo.geo):
  4105. try:
  4106. if type(geo_obj) == Polygon:
  4107. poly_buf = geo_obj.buffer(-margin)
  4108. else:
  4109. poly_buf = Polygon(geo_obj).buffer(-margin)
  4110. if method == _("Seed"):
  4111. cp = Geometry.clear_polygon2(self, polygon_to_clear=poly_buf, tooldia=tooldia,
  4112. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4113. overlap=overlap, contour=contour, connect=connect)
  4114. elif method == _("Lines"):
  4115. cp = Geometry.clear_polygon3(self, polygon=poly_buf, tooldia=tooldia,
  4116. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4117. overlap=overlap, contour=contour, connect=connect)
  4118. else:
  4119. cp = Geometry.clear_polygon(self, polygon=poly_buf, tooldia=tooldia,
  4120. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4121. overlap=overlap, contour=contour, connect=connect)
  4122. if cp is not None:
  4123. local_results += list(cp.get_objects())
  4124. except Exception as e:
  4125. log.debug("Could not Paint the polygons. %s" % str(e))
  4126. self.app.inform.emit(
  4127. '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  4128. "Or a different method of Paint"), str(e))
  4129. )
  4130. return
  4131. # add the result to the results list
  4132. results.append(cascaded_union(local_results))
  4133. # This is a dirty patch:
  4134. for r in results:
  4135. self.add_shape(DrawToolShape(r))
  4136. self.app.inform.emit('[success] %s' % _("Paint done."))
  4137. self.replot()
  4138. def flatten(self, geometry, orient_val=1, reset=True, pathonly=False):
  4139. """
  4140. Creates a list of non-iterable linear geometry objects.
  4141. Polygons are expanded into its exterior and interiors if specified.
  4142. Results are placed in self.flat_geometry
  4143. :param geometry: Shapely type or list or list of list of such.
  4144. :param orient_val: will orient the exterior coordinates CW if 1 and CCW for else (whatever else means ...)
  4145. https://shapely.readthedocs.io/en/stable/manual.html#polygons
  4146. :param reset: Clears the contents of self.flat_geometry.
  4147. :param pathonly: Expands polygons into linear elements.
  4148. """
  4149. if reset:
  4150. self.flat_geo = []
  4151. # ## If iterable, expand recursively.
  4152. try:
  4153. for geo in geometry:
  4154. if geo is not None:
  4155. self.flatten(geometry=geo,
  4156. orient_val=orient_val,
  4157. reset=False,
  4158. pathonly=pathonly)
  4159. # ## Not iterable, do the actual indexing and add.
  4160. except TypeError:
  4161. if type(geometry) == Polygon:
  4162. geometry = orient(geometry, orient_val)
  4163. if pathonly and type(geometry) == Polygon:
  4164. self.flat_geo.append(geometry.exterior)
  4165. self.flatten(geometry=geometry.interiors,
  4166. reset=False,
  4167. pathonly=True)
  4168. else:
  4169. self.flat_geo.append(geometry)
  4170. return self.flat_geo
  4171. def distance(pt1, pt2):
  4172. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4173. def mag(vec):
  4174. return np.sqrt(vec[0] ** 2 + vec[1] ** 2)
  4175. def poly2rings(poly):
  4176. return [poly.exterior] + [interior for interior in poly.interiors]
  4177. def get_shapely_list_bounds(geometry_list):
  4178. xmin = np.Inf
  4179. ymin = np.Inf
  4180. xmax = -np.Inf
  4181. ymax = -np.Inf
  4182. for gs in geometry_list:
  4183. try:
  4184. gxmin, gymin, gxmax, gymax = gs.bounds
  4185. xmin = min([xmin, gxmin])
  4186. ymin = min([ymin, gymin])
  4187. xmax = max([xmax, gxmax])
  4188. ymax = max([ymax, gymax])
  4189. except Exception as e:
  4190. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  4191. return [xmin, ymin, xmax, ymax]