FlatCAMGeoEditor.py 191 KB

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