FlatCAMGeoEditor.py 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911
  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
  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
  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 Rate'))
  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. self.app.progress.emit(20)
  1066. for sel_sha in shape_list:
  1067. px = 0.5 * (xminimal + xmaximal)
  1068. py = 0.5 * (yminimal + ymaximal)
  1069. sel_sha.rotate(-num, point=(px, py))
  1070. self.draw_app.replot()
  1071. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1072. # self.draw_app.transform_complete.emit()
  1073. self.app.inform.emit('[success] %s' %
  1074. _("Done. Rotate completed."))
  1075. self.app.progress.emit(100)
  1076. except Exception as e:
  1077. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation action was not executed"), str(e)))
  1078. return
  1079. def on_flip(self, axis):
  1080. shape_list = self.draw_app.selected
  1081. xminlist = []
  1082. yminlist = []
  1083. xmaxlist = []
  1084. ymaxlist = []
  1085. if not shape_list:
  1086. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1087. _("No shape selected. Please Select a shape to flip!"))
  1088. return
  1089. else:
  1090. with self.app.proc_container.new(_("Applying Flip")):
  1091. try:
  1092. # get mirroring coords from the point entry
  1093. if self.flip_ref_cb.isChecked():
  1094. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1095. # get mirroring coords from the center of an all-enclosing bounding box
  1096. else:
  1097. # first get a bounding box to fit all
  1098. for sha in shape_list:
  1099. xmin, ymin, xmax, ymax = sha.bounds()
  1100. xminlist.append(xmin)
  1101. yminlist.append(ymin)
  1102. xmaxlist.append(xmax)
  1103. ymaxlist.append(ymax)
  1104. # get the minimum x,y and maximum x,y for all objects selected
  1105. xminimal = min(xminlist)
  1106. yminimal = min(yminlist)
  1107. xmaximal = max(xmaxlist)
  1108. ymaximal = max(ymaxlist)
  1109. px = 0.5 * (xminimal + xmaximal)
  1110. py = 0.5 * (yminimal + ymaximal)
  1111. self.app.progress.emit(20)
  1112. # execute mirroring
  1113. for sha in shape_list:
  1114. if axis is 'X':
  1115. sha.mirror('X', (px, py))
  1116. self.app.inform.emit('[success] %s...' %
  1117. _('Flip on the Y axis done'))
  1118. elif axis is 'Y':
  1119. sha.mirror('Y', (px, py))
  1120. self.app.inform.emit('[success] %s' %
  1121. _('Flip on the X axis done'))
  1122. self.draw_app.replot()
  1123. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1124. #
  1125. # self.draw_app.transform_complete.emit()
  1126. self.app.progress.emit(100)
  1127. except Exception as e:
  1128. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed"), str(e)))
  1129. return
  1130. def on_skew(self, axis, num):
  1131. shape_list = self.draw_app.selected
  1132. xminlist = []
  1133. yminlist = []
  1134. if not shape_list:
  1135. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1136. _("No shape selected. Please Select a shape to shear/skew!"))
  1137. return
  1138. else:
  1139. with self.app.proc_container.new(_("Applying Skew")):
  1140. try:
  1141. # first get a bounding box to fit all
  1142. for sha in shape_list:
  1143. xmin, ymin, xmax, ymax = sha.bounds()
  1144. xminlist.append(xmin)
  1145. yminlist.append(ymin)
  1146. # get the minimum x,y and maximum x,y for all objects selected
  1147. xminimal = min(xminlist)
  1148. yminimal = min(yminlist)
  1149. self.app.progress.emit(20)
  1150. for sha in shape_list:
  1151. if axis is 'X':
  1152. sha.skew(num, 0, point=(xminimal, yminimal))
  1153. elif axis is 'Y':
  1154. sha.skew(0, num, point=(xminimal, yminimal))
  1155. self.draw_app.replot()
  1156. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1157. #
  1158. # self.draw_app.transform_complete.emit()
  1159. if axis == 'X':
  1160. self.app.inform.emit('[success] %s...' %
  1161. _('Skew on the X axis done'))
  1162. else:
  1163. self.app.inform.emit('[success] %s...' %
  1164. _('Skew on the Y axis done'))
  1165. self.app.progress.emit(100)
  1166. except Exception as e:
  1167. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Skew action was not executed"), str(e)))
  1168. return
  1169. def on_scale(self, axis, xfactor, yfactor, point=None):
  1170. shape_list = self.draw_app.selected
  1171. xminlist = []
  1172. yminlist = []
  1173. xmaxlist = []
  1174. ymaxlist = []
  1175. if not shape_list:
  1176. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1177. _("No shape selected. Please Select a shape to scale!"))
  1178. return
  1179. else:
  1180. with self.app.proc_container.new(_("Applying Scale")):
  1181. try:
  1182. # first get a bounding box to fit all
  1183. for sha in shape_list:
  1184. xmin, ymin, xmax, ymax = sha.bounds()
  1185. xminlist.append(xmin)
  1186. yminlist.append(ymin)
  1187. xmaxlist.append(xmax)
  1188. ymaxlist.append(ymax)
  1189. # get the minimum x,y and maximum x,y for all objects selected
  1190. xminimal = min(xminlist)
  1191. yminimal = min(yminlist)
  1192. xmaximal = max(xmaxlist)
  1193. ymaximal = max(ymaxlist)
  1194. self.app.progress.emit(20)
  1195. if point is None:
  1196. px = 0.5 * (xminimal + xmaximal)
  1197. py = 0.5 * (yminimal + ymaximal)
  1198. else:
  1199. px = 0
  1200. py = 0
  1201. for sha in shape_list:
  1202. sha.scale(xfactor, yfactor, point=(px, py))
  1203. self.draw_app.replot()
  1204. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1205. #
  1206. # self.draw_app.transform_complete.emit()
  1207. if str(axis) == 'X':
  1208. self.app.inform.emit('[success] %s...' %
  1209. _('Scale on the X axis done'))
  1210. else:
  1211. self.app.inform.emit('[success] %s...' %
  1212. _('Scale on the Y axis done'))
  1213. self.app.progress.emit(100)
  1214. except Exception as e:
  1215. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Scale action was not executed"), str(e)))
  1216. return
  1217. def on_offset(self, axis, num):
  1218. shape_list = self.draw_app.selected
  1219. xminlist = []
  1220. yminlist = []
  1221. if not shape_list:
  1222. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1223. _("No shape selected. Please Select a shape to offset!"))
  1224. return
  1225. else:
  1226. with self.app.proc_container.new(_("Applying Offset")):
  1227. try:
  1228. self.app.progress.emit(20)
  1229. for sha in shape_list:
  1230. if axis is 'X':
  1231. sha.offset((num, 0))
  1232. elif axis is 'Y':
  1233. sha.offset((0, num))
  1234. self.draw_app.replot()
  1235. if axis == 'X':
  1236. self.app.inform.emit('[success] %s...' %
  1237. _('Offset on the X axis done'))
  1238. else:
  1239. self.app.inform.emit('[success] %s...' %
  1240. _('Offset on the Y axis done'))
  1241. self.app.progress.emit(100)
  1242. except Exception as e:
  1243. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Offset action was not executed"), str(e)))
  1244. return
  1245. def on_rotate_key(self):
  1246. val_box = FCInputDialog(title=_("Rotate ..."),
  1247. text='%s:' % _('Enter an Angle Value (degrees)'),
  1248. min=-359.9999, max=360.0000, decimals=self.decimals,
  1249. init_val=float(self.app.defaults['tools_transform_rotate']))
  1250. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/rotate.png'))
  1251. val, ok = val_box.get_value()
  1252. if ok:
  1253. self.on_rotate(val=val)
  1254. self.app.inform.emit('[success] %s...' %
  1255. _("Geometry shape rotate done"))
  1256. return
  1257. else:
  1258. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1259. _("Geometry shape rotate cancelled"))
  1260. def on_offx_key(self):
  1261. units = self.app.defaults['units'].lower()
  1262. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1263. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1264. min=-9999.9999, max=10000.0000, decimals=self.decimals,
  1265. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1266. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsetx32.png'))
  1267. val, ok = val_box.get_value()
  1268. if ok:
  1269. self.on_offx(val=val)
  1270. self.app.inform.emit('[success] %s' %
  1271. _("Geometry shape offset on X axis done"))
  1272. return
  1273. else:
  1274. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1275. _("Geometry shape offset X cancelled"))
  1276. def on_offy_key(self):
  1277. units = self.app.defaults['units'].lower()
  1278. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1279. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1280. min=-9999.9999, max=10000.0000, decimals=self.decimals,
  1281. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1282. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsety32.png'))
  1283. val, ok = val_box.get_value()
  1284. if ok:
  1285. self.on_offx(val=val)
  1286. self.app.inform.emit('[success] %s...' %
  1287. _("Geometry shape offset on Y axis done"))
  1288. return
  1289. else:
  1290. self.app.inform.emit('[success] %s...' %
  1291. _("Geometry shape offset on Y axis canceled"))
  1292. def on_skewx_key(self):
  1293. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1294. text='%s:' % _('Enter an Angle Value (degrees)'),
  1295. min=-359.9999, max=360.0000, decimals=self.decimals,
  1296. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1297. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewX.png'))
  1298. val, ok = val_box.get_value()
  1299. if ok:
  1300. self.on_skewx(val=val)
  1301. self.app.inform.emit('[success] %s...' %
  1302. _("Geometry shape skew on X axis done"))
  1303. return
  1304. else:
  1305. self.app.inform.emit('[success] %s...' %
  1306. _("Geometry shape skew on X axis canceled"))
  1307. def on_skewy_key(self):
  1308. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1309. text='%s:' % _('Enter an Angle Value (degrees)'),
  1310. min=-359.9999, max=360.0000, decimals=self.decimals,
  1311. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1312. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewY.png'))
  1313. val, ok = val_box.get_value()
  1314. if ok:
  1315. self.on_skewx(val=val)
  1316. self.app.inform.emit('[success] %s...' %
  1317. _("Geometry shape skew on Y axis done"))
  1318. return
  1319. else:
  1320. self.app.inform.emit('[success] %s...' %
  1321. _("Geometry shape skew on Y axis canceled"))
  1322. class DrawToolShape(object):
  1323. """
  1324. Encapsulates "shapes" under a common class.
  1325. """
  1326. tolerance = None
  1327. @staticmethod
  1328. def get_pts(o):
  1329. """
  1330. Returns a list of all points in the object, where
  1331. the object can be a Polygon, Not a polygon, or a list
  1332. of such. Search is done recursively.
  1333. :param: geometric object
  1334. :return: List of points
  1335. :rtype: list
  1336. """
  1337. pts = []
  1338. # Iterable: descend into each item.
  1339. try:
  1340. for subo in o:
  1341. pts += DrawToolShape.get_pts(subo)
  1342. # Non-iterable
  1343. except TypeError:
  1344. if o is not None:
  1345. # DrawToolShape: descend into .geo.
  1346. if isinstance(o, DrawToolShape):
  1347. pts += DrawToolShape.get_pts(o.geo)
  1348. # Descend into .exerior and .interiors
  1349. elif type(o) == Polygon:
  1350. pts += DrawToolShape.get_pts(o.exterior)
  1351. for i in o.interiors:
  1352. pts += DrawToolShape.get_pts(i)
  1353. elif type(o) == MultiLineString:
  1354. for line in o:
  1355. pts += DrawToolShape.get_pts(line)
  1356. # Has .coords: list them.
  1357. else:
  1358. if DrawToolShape.tolerance is not None:
  1359. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1360. else:
  1361. pts += list(o.coords)
  1362. else:
  1363. return
  1364. return pts
  1365. def __init__(self, geo=[]):
  1366. # Shapely type or list of such
  1367. self.geo = geo
  1368. self.utility = False
  1369. def get_all_points(self):
  1370. return DrawToolShape.get_pts(self)
  1371. def bounds(self):
  1372. """
  1373. Returns coordinates of rectangular bounds
  1374. of geometry: (xmin, ymin, xmax, ymax).
  1375. """
  1376. # fixed issue of getting bounds only for one level lists of objects
  1377. # now it can get bounds for nested lists of objects
  1378. def bounds_rec(shape_el):
  1379. if type(shape_el) is list:
  1380. minx = np.Inf
  1381. miny = np.Inf
  1382. maxx = -np.Inf
  1383. maxy = -np.Inf
  1384. for k in shape_el:
  1385. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1386. minx = min(minx, minx_)
  1387. miny = min(miny, miny_)
  1388. maxx = max(maxx, maxx_)
  1389. maxy = max(maxy, maxy_)
  1390. return minx, miny, maxx, maxy
  1391. else:
  1392. # it's a Shapely object, return it's bounds
  1393. return shape_el.bounds
  1394. bounds_coords = bounds_rec(self.geo)
  1395. return bounds_coords
  1396. def mirror(self, axis, point):
  1397. """
  1398. Mirrors the shape around a specified axis passing through
  1399. the given point.
  1400. :param axis: "X" or "Y" indicates around which axis to mirror.
  1401. :type axis: str
  1402. :param point: [x, y] point belonging to the mirror axis.
  1403. :type point: list
  1404. :return: None
  1405. """
  1406. px, py = point
  1407. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1408. def mirror_geom(shape_el):
  1409. if type(shape_el) is list:
  1410. new_obj = []
  1411. for g in shape_el:
  1412. new_obj.append(mirror_geom(g))
  1413. return new_obj
  1414. else:
  1415. return affinity.scale(shape_el, xscale, yscale, origin=(px, py))
  1416. try:
  1417. self.geo = mirror_geom(self.geo)
  1418. except AttributeError:
  1419. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1420. def rotate(self, angle, point):
  1421. """
  1422. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1423. Parameters
  1424. ----------
  1425. The angle of rotation are specified in degrees (default). Positive angles are
  1426. counter-clockwise and negative are clockwise rotations.
  1427. The point of origin can be a keyword 'center' for the bounding box
  1428. center (default), 'centroid' for the geometry's centroid, a Point object
  1429. or a coordinate tuple (x0, y0).
  1430. See shapely manual for more information:
  1431. http://toblerity.org/shapely/manual.html#affine-transformations
  1432. """
  1433. px, py = point
  1434. def rotate_geom(shape_el):
  1435. if type(shape_el) is list:
  1436. new_obj = []
  1437. for g in shape_el:
  1438. new_obj.append(rotate_geom(g))
  1439. return new_obj
  1440. else:
  1441. return affinity.rotate(shape_el, angle, origin=(px, py))
  1442. try:
  1443. self.geo = rotate_geom(self.geo)
  1444. except AttributeError:
  1445. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1446. def skew(self, angle_x, angle_y, point):
  1447. """
  1448. Shear/Skew a shape by angles along x and y dimensions.
  1449. Parameters
  1450. ----------
  1451. angle_x, angle_y : float, float
  1452. The shear angle(s) for the x and y axes respectively. These can be
  1453. specified in either degrees (default) or radians by setting
  1454. use_radians=True.
  1455. point: tuple of coordinates (x,y)
  1456. See shapely manual for more information:
  1457. http://toblerity.org/shapely/manual.html#affine-transformations
  1458. """
  1459. px, py = point
  1460. def skew_geom(shape_el):
  1461. if type(shape_el) is list:
  1462. new_obj = []
  1463. for g in shape_el:
  1464. new_obj.append(skew_geom(g))
  1465. return new_obj
  1466. else:
  1467. return affinity.skew(shape_el, angle_x, angle_y, origin=(px, py))
  1468. try:
  1469. self.geo = skew_geom(self.geo)
  1470. except AttributeError:
  1471. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1472. def offset(self, vect):
  1473. """
  1474. Offsets all shapes by a given vector/
  1475. :param vect: (x, y) vector by which to offset the shape geometry
  1476. :type vect: tuple
  1477. :return: None
  1478. :rtype: None
  1479. """
  1480. try:
  1481. dx, dy = vect
  1482. except TypeError:
  1483. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1484. "Probable you entered only one value in the Offset field.")
  1485. return
  1486. def translate_recursion(geom):
  1487. if type(geom) == list:
  1488. geoms = list()
  1489. for local_geom in geom:
  1490. geoms.append(translate_recursion(local_geom))
  1491. return geoms
  1492. else:
  1493. return affinity.translate(geom, xoff=dx, yoff=dy)
  1494. try:
  1495. self.geo = translate_recursion(self.geo)
  1496. except AttributeError:
  1497. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1498. def scale(self, xfactor, yfactor=None, point=None):
  1499. """
  1500. Scales all shape geometry by a given factor.
  1501. :param xfactor: Factor by which to scale the shape's geometry/
  1502. :type xfactor: float
  1503. :param yfactor: Factor by which to scale the shape's geometry/
  1504. :type yfactor: float
  1505. :return: None
  1506. :rtype: None
  1507. """
  1508. try:
  1509. xfactor = float(xfactor)
  1510. except Exception:
  1511. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1512. return
  1513. if yfactor is None:
  1514. yfactor = xfactor
  1515. else:
  1516. try:
  1517. yfactor = float(yfactor)
  1518. except Exception:
  1519. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1520. return
  1521. if point is None:
  1522. px = 0
  1523. py = 0
  1524. else:
  1525. px, py = point
  1526. def scale_recursion(geom):
  1527. if type(geom) == list:
  1528. geoms = list()
  1529. for local_geom in geom:
  1530. geoms.append(scale_recursion(local_geom))
  1531. return geoms
  1532. else:
  1533. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1534. try:
  1535. self.geo = scale_recursion(self.geo)
  1536. except AttributeError:
  1537. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1538. class DrawToolUtilityShape(DrawToolShape):
  1539. """
  1540. Utility shapes are temporary geometry in the editor
  1541. to assist in the creation of shapes. For example it
  1542. will show the outline of a rectangle from the first
  1543. point to the current mouse pointer before the second
  1544. point is clicked and the final geometry is created.
  1545. """
  1546. def __init__(self, geo=[]):
  1547. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1548. self.utility = True
  1549. class DrawTool(object):
  1550. """
  1551. Abstract Class representing a tool in the drawing
  1552. program. Can generate geometry, including temporary
  1553. utility geometry that is updated on user clicks
  1554. and mouse motion.
  1555. """
  1556. def __init__(self, draw_app):
  1557. self.draw_app = draw_app
  1558. self.complete = False
  1559. self.points = []
  1560. self.geometry = None # DrawToolShape or None
  1561. def click(self, point):
  1562. """
  1563. :param point: [x, y] Coordinate pair.
  1564. """
  1565. return ""
  1566. def click_release(self, point):
  1567. """
  1568. :param point: [x, y] Coordinate pair.
  1569. """
  1570. return ""
  1571. def on_key(self, key):
  1572. # Jump to coords
  1573. if key == QtCore.Qt.Key_J or key == 'J':
  1574. self.draw_app.app.on_jump_to()
  1575. return
  1576. def utility_geometry(self, data=None):
  1577. return None
  1578. def bounds(self, obj):
  1579. def bounds_rec(o):
  1580. if type(o) is list:
  1581. minx = np.Inf
  1582. miny = np.Inf
  1583. maxx = -np.Inf
  1584. maxy = -np.Inf
  1585. for k in o:
  1586. try:
  1587. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1588. except Exception as e:
  1589. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1590. return
  1591. minx = min(minx, minx_)
  1592. miny = min(miny, miny_)
  1593. maxx = max(maxx, maxx_)
  1594. maxy = max(maxy, maxy_)
  1595. return minx, miny, maxx, maxy
  1596. else:
  1597. # it's a Shapely object, return it's bounds
  1598. return o.geo.bounds
  1599. bounds_coords = bounds_rec(obj)
  1600. return bounds_coords
  1601. class FCShapeTool(DrawTool):
  1602. """
  1603. Abstract class for tools that create a shape.
  1604. """
  1605. def __init__(self, draw_app):
  1606. DrawTool.__init__(self, draw_app)
  1607. def make(self):
  1608. pass
  1609. class FCCircle(FCShapeTool):
  1610. """
  1611. Resulting type: Polygon
  1612. """
  1613. def __init__(self, draw_app):
  1614. DrawTool.__init__(self, draw_app)
  1615. self.name = 'circle'
  1616. self.draw_app = draw_app
  1617. try:
  1618. QtGui.QGuiApplication.restoreOverrideCursor()
  1619. except Exception:
  1620. pass
  1621. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_circle_geo.png'))
  1622. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1623. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1624. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1625. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1626. def click(self, point):
  1627. self.points.append(point)
  1628. if len(self.points) == 1:
  1629. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1630. return "Click on perimeter to complete ..."
  1631. if len(self.points) == 2:
  1632. self.make()
  1633. return "Done."
  1634. return ""
  1635. def utility_geometry(self, data=None):
  1636. if len(self.points) == 1:
  1637. p1 = self.points[0]
  1638. p2 = data
  1639. radius = np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1640. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1641. return None
  1642. def make(self):
  1643. try:
  1644. QtGui.QGuiApplication.restoreOverrideCursor()
  1645. except Exception:
  1646. pass
  1647. p1 = self.points[0]
  1648. p2 = self.points[1]
  1649. radius = distance(p1, p2)
  1650. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1651. self.complete = True
  1652. self.draw_app.app.jump_signal.disconnect()
  1653. self.draw_app.app.inform.emit('[success] %s' % _("Done. Adding Circle completed."))
  1654. def clean_up(self):
  1655. self.draw_app.selected = list()
  1656. self.draw_app.plot_all()
  1657. try:
  1658. self.draw_app.app.jump_signal.disconnect()
  1659. except (TypeError, AttributeError):
  1660. pass
  1661. class FCArc(FCShapeTool):
  1662. def __init__(self, draw_app):
  1663. DrawTool.__init__(self, draw_app)
  1664. self.name = 'arc'
  1665. self.draw_app = draw_app
  1666. try:
  1667. QtGui.QGuiApplication.restoreOverrideCursor()
  1668. except Exception:
  1669. pass
  1670. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_arc.png'))
  1671. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1672. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1673. # Direction of rotation between point 1 and 2.
  1674. # 'cw' or 'ccw'. Switch direction by hitting the
  1675. # 'o' key.
  1676. self.direction = "cw"
  1677. # Mode
  1678. # C12 = Center, p1, p2
  1679. # 12C = p1, p2, Center
  1680. # 132 = p1, p3, p2
  1681. self.mode = "c12" # Center, p1, p2
  1682. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1683. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1684. def click(self, point):
  1685. self.points.append(point)
  1686. if len(self.points) == 1:
  1687. if self.mode == 'c12':
  1688. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1689. elif self.mode == '132':
  1690. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1691. else:
  1692. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1693. return "Click on 1st point ..."
  1694. if len(self.points) == 2:
  1695. if self.mode == 'c12':
  1696. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1697. elif self.mode == '132':
  1698. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1699. else:
  1700. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1701. return "Click on 2nd point to complete ..."
  1702. if len(self.points) == 3:
  1703. self.make()
  1704. return "Done."
  1705. return ""
  1706. def on_key(self, key):
  1707. if key == 'D' or key == QtCore.Qt.Key_D:
  1708. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1709. return _('Direction: %s') % self.direction.upper()
  1710. # Jump to coords
  1711. if key == QtCore.Qt.Key_J or key == 'J':
  1712. self.draw_app.app.on_jump_to()
  1713. if key == 'M' or key == QtCore.Qt.Key_M:
  1714. # delete the possible points made before this action; we want to start anew
  1715. self.points[:] = []
  1716. # and delete the utility geometry made up until this point
  1717. self.draw_app.delete_utility_geometry()
  1718. if self.mode == 'c12':
  1719. self.mode = '12c'
  1720. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1721. elif self.mode == '12c':
  1722. self.mode = '132'
  1723. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1724. else:
  1725. self.mode = 'c12'
  1726. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1727. def utility_geometry(self, data=None):
  1728. if len(self.points) == 1: # Show the radius
  1729. center = self.points[0]
  1730. p1 = data
  1731. return DrawToolUtilityShape(LineString([center, p1]))
  1732. if len(self.points) == 2: # Show the arc
  1733. if self.mode == 'c12':
  1734. center = self.points[0]
  1735. p1 = self.points[1]
  1736. p2 = data
  1737. radius = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1738. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1739. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1740. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1741. self.direction, self.steps_per_circ)),
  1742. Point(center)])
  1743. elif self.mode == '132':
  1744. p1 = np.array(self.points[0])
  1745. p3 = np.array(self.points[1])
  1746. p2 = np.array(data)
  1747. try:
  1748. center, radius, t = three_point_circle(p1, p2, p3)
  1749. except TypeError:
  1750. return
  1751. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1752. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1753. stopangle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1754. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1755. direction, self.steps_per_circ)),
  1756. Point(center), Point(p1), Point(p3)])
  1757. else: # '12c'
  1758. p1 = np.array(self.points[0])
  1759. p2 = np.array(self.points[1])
  1760. # Midpoint
  1761. a = (p1 + p2) / 2.0
  1762. # Parallel vector
  1763. c = p2 - p1
  1764. # Perpendicular vector
  1765. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1766. b /= numpy_norm(b)
  1767. # Distance
  1768. t = distance(data, a)
  1769. # Which side? Cross product with c.
  1770. # cross(M-A, B-A), where line is AB and M is test point.
  1771. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1772. t *= np.sign(side)
  1773. # Center = a + bt
  1774. center = a + b * t
  1775. radius = numpy_norm(center - p1)
  1776. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1777. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1778. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1779. self.direction, self.steps_per_circ)),
  1780. Point(center)])
  1781. return None
  1782. def make(self):
  1783. if self.mode == 'c12':
  1784. center = self.points[0]
  1785. p1 = self.points[1]
  1786. p2 = self.points[2]
  1787. radius = distance(center, p1)
  1788. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1789. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1790. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1791. self.direction, self.steps_per_circ)))
  1792. elif self.mode == '132':
  1793. p1 = np.array(self.points[0])
  1794. p3 = np.array(self.points[1])
  1795. p2 = np.array(self.points[2])
  1796. center, radius, t = three_point_circle(p1, p2, p3)
  1797. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1798. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1799. stopangle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1800. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1801. direction, self.steps_per_circ)))
  1802. else: # self.mode == '12c'
  1803. p1 = np.array(self.points[0])
  1804. p2 = np.array(self.points[1])
  1805. pc = np.array(self.points[2])
  1806. # Midpoint
  1807. a = (p1 + p2) / 2.0
  1808. # Parallel vector
  1809. c = p2 - p1
  1810. # Perpendicular vector
  1811. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1812. b /= numpy_norm(b)
  1813. # Distance
  1814. t = distance(pc, a)
  1815. # Which side? Cross product with c.
  1816. # cross(M-A, B-A), where line is AB and M is test point.
  1817. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1818. t *= np.sign(side)
  1819. # Center = a + bt
  1820. center = a + b * t
  1821. radius = numpy_norm(center - p1)
  1822. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1823. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1824. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1825. self.direction, self.steps_per_circ)))
  1826. self.complete = True
  1827. self.draw_app.app.jump_signal.disconnect()
  1828. self.draw_app.app.inform.emit('[success] %s' % _("Done. Arc completed."))
  1829. def clean_up(self):
  1830. self.draw_app.selected = list()
  1831. self.draw_app.plot_all()
  1832. try:
  1833. self.draw_app.app.jump_signal.disconnect()
  1834. except (TypeError, AttributeError):
  1835. pass
  1836. class FCRectangle(FCShapeTool):
  1837. """
  1838. Resulting type: Polygon
  1839. """
  1840. def __init__(self, draw_app):
  1841. DrawTool.__init__(self, draw_app)
  1842. self.name = 'rectangle'
  1843. self.draw_app = draw_app
  1844. try:
  1845. QtGui.QGuiApplication.restoreOverrideCursor()
  1846. except Exception:
  1847. pass
  1848. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero.png'))
  1849. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1850. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1851. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1852. def click(self, point):
  1853. self.points.append(point)
  1854. if len(self.points) == 1:
  1855. self.draw_app.app.inform.emit(_("Click on opposite corner to complete ..."))
  1856. return "Click on opposite corner to complete ..."
  1857. if len(self.points) == 2:
  1858. self.make()
  1859. return "Done."
  1860. return ""
  1861. def utility_geometry(self, data=None):
  1862. if len(self.points) == 1:
  1863. p1 = self.points[0]
  1864. p2 = data
  1865. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1866. return None
  1867. def make(self):
  1868. try:
  1869. QtGui.QGuiApplication.restoreOverrideCursor()
  1870. except Exception:
  1871. pass
  1872. p1 = self.points[0]
  1873. p2 = self.points[1]
  1874. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1875. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1876. self.complete = True
  1877. self.draw_app.app.jump_signal.disconnect()
  1878. self.draw_app.app.inform.emit('[success] %s' % _("Done. Rectangle completed."))
  1879. def clean_up(self):
  1880. self.draw_app.selected = list()
  1881. self.draw_app.plot_all()
  1882. try:
  1883. self.draw_app.app.jump_signal.disconnect()
  1884. except (TypeError, AttributeError):
  1885. pass
  1886. class FCPolygon(FCShapeTool):
  1887. """
  1888. Resulting type: Polygon
  1889. """
  1890. def __init__(self, draw_app):
  1891. DrawTool.__init__(self, draw_app)
  1892. self.name = 'polygon'
  1893. self.draw_app = draw_app
  1894. try:
  1895. QtGui.QGuiApplication.restoreOverrideCursor()
  1896. except Exception:
  1897. pass
  1898. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero.png'))
  1899. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1900. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1901. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1902. def click(self, point):
  1903. self.draw_app.in_action = True
  1904. self.points.append(point)
  1905. if len(self.points) > 0:
  1906. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1907. return "Click on next point or hit ENTER to complete ..."
  1908. return ""
  1909. def utility_geometry(self, data=None):
  1910. if len(self.points) == 1:
  1911. temp_points = [x for x in self.points]
  1912. temp_points.append(data)
  1913. return DrawToolUtilityShape(LineString(temp_points))
  1914. if len(self.points) > 1:
  1915. temp_points = [x for x in self.points]
  1916. temp_points.append(data)
  1917. return DrawToolUtilityShape(LinearRing(temp_points))
  1918. return None
  1919. def make(self):
  1920. try:
  1921. QtGui.QGuiApplication.restoreOverrideCursor()
  1922. except Exception:
  1923. pass
  1924. # self.geometry = LinearRing(self.points)
  1925. self.geometry = DrawToolShape(Polygon(self.points))
  1926. self.draw_app.in_action = False
  1927. self.complete = True
  1928. self.draw_app.app.jump_signal.disconnect()
  1929. self.draw_app.app.inform.emit('[success] %s' % _("Done. Polygon completed."))
  1930. def on_key(self, key):
  1931. # Jump to coords
  1932. if key == QtCore.Qt.Key_J or key == 'J':
  1933. self.draw_app.app.on_jump_to()
  1934. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1935. if len(self.points) > 0:
  1936. self.points = self.points[0:-1]
  1937. # Remove any previous utility shape
  1938. self.draw_app.tool_shape.clear(update=False)
  1939. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1940. self.draw_app.draw_utility_geometry(geo=geo)
  1941. return _("Backtracked one point ...")
  1942. def clean_up(self):
  1943. self.draw_app.selected = list()
  1944. self.draw_app.plot_all()
  1945. try:
  1946. self.draw_app.app.jump_signal.disconnect()
  1947. except (TypeError, AttributeError):
  1948. pass
  1949. class FCPath(FCPolygon):
  1950. """
  1951. Resulting type: LineString
  1952. """
  1953. def __init__(self, draw_app):
  1954. FCPolygon.__init__(self, draw_app)
  1955. self.draw_app = draw_app
  1956. try:
  1957. QtGui.QGuiApplication.restoreOverrideCursor()
  1958. except Exception:
  1959. pass
  1960. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path5.png'))
  1961. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1962. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1963. def make(self):
  1964. self.geometry = DrawToolShape(LineString(self.points))
  1965. self.name = 'path'
  1966. try:
  1967. QtGui.QGuiApplication.restoreOverrideCursor()
  1968. except Exception as e:
  1969. pass
  1970. self.draw_app.in_action = False
  1971. self.complete = True
  1972. self.draw_app.app.jump_signal.disconnect()
  1973. self.draw_app.app.inform.emit('[success] %s' % _("Done. Path completed."))
  1974. def utility_geometry(self, data=None):
  1975. if len(self.points) > 0:
  1976. temp_points = [x for x in self.points]
  1977. temp_points.append(data)
  1978. return DrawToolUtilityShape(LineString(temp_points))
  1979. return None
  1980. def on_key(self, key):
  1981. # Jump to coords
  1982. if key == QtCore.Qt.Key_J or key == 'J':
  1983. self.draw_app.app.on_jump_to()
  1984. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1985. if len(self.points) > 0:
  1986. self.points = self.points[0:-1]
  1987. # Remove any previous utility shape
  1988. self.draw_app.tool_shape.clear(update=False)
  1989. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1990. self.draw_app.draw_utility_geometry(geo=geo)
  1991. return _("Backtracked one point ...")
  1992. def clean_up(self):
  1993. self.draw_app.selected = list()
  1994. self.draw_app.plot_all()
  1995. try:
  1996. self.draw_app.app.jump_signal.disconnect()
  1997. except (TypeError, AttributeError):
  1998. pass
  1999. class FCSelect(DrawTool):
  2000. def __init__(self, draw_app):
  2001. DrawTool.__init__(self, draw_app)
  2002. self.name = 'select'
  2003. self.draw_app = draw_app
  2004. try:
  2005. QtGui.QGuiApplication.restoreOverrideCursor()
  2006. except Exception as e:
  2007. pass
  2008. self.storage = self.draw_app.storage
  2009. # self.shape_buffer = self.draw_app.shape_buffer
  2010. # self.selected = self.draw_app.selected
  2011. def click_release(self, point):
  2012. # list where we store the overlapped shapes under our mouse left click position
  2013. over_shape_list = []
  2014. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  2015. for obj_shape in self.storage.get_objects():
  2016. # first method of click selection -> inconvenient
  2017. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  2018. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  2019. # over_shape_list.append(obj_shape)
  2020. # second method of click selection -> slow
  2021. # outside = obj_shape.geo.buffer(0.1)
  2022. # inside = obj_shape.geo.buffer(-0.1)
  2023. # shape_band = outside.difference(inside)
  2024. # if Point(pos).within(shape_band):
  2025. # over_shape_list.append(obj_shape)
  2026. # 3rd method of click selection -> inconvenient
  2027. try:
  2028. _, closest_shape = self.storage.nearest(point)
  2029. except StopIteration:
  2030. return ""
  2031. over_shape_list.append(closest_shape)
  2032. try:
  2033. # if there is no shape under our click then deselect all shapes
  2034. # it will not work for 3rd method of click selection
  2035. if not over_shape_list:
  2036. self.draw_app.selected = []
  2037. FlatCAMGeoEditor.draw_shape_idx = -1
  2038. else:
  2039. # if there are shapes under our click then advance through the list of them, one at the time in a
  2040. # circular way
  2041. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2042. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2043. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2044. if key_modifier == QtCore.Qt.ShiftModifier:
  2045. mod_key = 'Shift'
  2046. elif key_modifier == QtCore.Qt.ControlModifier:
  2047. mod_key = 'Control'
  2048. else:
  2049. mod_key = None
  2050. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  2051. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2052. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2053. if obj_to_add in self.draw_app.selected:
  2054. self.draw_app.selected.remove(obj_to_add)
  2055. else:
  2056. self.draw_app.selected.append(obj_to_add)
  2057. else:
  2058. self.draw_app.selected = []
  2059. self.draw_app.selected.append(obj_to_add)
  2060. except Exception as e:
  2061. log.error("[ERROR] Something went bad. %s" % str(e))
  2062. raise
  2063. return ""
  2064. class FCExplode(FCShapeTool):
  2065. def __init__(self, draw_app):
  2066. FCShapeTool.__init__(self, draw_app)
  2067. self.name = 'explode'
  2068. self.draw_app = draw_app
  2069. try:
  2070. QtGui.QGuiApplication.restoreOverrideCursor()
  2071. except Exception:
  2072. pass
  2073. self.storage = self.draw_app.storage
  2074. self.origin = (0, 0)
  2075. self.destination = None
  2076. self.draw_app.active_tool = self
  2077. if len(self.draw_app.get_selected()) == 0:
  2078. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' % ("No shape selected. Select a shape to explode"))
  2079. else:
  2080. self.make()
  2081. def make(self):
  2082. to_be_deleted_list = list()
  2083. lines = list()
  2084. for shape in self.draw_app.get_selected():
  2085. to_be_deleted_list.append(shape)
  2086. geo = shape.geo
  2087. ext_coords = list(geo.exterior.coords)
  2088. for c in range(len(ext_coords)):
  2089. if c < len(ext_coords) - 1:
  2090. lines.append(LineString([ext_coords[c], ext_coords[c + 1]]))
  2091. for int_geo in geo.interiors:
  2092. int_coords = list(int_geo.coords)
  2093. for c in range(len(int_coords)):
  2094. if c < len(int_coords):
  2095. lines.append(LineString([int_coords[c], int_coords[c + 1]]))
  2096. for shape in to_be_deleted_list:
  2097. self.draw_app.storage.remove(shape)
  2098. if shape in self.draw_app.selected:
  2099. self.draw_app.selected.remove(shape)
  2100. geo_list = list()
  2101. for line in lines:
  2102. geo_list.append(DrawToolShape(line))
  2103. self.geometry = geo_list
  2104. self.draw_app.on_shape_complete()
  2105. self.draw_app.app.inform.emit('[success] %s...' % _("Done. Polygons exploded into lines."))
  2106. def clean_up(self):
  2107. self.draw_app.selected = list()
  2108. self.draw_app.plot_all()
  2109. try:
  2110. self.draw_app.app.jump_signal.disconnect()
  2111. except (TypeError, AttributeError):
  2112. pass
  2113. class FCMove(FCShapeTool):
  2114. def __init__(self, draw_app):
  2115. FCShapeTool.__init__(self, draw_app)
  2116. self.name = 'move'
  2117. self.draw_app = draw_app
  2118. try:
  2119. QtGui.QGuiApplication.restoreOverrideCursor()
  2120. except Exception as e:
  2121. pass
  2122. self.storage = self.draw_app.storage
  2123. self.origin = None
  2124. self.destination = None
  2125. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2126. self.selection_shape = self.selection_bbox()
  2127. if len(self.draw_app.get_selected()) == 0:
  2128. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' %
  2129. _("MOVE: No shape selected. Select a shape to move"))
  2130. return
  2131. else:
  2132. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2133. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2134. def set_origin(self, origin):
  2135. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2136. self.origin = origin
  2137. def click(self, point):
  2138. if len(self.draw_app.get_selected()) == 0:
  2139. # self.complete = True
  2140. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2141. self.select_shapes(point)
  2142. self.draw_app.replot()
  2143. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2144. return
  2145. if self.origin is None:
  2146. self.set_origin(point)
  2147. self.selection_shape = self.selection_bbox()
  2148. return "Click on final location."
  2149. else:
  2150. self.destination = point
  2151. self.make()
  2152. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2153. # 'params': []}))
  2154. return "Done."
  2155. def make(self):
  2156. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2157. # Create new geometry
  2158. dx = self.destination[0] - self.origin[0]
  2159. dy = self.destination[1] - self.origin[1]
  2160. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2161. for geom in self.draw_app.get_selected()]
  2162. # Delete old
  2163. self.draw_app.delete_selected()
  2164. self.complete = True
  2165. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Move completed."))
  2166. self.draw_app.app.jump_signal.disconnect()
  2167. def selection_bbox(self):
  2168. geo_list = []
  2169. for select_shape in self.draw_app.get_selected():
  2170. geometric_data = select_shape.geo
  2171. try:
  2172. for g in geometric_data:
  2173. geo_list.append(g)
  2174. except TypeError:
  2175. geo_list.append(geometric_data)
  2176. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2177. pt1 = (xmin, ymin)
  2178. pt2 = (xmax, ymin)
  2179. pt3 = (xmax, ymax)
  2180. pt4 = (xmin, ymax)
  2181. return Polygon([pt1, pt2, pt3, pt4])
  2182. def utility_geometry(self, data=None):
  2183. """
  2184. Temporary geometry on screen while using this tool.
  2185. :param data:
  2186. :return:
  2187. """
  2188. geo_list = []
  2189. if self.origin is None:
  2190. return None
  2191. if len(self.draw_app.get_selected()) == 0:
  2192. return None
  2193. dx = data[0] - self.origin[0]
  2194. dy = data[1] - self.origin[1]
  2195. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2196. try:
  2197. for geom in self.draw_app.get_selected():
  2198. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2199. except AttributeError:
  2200. self.draw_app.select_tool('select')
  2201. self.draw_app.selected = []
  2202. return
  2203. return DrawToolUtilityShape(geo_list)
  2204. else:
  2205. try:
  2206. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2207. except ValueError:
  2208. ss_el = None
  2209. return DrawToolUtilityShape(ss_el)
  2210. def select_shapes(self, pos):
  2211. # list where we store the overlapped shapes under our mouse left click position
  2212. over_shape_list = []
  2213. try:
  2214. _, closest_shape = self.storage.nearest(pos)
  2215. except StopIteration:
  2216. return ""
  2217. over_shape_list.append(closest_shape)
  2218. try:
  2219. # if there is no shape under our click then deselect all shapes
  2220. # it will not work for 3rd method of click selection
  2221. if not over_shape_list:
  2222. self.draw_app.selected = []
  2223. self.draw_app.draw_shape_idx = -1
  2224. else:
  2225. # if there are shapes under our click then advance through the list of them, one at the time in a
  2226. # circular way
  2227. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2228. try:
  2229. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2230. except IndexError:
  2231. return
  2232. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2233. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2234. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2235. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2236. if key_modifier == Qt.ControlModifier:
  2237. if obj_to_add in self.draw_app.selected:
  2238. self.draw_app.selected.remove(obj_to_add)
  2239. else:
  2240. self.draw_app.selected.append(obj_to_add)
  2241. else:
  2242. self.draw_app.selected = []
  2243. self.draw_app.selected.append(obj_to_add)
  2244. else:
  2245. if key_modifier == Qt.ShiftModifier:
  2246. if obj_to_add in self.draw_app.selected:
  2247. self.draw_app.selected.remove(obj_to_add)
  2248. else:
  2249. self.draw_app.selected.append(obj_to_add)
  2250. else:
  2251. self.draw_app.selected = []
  2252. self.draw_app.selected.append(obj_to_add)
  2253. except Exception as e:
  2254. log.error("[ERROR] Something went bad. %s" % str(e))
  2255. raise
  2256. def clean_up(self):
  2257. self.draw_app.selected = list()
  2258. self.draw_app.plot_all()
  2259. try:
  2260. self.draw_app.app.jump_signal.disconnect()
  2261. except (TypeError, AttributeError):
  2262. pass
  2263. class FCCopy(FCMove):
  2264. def __init__(self, draw_app):
  2265. FCMove.__init__(self, draw_app)
  2266. self.name = 'copy'
  2267. def make(self):
  2268. # Create new geometry
  2269. dx = self.destination[0] - self.origin[0]
  2270. dy = self.destination[1] - self.origin[1]
  2271. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2272. for geom in self.draw_app.get_selected()]
  2273. self.complete = True
  2274. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Copy completed."))
  2275. self.draw_app.app.jump_signal.disconnect()
  2276. def clean_up(self):
  2277. self.draw_app.selected = list()
  2278. self.draw_app.plot_all()
  2279. try:
  2280. self.draw_app.app.jump_signal.disconnect()
  2281. except (TypeError, AttributeError):
  2282. pass
  2283. class FCText(FCShapeTool):
  2284. def __init__(self, draw_app):
  2285. FCShapeTool.__init__(self, draw_app)
  2286. self.name = 'text'
  2287. self.draw_app = draw_app
  2288. try:
  2289. QtGui.QGuiApplication.restoreOverrideCursor()
  2290. except Exception:
  2291. pass
  2292. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_text.png'))
  2293. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2294. self.app = draw_app.app
  2295. self.draw_app.app.inform.emit(_("Click on 1st point ..."))
  2296. self.origin = (0, 0)
  2297. self.text_gui = TextInputTool(self.app)
  2298. self.text_gui.run()
  2299. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2300. def click(self, point):
  2301. # Create new geometry
  2302. dx = point[0]
  2303. dy = point[1]
  2304. if self.text_gui.text_path:
  2305. try:
  2306. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2307. except Exception as e:
  2308. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2309. self.draw_app.app.inform.emit('[ERROR] %s: %s' %
  2310. (_("Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2311. "supported. Error"), str(e)))
  2312. self.text_gui.text_path = []
  2313. self.text_gui.hide_tool()
  2314. self.draw_app.select_tool('select')
  2315. self.draw_app.app.jump_signal.disconnect()
  2316. return
  2317. else:
  2318. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' % _("No text to add."))
  2319. self.draw_app.app.jump_signal.disconnect()
  2320. return
  2321. self.text_gui.text_path = []
  2322. self.text_gui.hide_tool()
  2323. self.complete = True
  2324. self.draw_app.app.inform.emit('[success]%s' % _(" Done. Adding Text completed."))
  2325. def utility_geometry(self, data=None):
  2326. """
  2327. Temporary geometry on screen while using this tool.
  2328. :param data: mouse position coords
  2329. :return:
  2330. """
  2331. dx = data[0] - self.origin[0]
  2332. dy = data[1] - self.origin[1]
  2333. try:
  2334. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2335. except Exception:
  2336. return
  2337. def clean_up(self):
  2338. self.draw_app.selected = list()
  2339. self.draw_app.plot_all()
  2340. try:
  2341. self.draw_app.app.jump_signal.disconnect()
  2342. except (TypeError, AttributeError):
  2343. pass
  2344. class FCBuffer(FCShapeTool):
  2345. def __init__(self, draw_app):
  2346. FCShapeTool.__init__(self, draw_app)
  2347. self.name = 'buffer'
  2348. # self.shape_buffer = self.draw_app.shape_buffer
  2349. self.draw_app = draw_app
  2350. self.app = draw_app.app
  2351. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2352. self.origin = (0, 0)
  2353. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2354. self.buff_tool.run()
  2355. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2356. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2357. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2358. self.activate()
  2359. def on_buffer(self):
  2360. if not self.draw_app.selected:
  2361. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Buffer cancelled. No shape selected."))
  2362. return
  2363. try:
  2364. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2365. except ValueError:
  2366. # try to convert comma to decimal point. if it's still not working error message and return
  2367. try:
  2368. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2369. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2370. except ValueError:
  2371. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2372. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2373. return
  2374. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2375. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2376. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2377. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2378. self.app.ui.notebook.setTabText(2, _("Tools"))
  2379. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2380. self.disactivate()
  2381. if ret_val == 'fail':
  2382. return
  2383. self.draw_app.app.inform.emit('[success] %s' %
  2384. _("Done. Buffer Tool completed."))
  2385. def on_buffer_int(self):
  2386. if not self.draw_app.selected:
  2387. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2388. _("Buffer cancelled. No shape selected."))
  2389. return
  2390. try:
  2391. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2392. except ValueError:
  2393. # try to convert comma to decimal point. if it's still not working error message and return
  2394. try:
  2395. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2396. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2397. except ValueError:
  2398. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2399. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2400. return
  2401. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2402. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2403. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2404. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2405. self.app.ui.notebook.setTabText(2, _("Tools"))
  2406. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2407. self.disactivate()
  2408. if ret_val == 'fail':
  2409. return
  2410. self.draw_app.app.inform.emit('[success] %s' %
  2411. _("Done. Buffer Int Tool completed."))
  2412. def on_buffer_ext(self):
  2413. if not self.draw_app.selected:
  2414. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2415. _("Buffer cancelled. No shape selected."))
  2416. return
  2417. try:
  2418. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2419. except ValueError:
  2420. # try to convert comma to decimal point. if it's still not working error message and return
  2421. try:
  2422. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2423. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2424. except ValueError:
  2425. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2426. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2427. return
  2428. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2429. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2430. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2431. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2432. self.app.ui.notebook.setTabText(2, _("Tools"))
  2433. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2434. self.disactivate()
  2435. if ret_val == 'fail':
  2436. return
  2437. self.draw_app.app.inform.emit('[success] %s' %
  2438. _("Done. Buffer Ext Tool completed."))
  2439. def activate(self):
  2440. self.buff_tool.buffer_button.clicked.disconnect()
  2441. self.buff_tool.buffer_int_button.clicked.disconnect()
  2442. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2443. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2444. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2445. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2446. def disactivate(self):
  2447. self.buff_tool.buffer_button.clicked.disconnect()
  2448. self.buff_tool.buffer_int_button.clicked.disconnect()
  2449. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2450. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2451. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2452. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2453. self.complete = True
  2454. self.draw_app.select_tool("select")
  2455. self.buff_tool.hide_tool()
  2456. def clean_up(self):
  2457. self.draw_app.selected = list()
  2458. self.draw_app.plot_all()
  2459. try:
  2460. self.draw_app.app.jump_signal.disconnect()
  2461. except (TypeError, AttributeError):
  2462. pass
  2463. class FCEraser(FCShapeTool):
  2464. def __init__(self, draw_app):
  2465. DrawTool.__init__(self, draw_app)
  2466. self.name = 'eraser'
  2467. self.draw_app = draw_app
  2468. self.origin = None
  2469. self.destination = None
  2470. if len(self.draw_app.get_selected()) == 0:
  2471. if self.draw_app.launched_from_shortcuts is True:
  2472. self.draw_app.launched_from_shortcuts = False
  2473. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2474. else:
  2475. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2476. self.geometry = []
  2477. self.storage = self.draw_app.storage
  2478. # Switch notebook to Selected page
  2479. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2480. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2481. def set_origin(self, origin):
  2482. self.origin = origin
  2483. def click(self, point):
  2484. if len(self.draw_app.get_selected()) == 0:
  2485. for obj_shape in self.storage.get_objects():
  2486. try:
  2487. __, closest_shape = self.storage.nearest(point)
  2488. self.draw_app.selected.append(closest_shape)
  2489. except StopIteration:
  2490. if len(self.draw_app.selected) > 0:
  2491. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2492. return ""
  2493. if len(self.draw_app.get_selected()) == 0:
  2494. return "Nothing to ersase."
  2495. else:
  2496. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2497. if self.origin is None:
  2498. self.set_origin(point)
  2499. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2500. return
  2501. else:
  2502. self.destination = point
  2503. self.make()
  2504. # self.draw_app.select_tool("select")
  2505. return
  2506. def make(self):
  2507. eraser_sel_shapes = []
  2508. # create the eraser shape from selection
  2509. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2510. temp_shape = eraser_shape.buffer(0.0000001)
  2511. temp_shape = Polygon(temp_shape.exterior)
  2512. eraser_sel_shapes.append(temp_shape)
  2513. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2514. for obj_shape in self.storage.get_objects():
  2515. try:
  2516. geometric_data = obj_shape.geo
  2517. if eraser_sel_shapes.intersects(geometric_data):
  2518. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2519. except KeyError:
  2520. pass
  2521. self.draw_app.delete_utility_geometry()
  2522. self.draw_app.plot_all()
  2523. self.draw_app.app.inform.emit('[success] %s' % _("Done. Eraser tool action completed."))
  2524. self.draw_app.app.jump_signal.disconnect()
  2525. def utility_geometry(self, data=None):
  2526. """
  2527. Temporary geometry on screen while using this tool.
  2528. :param data:
  2529. :return:
  2530. """
  2531. geo_list = []
  2532. if self.origin is None:
  2533. return None
  2534. if len(self.draw_app.get_selected()) == 0:
  2535. return None
  2536. dx = data[0] - self.origin[0]
  2537. dy = data[1] - self.origin[1]
  2538. try:
  2539. for geom in self.draw_app.get_selected():
  2540. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2541. except AttributeError:
  2542. self.draw_app.select_tool('select')
  2543. self.draw_app.selected = []
  2544. return
  2545. return DrawToolUtilityShape(geo_list)
  2546. def clean_up(self):
  2547. self.draw_app.selected = list()
  2548. self.draw_app.plot_all()
  2549. try:
  2550. self.draw_app.app.jump_signal.disconnect()
  2551. except (TypeError, AttributeError):
  2552. pass
  2553. class FCPaint(FCShapeTool):
  2554. def __init__(self, draw_app):
  2555. FCShapeTool.__init__(self, draw_app)
  2556. self.name = 'paint'
  2557. self.draw_app = draw_app
  2558. self.app = draw_app.app
  2559. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2560. self.origin = (0, 0)
  2561. self.draw_app.paint_tool.run()
  2562. class FCTransform(FCShapeTool):
  2563. def __init__(self, draw_app):
  2564. FCShapeTool.__init__(self, draw_app)
  2565. self.name = 'transformation'
  2566. self.draw_app = draw_app
  2567. self.app = draw_app.app
  2568. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2569. self.origin = (0, 0)
  2570. self.draw_app.transform_tool.run()
  2571. # ###############################################
  2572. # ################ Main Application #############
  2573. # ###############################################
  2574. class FlatCAMGeoEditor(QtCore.QObject):
  2575. transform_complete = QtCore.pyqtSignal()
  2576. draw_shape_idx = -1
  2577. def __init__(self, app, disabled=False):
  2578. assert isinstance(app, FlatCAMApp.App), \
  2579. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2580. super(FlatCAMGeoEditor, self).__init__()
  2581. self.app = app
  2582. self.canvas = app.plotcanvas
  2583. self.decimals = app.decimals
  2584. # ## Toolbar events and properties
  2585. self.tools = {
  2586. "select": {"button": self.app.ui.geo_select_btn,
  2587. "constructor": FCSelect},
  2588. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2589. "constructor": FCArc},
  2590. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2591. "constructor": FCCircle},
  2592. "path": {"button": self.app.ui.geo_add_path_btn,
  2593. "constructor": FCPath},
  2594. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2595. "constructor": FCRectangle},
  2596. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2597. "constructor": FCPolygon},
  2598. "text": {"button": self.app.ui.geo_add_text_btn,
  2599. "constructor": FCText},
  2600. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2601. "constructor": FCBuffer},
  2602. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2603. "constructor": FCPaint},
  2604. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2605. "constructor": FCEraser},
  2606. "move": {"button": self.app.ui.geo_move_btn,
  2607. "constructor": FCMove},
  2608. "transform": {"button": self.app.ui.geo_transform_btn,
  2609. "constructor": FCTransform},
  2610. "copy": {"button": self.app.ui.geo_copy_btn,
  2611. "constructor": FCCopy},
  2612. "explode": {"button": self.app.ui.geo_explode_btn,
  2613. "constructor": FCExplode}
  2614. }
  2615. # # ## Data
  2616. self.active_tool = None
  2617. self.storage = FlatCAMGeoEditor.make_storage()
  2618. self.utility = []
  2619. # VisPy visuals
  2620. self.fcgeometry = None
  2621. if self.app.is_legacy is False:
  2622. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2623. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2624. else:
  2625. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2626. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='shapes_geo_editor')
  2627. self.tool_shape = ShapeCollectionLegacy(obj=self, app=self.app, name='tool_shapes_geo_editor')
  2628. self.app.pool_recreated.connect(self.pool_recreated)
  2629. # Remove from scene
  2630. self.shapes.enabled = False
  2631. self.tool_shape.enabled = False
  2632. # List of selected shapes.
  2633. self.selected = []
  2634. self.flat_geo = []
  2635. self.move_timer = QtCore.QTimer()
  2636. self.move_timer.setSingleShot(True)
  2637. # this var will store the state of the toolbar before starting the editor
  2638. self.toolbar_old_state = False
  2639. self.key = None # Currently pressed key
  2640. self.geo_key_modifiers = None
  2641. self.x = None # Current mouse cursor pos
  2642. self.y = None
  2643. # if we edit a multigeo geometry store here the tool number
  2644. self.multigeo_tool = None
  2645. # Current snapped mouse pos
  2646. self.snap_x = None
  2647. self.snap_y = None
  2648. self.pos = None
  2649. # signal that there is an action active like polygon or path
  2650. self.in_action = False
  2651. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2652. self.launched_from_shortcuts = False
  2653. def make_callback(thetool):
  2654. def f():
  2655. self.on_tool_select(thetool)
  2656. return f
  2657. for tool in self.tools:
  2658. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2659. self.tools[tool]["button"].setCheckable(True) # Checkable
  2660. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2661. self.app.ui.corner_snap_btn.setCheckable(True)
  2662. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2663. self.options = {
  2664. "global_gridx": 0.1,
  2665. "global_gridy": 0.1,
  2666. "global_snap_max": 0.05,
  2667. "grid_snap": True,
  2668. "corner_snap": False,
  2669. "grid_gap_link": True
  2670. }
  2671. self.options.update(self.app.options)
  2672. for option in self.options:
  2673. if option in self.app.options:
  2674. self.options[option] = self.app.options[option]
  2675. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2676. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2677. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2678. self.app.ui.grid_gap_link_cb.setChecked(True)
  2679. self.rtree_index = rtindex.Index()
  2680. def entry2option(option, entry):
  2681. try:
  2682. self.options[option] = float(entry.text())
  2683. except Exception as e:
  2684. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2685. return
  2686. def gridx_changed(goption, gentry):
  2687. entry2option(option=goption, entry=gentry)
  2688. # if the grid link is checked copy the value in the GridX field to GridY
  2689. try:
  2690. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2691. except ValueError:
  2692. return
  2693. units = self.app.defaults['units'].upper()
  2694. if self.app.ui.grid_gap_link_cb.isChecked():
  2695. self.app.ui.grid_gap_y_entry.set_value(val, decimals=self.decimals)
  2696. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2697. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2698. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2699. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2700. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2701. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2702. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2703. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2704. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2705. # if using Paint store here the tool diameter used
  2706. self.paint_tooldia = None
  2707. self.paint_tool = PaintOptionsTool(self.app, self)
  2708. self.transform_tool = TransformEditorTool(self.app, self)
  2709. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2710. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2711. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2712. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2713. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2714. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2715. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2716. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2717. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2718. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2719. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2720. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2721. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2722. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2723. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2724. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2725. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2726. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2727. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2728. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2729. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2730. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2731. self.transform_complete.connect(self.on_transform_complete)
  2732. # Event signals disconnect id holders
  2733. self.mp = None
  2734. self.mm = None
  2735. self.mr = None
  2736. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2737. self.editor_active = False
  2738. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2739. def pool_recreated(self, pool):
  2740. self.shapes.pool = pool
  2741. self.tool_shape.pool = pool
  2742. def on_transform_complete(self):
  2743. self.delete_selected()
  2744. self.replot()
  2745. def activate(self):
  2746. # adjust the status of the menu entries related to the editor
  2747. self.app.ui.menueditedit.setDisabled(True)
  2748. self.app.ui.menueditok.setDisabled(False)
  2749. # adjust the visibility of some of the canvas context menu
  2750. self.app.ui.popmenu_edit.setVisible(False)
  2751. self.app.ui.popmenu_save.setVisible(True)
  2752. self.connect_canvas_event_handlers()
  2753. # initialize working objects
  2754. self.storage = FlatCAMGeoEditor.make_storage()
  2755. self.utility = []
  2756. self.selected = []
  2757. self.shapes.enabled = True
  2758. self.tool_shape.enabled = True
  2759. self.app.app_cursor.enabled = True
  2760. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2761. self.app.ui.corner_snap_btn.setEnabled(True)
  2762. self.app.ui.snap_magnet.setVisible(True)
  2763. self.app.ui.corner_snap_btn.setVisible(True)
  2764. self.app.ui.geo_editor_menu.setDisabled(False)
  2765. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2766. self.app.ui.update_obj_btn.setEnabled(True)
  2767. self.app.ui.g_editor_cmenu.setEnabled(True)
  2768. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2769. self.app.ui.geo_edit_toolbar.setVisible(True)
  2770. self.app.ui.snap_toolbar.setDisabled(False)
  2771. self.app.ui.popmenu_disable.setVisible(False)
  2772. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2773. self.app.ui.popmenu_properties.setVisible(False)
  2774. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2775. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2776. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2777. for w in sel_tab_widget_list:
  2778. w.setEnabled(False)
  2779. # Tell the App that the editor is active
  2780. self.editor_active = True
  2781. log.debug("Finished activating the Geometry Editor...")
  2782. def deactivate(self):
  2783. try:
  2784. QtGui.QGuiApplication.restoreOverrideCursor()
  2785. except Exception as e:
  2786. pass
  2787. # adjust the status of the menu entries related to the editor
  2788. self.app.ui.menueditedit.setDisabled(False)
  2789. self.app.ui.menueditok.setDisabled(True)
  2790. # adjust the visibility of some of the canvas context menu
  2791. self.app.ui.popmenu_edit.setVisible(True)
  2792. self.app.ui.popmenu_save.setVisible(False)
  2793. self.disconnect_canvas_event_handlers()
  2794. self.clear()
  2795. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2796. settings = QSettings("Open Source", "FlatCAM")
  2797. if settings.contains("layout"):
  2798. layout = settings.value('layout', type=str)
  2799. if layout == 'standard':
  2800. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2801. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2802. self.app.ui.corner_snap_btn.setEnabled(False)
  2803. self.app.ui.snap_magnet.setVisible(False)
  2804. self.app.ui.corner_snap_btn.setVisible(False)
  2805. elif layout == 'compact':
  2806. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2807. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2808. self.app.ui.corner_snap_btn.setEnabled(False)
  2809. else:
  2810. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2811. self.app.ui.snap_magnet.setVisible(False)
  2812. self.app.ui.corner_snap_btn.setVisible(False)
  2813. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2814. self.app.ui.corner_snap_btn.setEnabled(False)
  2815. # set the Editor Toolbar visibility to what was before entering in the Editor
  2816. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2817. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2818. # Disable visuals
  2819. self.shapes.enabled = False
  2820. self.tool_shape.enabled = False
  2821. self.app.ui.geo_editor_menu.setDisabled(True)
  2822. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2823. self.app.ui.update_obj_btn.setEnabled(False)
  2824. self.app.ui.g_editor_cmenu.setEnabled(False)
  2825. self.app.ui.e_editor_cmenu.setEnabled(False)
  2826. # Tell the app that the editor is no longer active
  2827. self.editor_active = False
  2828. self.app.ui.popmenu_disable.setVisible(True)
  2829. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2830. self.app.ui.popmenu_properties.setVisible(True)
  2831. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2832. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2833. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2834. try:
  2835. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2836. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2837. for w in sel_tab_widget_list:
  2838. w.setEnabled(True)
  2839. except Exception as e:
  2840. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2841. # Show original geometry
  2842. if self.fcgeometry:
  2843. self.fcgeometry.visible = True
  2844. log.debug("Finished deactivating the Geometry Editor...")
  2845. def connect_canvas_event_handlers(self):
  2846. # Canvas events
  2847. # first connect to new, then disconnect the old handlers
  2848. # don't ask why but if there is nothing connected I've seen issues
  2849. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  2850. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  2851. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_geo_click_release)
  2852. if self.app.is_legacy is False:
  2853. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2854. # but those from FlatCAMGeoEditor
  2855. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2856. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2857. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2858. self.app.plotcanvas.graph_event_disconnect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  2859. else:
  2860. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  2861. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  2862. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  2863. self.app.plotcanvas.graph_event_disconnect(self.app.mdc)
  2864. # self.app.collection.view.clicked.disconnect()
  2865. self.app.ui.popmenu_copy.triggered.disconnect()
  2866. self.app.ui.popmenu_delete.triggered.disconnect()
  2867. self.app.ui.popmenu_move.triggered.disconnect()
  2868. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  2869. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2870. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  2871. # Geometry Editor
  2872. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  2873. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  2874. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  2875. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  2876. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  2877. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  2878. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  2879. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  2880. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  2881. self.app.ui.draw_union.triggered.connect(self.union)
  2882. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  2883. self.app.ui.draw_substract.triggered.connect(self.subtract)
  2884. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  2885. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  2886. self.app.ui.draw_move.triggered.connect(self.on_move)
  2887. def disconnect_canvas_event_handlers(self):
  2888. # we restore the key and mouse control to FlatCAMApp method
  2889. # first connect to new, then disconnect the old handlers
  2890. # don't ask why but if there is nothing connected I've seen issues
  2891. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2892. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2893. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2894. self.app.on_mouse_click_release_over_plot)
  2895. self.app.mdc = self.app.plotcanvas.graph_event_connect('mouse_double_click',
  2896. self.app.on_mouse_double_click_over_plot)
  2897. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2898. if self.app.is_legacy is False:
  2899. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  2900. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  2901. self.canvas.graph_event_disconnect('mouse_release', self.on_geo_click_release)
  2902. else:
  2903. self.canvas.graph_event_disconnect(self.mp)
  2904. self.canvas.graph_event_disconnect(self.mm)
  2905. self.canvas.graph_event_disconnect(self.mr)
  2906. try:
  2907. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  2908. except (TypeError, AttributeError):
  2909. pass
  2910. try:
  2911. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2912. except (TypeError, AttributeError):
  2913. pass
  2914. try:
  2915. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  2916. except (TypeError, AttributeError):
  2917. pass
  2918. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2919. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2920. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2921. # Geometry Editor
  2922. try:
  2923. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  2924. except (TypeError, AttributeError):
  2925. pass
  2926. try:
  2927. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  2928. except (TypeError, AttributeError):
  2929. pass
  2930. try:
  2931. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  2932. except (TypeError, AttributeError):
  2933. pass
  2934. try:
  2935. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  2936. except (TypeError, AttributeError):
  2937. pass
  2938. try:
  2939. self.app.ui.draw_circle.triggered.disconnect()
  2940. except (TypeError, AttributeError):
  2941. pass
  2942. try:
  2943. self.app.ui.draw_poly.triggered.disconnect()
  2944. except (TypeError, AttributeError):
  2945. pass
  2946. try:
  2947. self.app.ui.draw_arc.triggered.disconnect()
  2948. except (TypeError, AttributeError):
  2949. pass
  2950. try:
  2951. self.app.ui.draw_text.triggered.disconnect()
  2952. except (TypeError, AttributeError):
  2953. pass
  2954. try:
  2955. self.app.ui.draw_buffer.triggered.disconnect()
  2956. except (TypeError, AttributeError):
  2957. pass
  2958. try:
  2959. self.app.ui.draw_paint.triggered.disconnect()
  2960. except (TypeError, AttributeError):
  2961. pass
  2962. try:
  2963. self.app.ui.draw_eraser.triggered.disconnect()
  2964. except (TypeError, AttributeError):
  2965. pass
  2966. try:
  2967. self.app.ui.draw_union.triggered.disconnect(self.union)
  2968. except (TypeError, AttributeError):
  2969. pass
  2970. try:
  2971. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  2972. except (TypeError, AttributeError):
  2973. pass
  2974. try:
  2975. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  2976. except (TypeError, AttributeError):
  2977. pass
  2978. try:
  2979. self.app.ui.draw_transform.triggered.disconnect()
  2980. except (TypeError, AttributeError):
  2981. pass
  2982. try:
  2983. self.app.jump_signal.disconnect()
  2984. except (TypeError, AttributeError):
  2985. pass
  2986. def add_shape(self, shape):
  2987. """
  2988. Adds a shape to the shape storage.
  2989. :param shape: Shape to be added.
  2990. :type shape: DrawToolShape
  2991. :return: None
  2992. """
  2993. if shape is None:
  2994. return
  2995. # List of DrawToolShape?
  2996. if isinstance(shape, list):
  2997. for subshape in shape:
  2998. self.add_shape(subshape)
  2999. return
  3000. assert isinstance(shape, DrawToolShape), "Expected a DrawToolShape, got %s" % type(shape)
  3001. assert shape.geo is not None, "Shape object has empty geometry (None)"
  3002. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  3003. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  3004. if isinstance(shape, DrawToolUtilityShape):
  3005. self.utility.append(shape)
  3006. else:
  3007. self.storage.insert(shape) # TODO: Check performance
  3008. def delete_utility_geometry(self):
  3009. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3010. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3011. for_deletion = [shape for shape in self.utility]
  3012. for shape in for_deletion:
  3013. self.delete_shape(shape)
  3014. self.tool_shape.clear(update=True)
  3015. self.tool_shape.redraw()
  3016. def toolbar_tool_toggle(self, key):
  3017. self.options[key] = self.sender().isChecked()
  3018. return 1 if self.options[key] == True else 0
  3019. def clear(self):
  3020. self.active_tool = None
  3021. # self.shape_buffer = []
  3022. self.selected = []
  3023. self.shapes.clear(update=True)
  3024. self.tool_shape.clear(update=True)
  3025. # self.storage = FlatCAMGeoEditor.make_storage()
  3026. self.replot()
  3027. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  3028. """
  3029. Imports the geometry from the given FlatCAM Geometry object
  3030. into the editor.
  3031. :param fcgeometry: FlatCAMGeometry
  3032. :param multigeo_tool: a tool for the case of multigeo
  3033. :return: None
  3034. """
  3035. assert isinstance(fcgeometry, Geometry), \
  3036. "Expected a Geometry, got %s" % type(fcgeometry)
  3037. self.deactivate()
  3038. self.activate()
  3039. # Hide original geometry
  3040. self.fcgeometry = fcgeometry
  3041. fcgeometry.visible = False
  3042. # Set selection tolerance
  3043. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3044. self.select_tool("select")
  3045. if self.app.defaults['geometry_spindledir'] == 'CW':
  3046. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3047. milling_type = 1 # CCW motion = climb milling (spindle is rotating CW)
  3048. else:
  3049. milling_type = -1 # CW motion = conventional milling (spindle is rotating CW)
  3050. else:
  3051. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3052. milling_type = -1 # CCW motion = climb milling (spindle is rotating CCW)
  3053. else:
  3054. milling_type = 1 # CW motion = conventional milling (spindle is rotating CCW)
  3055. # Link shapes into editor.
  3056. if multigeo_tool:
  3057. self.multigeo_tool = multigeo_tool
  3058. geo_to_edit = self.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'],
  3059. orient_val=milling_type)
  3060. self.app.inform.emit(
  3061. '[WARNING_NOTCL] %s: %s %s: %s' % (
  3062. _("Editing MultiGeo Geometry, tool"),
  3063. str(self.multigeo_tool),
  3064. _("with diameter"),
  3065. str(fcgeometry.tools[self.multigeo_tool]['tooldia'])
  3066. )
  3067. )
  3068. else:
  3069. geo_to_edit = self.flatten(geometry=fcgeometry.solid_geometry,
  3070. orient_val=milling_type)
  3071. for shape in geo_to_edit:
  3072. if shape is not None: # TODO: Make flatten never create a None
  3073. if type(shape) == Polygon:
  3074. self.add_shape(DrawToolShape(shape.exterior))
  3075. for inter in shape.interiors:
  3076. self.add_shape(DrawToolShape(inter))
  3077. else:
  3078. self.add_shape(DrawToolShape(shape))
  3079. self.replot()
  3080. # updated units
  3081. self.units = self.app.defaults['units'].upper()
  3082. self.decimals = self.app.decimals
  3083. # start with GRID toolbar activated
  3084. if self.app.ui.grid_snap_btn.isChecked() is False:
  3085. self.app.ui.grid_snap_btn.trigger()
  3086. self.app.on_grid_snap_triggered(state=True)
  3087. def on_buffer_tool(self):
  3088. buff_tool = BufferSelectionTool(self.app, self)
  3089. buff_tool.run()
  3090. def on_paint_tool(self):
  3091. paint_tool = PaintOptionsTool(self.app, self)
  3092. paint_tool.run()
  3093. def on_tool_select(self, tool):
  3094. """
  3095. Behavior of the toolbar. Tool initialization.
  3096. :rtype : None
  3097. """
  3098. self.app.log.debug("on_tool_select('%s')" % tool)
  3099. # This is to make the group behave as radio group
  3100. if tool in self.tools:
  3101. if self.tools[tool]["button"].isChecked():
  3102. self.app.log.debug("%s is checked." % tool)
  3103. for t in self.tools:
  3104. if t != tool:
  3105. self.tools[t]["button"].setChecked(False)
  3106. self.active_tool = self.tools[tool]["constructor"](self)
  3107. else:
  3108. self.app.log.debug("%s is NOT checked." % tool)
  3109. for t in self.tools:
  3110. self.tools[t]["button"].setChecked(False)
  3111. self.select_tool('select')
  3112. self.active_tool = FCSelect(self)
  3113. def draw_tool_path(self):
  3114. self.select_tool('path')
  3115. return
  3116. def draw_tool_rectangle(self):
  3117. self.select_tool('rectangle')
  3118. return
  3119. def on_grid_toggled(self):
  3120. self.toolbar_tool_toggle("grid_snap")
  3121. # make sure that the cursor shape is enabled/disabled, too
  3122. if self.options['grid_snap'] is True:
  3123. self.app.app_cursor.enabled = True
  3124. else:
  3125. self.app.app_cursor.enabled = False
  3126. def on_canvas_click(self, event):
  3127. """
  3128. event.x and .y have canvas coordinates
  3129. event.xdaya and .ydata have plot coordinates
  3130. :param event: Event object dispatched by Matplotlib
  3131. :return: None
  3132. """
  3133. if self.app.is_legacy is False:
  3134. event_pos = event.pos
  3135. else:
  3136. event_pos = (event.xdata, event.ydata)
  3137. self.pos = self.canvas.translate_coords(event_pos)
  3138. if self.app.grid_status() == True:
  3139. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  3140. else:
  3141. self.pos = (self.pos[0], self.pos[1])
  3142. if event.button == 1:
  3143. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3144. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3145. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3146. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3147. if modifiers == QtCore.Qt.ShiftModifier:
  3148. self.app.clipboard.setText(
  3149. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3150. return
  3151. # Selection with left mouse button
  3152. if self.active_tool is not None and event.button == 1:
  3153. # Dispatch event to active_tool
  3154. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3155. # If it is a shape generating tool
  3156. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3157. self.on_shape_complete()
  3158. if isinstance(self.active_tool, FCText):
  3159. self.select_tool("select")
  3160. else:
  3161. self.select_tool(self.active_tool.name)
  3162. if isinstance(self.active_tool, FCSelect):
  3163. # self.app.log.debug("Replotting after click.")
  3164. self.replot()
  3165. else:
  3166. self.app.log.debug("No active tool to respond to click!")
  3167. def on_canvas_move(self, event):
  3168. """
  3169. Called on 'mouse_move' event
  3170. event.pos have canvas screen coordinates
  3171. :param event: Event object dispatched by VisPy SceneCavas
  3172. :return: None
  3173. """
  3174. if self.app.is_legacy is False:
  3175. event_pos = event.pos
  3176. event_is_dragging = event.is_dragging
  3177. right_button = 2
  3178. else:
  3179. event_pos = (event.xdata, event.ydata)
  3180. event_is_dragging = self.app.plotcanvas.is_dragging
  3181. right_button = 3
  3182. pos = self.canvas.translate_coords(event_pos)
  3183. event.xdata, event.ydata = pos[0], pos[1]
  3184. self.x = event.xdata
  3185. self.y = event.ydata
  3186. self.app.ui.popMenu.mouse_is_panning = False
  3187. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3188. if event.button == right_button:
  3189. if event_is_dragging:
  3190. self.app.ui.popMenu.mouse_is_panning = True
  3191. # return
  3192. else:
  3193. self.app.ui.popMenu.mouse_is_panning = False
  3194. if self.active_tool is None:
  3195. return
  3196. try:
  3197. x = float(event.xdata)
  3198. y = float(event.ydata)
  3199. except TypeError:
  3200. return
  3201. # ### Snap coordinates ###
  3202. if self.app.grid_status() == True:
  3203. x, y = self.snap(x, y)
  3204. # Update cursor
  3205. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3206. edge_width=self.app.defaults["global_cursor_width"],
  3207. size=self.app.defaults["global_cursor_size"])
  3208. self.snap_x = x
  3209. self.snap_y = y
  3210. self.app.mouse = [x, y]
  3211. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3212. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3213. "<b>Y</b>: %.4f" % (x, y))
  3214. if self.pos is None:
  3215. self.pos = (0, 0)
  3216. dx = x - self.pos[0]
  3217. dy = y - self.pos[1]
  3218. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3219. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3220. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3221. if event.button == 1 and event_is_dragging and isinstance(self.active_tool, FCEraser):
  3222. pass
  3223. else:
  3224. self.update_utility_geometry(data=(x, y))
  3225. # ### Selection area on canvas section ###
  3226. dx = pos[0] - self.pos[0]
  3227. if event_is_dragging and event.button == 1:
  3228. self.app.delete_selection_shape()
  3229. if dx < 0:
  3230. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3231. color=self.app.defaults["global_alt_sel_line"],
  3232. face_color=self.app.defaults['global_alt_sel_fill'])
  3233. self.app.selection_type = False
  3234. else:
  3235. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3236. self.app.selection_type = True
  3237. else:
  3238. self.app.selection_type = None
  3239. def update_utility_geometry(self, data):
  3240. # ### Utility geometry (animated) ###
  3241. geo = self.active_tool.utility_geometry(data=data)
  3242. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3243. # Remove any previous utility shape
  3244. self.tool_shape.clear(update=True)
  3245. self.draw_utility_geometry(geo=geo)
  3246. def on_geo_click_release(self, event):
  3247. if self.app.is_legacy is False:
  3248. event_pos = event.pos
  3249. event_is_dragging = event.is_dragging
  3250. right_button = 2
  3251. else:
  3252. event_pos = (event.xdata, event.ydata)
  3253. event_is_dragging = self.app.plotcanvas.is_dragging
  3254. right_button = 3
  3255. pos_canvas = self.canvas.translate_coords(event_pos)
  3256. if self.app.grid_status() == True:
  3257. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3258. else:
  3259. pos = (pos_canvas[0], pos_canvas[1])
  3260. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3261. # canvas menu
  3262. try:
  3263. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3264. # selection and then select a type of selection ("enclosing" or "touching")
  3265. if event.button == 1: # left click
  3266. if self.app.selection_type is not None:
  3267. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3268. self.app.selection_type = None
  3269. elif isinstance(self.active_tool, FCSelect):
  3270. # Dispatch event to active_tool
  3271. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3272. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3273. # self.app.inform.emit(msg)
  3274. self.replot()
  3275. elif event.button == right_button: # right click
  3276. if self.app.ui.popMenu.mouse_is_panning == False:
  3277. if self.in_action is False:
  3278. try:
  3279. QtGui.QGuiApplication.restoreOverrideCursor()
  3280. except Exception as e:
  3281. pass
  3282. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3283. self.active_tool.complete = True
  3284. self.in_action = False
  3285. self.delete_utility_geometry()
  3286. self.app.inform.emit('[success] %s' %
  3287. _("Done."))
  3288. self.select_tool('select')
  3289. else:
  3290. self.app.cursor = QtGui.QCursor()
  3291. self.app.populate_cmenu_grids()
  3292. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3293. else:
  3294. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3295. # right mouse click will finish the action
  3296. if isinstance(self.active_tool, FCShapeTool):
  3297. self.active_tool.click(self.snap(self.x, self.y))
  3298. self.active_tool.make()
  3299. if self.active_tool.complete:
  3300. self.on_shape_complete()
  3301. self.app.inform.emit('[success] %s' %
  3302. _("Done."))
  3303. self.select_tool(self.active_tool.name)
  3304. except Exception as e:
  3305. log.warning("FLatCAMGeoEditor.on_geo_click_release() --> Error: %s" % str(e))
  3306. return
  3307. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3308. """
  3309. :param start_pos: mouse position when the selection LMB click was done
  3310. :param end_pos: mouse position when the left mouse button is released
  3311. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3312. :return:
  3313. """
  3314. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3315. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3316. if key_modifier == QtCore.Qt.ShiftModifier:
  3317. mod_key = 'Shift'
  3318. elif key_modifier == QtCore.Qt.ControlModifier:
  3319. mod_key = 'Control'
  3320. else:
  3321. mod_key = None
  3322. self.app.delete_selection_shape()
  3323. sel_objects_list = []
  3324. for obj in self.storage.get_objects():
  3325. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3326. poly_selection.intersects(obj.geo)):
  3327. sel_objects_list.append(obj)
  3328. if mod_key == self.app.defaults["global_mselect_key"]:
  3329. for obj in sel_objects_list:
  3330. if obj in self.selected:
  3331. self.selected.remove(obj)
  3332. else:
  3333. # add the object to the selected shapes
  3334. self.selected.append(obj)
  3335. else:
  3336. self.selected = []
  3337. self.selected = sel_objects_list
  3338. self.replot()
  3339. def draw_utility_geometry(self, geo):
  3340. # Add the new utility shape
  3341. try:
  3342. # this case is for the Font Parse
  3343. for el in list(geo.geo):
  3344. if type(el) == MultiPolygon:
  3345. for poly in el:
  3346. self.tool_shape.add(
  3347. shape=poly,
  3348. color=(self.app.defaults["global_draw_color"] + '80'),
  3349. update=False,
  3350. layer=0,
  3351. tolerance=None
  3352. )
  3353. elif type(el) == MultiLineString:
  3354. for linestring in el:
  3355. self.tool_shape.add(
  3356. shape=linestring,
  3357. color=(self.app.defaults["global_draw_color"] + '80'),
  3358. update=False,
  3359. layer=0,
  3360. tolerance=None
  3361. )
  3362. else:
  3363. self.tool_shape.add(
  3364. shape=el,
  3365. color=(self.app.defaults["global_draw_color"] + '80'),
  3366. update=False,
  3367. layer=0,
  3368. tolerance=None
  3369. )
  3370. except TypeError:
  3371. self.tool_shape.add(
  3372. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3373. update=False, layer=0, tolerance=None)
  3374. self.tool_shape.redraw()
  3375. def on_delete_btn(self):
  3376. self.delete_selected()
  3377. self.replot()
  3378. def delete_selected(self):
  3379. tempref = [s for s in self.selected]
  3380. for shape in tempref:
  3381. self.delete_shape(shape)
  3382. self.selected = []
  3383. def delete_shape(self, shape):
  3384. if shape in self.utility:
  3385. self.utility.remove(shape)
  3386. return
  3387. self.storage.remove(shape)
  3388. if shape in self.selected:
  3389. self.selected.remove(shape) # TODO: Check performance
  3390. def on_move(self):
  3391. # if not self.selected:
  3392. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3393. # return
  3394. self.app.ui.geo_move_btn.setChecked(True)
  3395. self.on_tool_select('move')
  3396. def on_move_click(self):
  3397. self.on_move()
  3398. self.active_tool.set_origin(self.snap(self.x, self.y))
  3399. def on_copy_click(self):
  3400. if not self.selected:
  3401. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3402. _("Copy cancelled. No shape selected."))
  3403. return
  3404. self.app.ui.geo_copy_btn.setChecked(True)
  3405. self.app.geo_editor.on_tool_select('copy')
  3406. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3407. self.app.geo_editor.x, self.app.geo_editor.y))
  3408. self.app.inform.emit(_("Click on target point."))
  3409. def on_corner_snap(self):
  3410. self.app.ui.corner_snap_btn.trigger()
  3411. def get_selected(self):
  3412. """
  3413. Returns list of shapes that are selected in the editor.
  3414. :return: List of shapes.
  3415. """
  3416. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3417. return self.selected
  3418. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3419. """
  3420. Plots a geometric object or list of objects without rendering. Plotted objects
  3421. are returned as a list. This allows for efficient/animated rendering.
  3422. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3423. :param color: Shape color
  3424. :param linewidth: Width of lines in # of pixels.
  3425. :return: List of plotted elements.
  3426. """
  3427. plot_elements = []
  3428. if geometry is None:
  3429. geometry = self.active_tool.geometry
  3430. try:
  3431. for geo in geometry:
  3432. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3433. # Non-iterable
  3434. except TypeError:
  3435. # DrawToolShape
  3436. if isinstance(geometry, DrawToolShape):
  3437. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3438. # Polygon: Descend into exterior and each interior.
  3439. if type(geometry) == Polygon:
  3440. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3441. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3442. if type(geometry) == LineString or type(geometry) == LinearRing:
  3443. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3444. tolerance=self.fcgeometry.drawing_tolerance,
  3445. linewidth=linewidth))
  3446. if type(geometry) == Point:
  3447. pass
  3448. return plot_elements
  3449. def plot_all(self):
  3450. """
  3451. Plots all shapes in the editor.
  3452. :return: None
  3453. :rtype: None
  3454. """
  3455. # self.app.log.debug("plot_all()")
  3456. self.shapes.clear(update=True)
  3457. for shape in self.storage.get_objects():
  3458. if shape.geo is None: # TODO: This shouldn't have happened
  3459. continue
  3460. if shape in self.selected:
  3461. self.plot_shape(geometry=shape.geo,
  3462. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3463. linewidth=2)
  3464. continue
  3465. self.plot_shape(geometry=shape.geo,
  3466. color=self.app.defaults['global_draw_color'] + "FF")
  3467. for shape in self.utility:
  3468. self.plot_shape(geometry=shape.geo,
  3469. linewidth=1)
  3470. continue
  3471. self.shapes.redraw()
  3472. def replot(self):
  3473. self.plot_all()
  3474. def on_shape_complete(self):
  3475. self.app.log.debug("on_shape_complete()")
  3476. geom = []
  3477. try:
  3478. for shape in self.active_tool.geometry:
  3479. geom.append(shape.geo)
  3480. except TypeError:
  3481. geom = self.active_tool.geometry.geo
  3482. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3483. # reverse the geometry coordinates direction to allow creation of Gcode for climb milling
  3484. try:
  3485. pl = []
  3486. for p in geom:
  3487. if p is not None:
  3488. if isinstance(p, Polygon):
  3489. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3490. elif isinstance(p, LinearRing):
  3491. pl.append(Polygon(p.coords[::-1]))
  3492. elif isinstance(p, LineString):
  3493. pl.append(LineString(p.coords[::-1]))
  3494. try:
  3495. geom = MultiPolygon(pl)
  3496. except TypeError:
  3497. # this may happen if the geom elements are made out of LineStrings because you can't create a
  3498. # MultiPolygon out of LineStrings
  3499. pass
  3500. except TypeError:
  3501. if isinstance(geom, Polygon) and geom is not None:
  3502. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3503. elif isinstance(geom, LinearRing) and geom is not None:
  3504. geom = Polygon(geom.coords[::-1])
  3505. elif isinstance(geom, LineString) and geom is not None:
  3506. geom = LineString(geom.coords[::-1])
  3507. else:
  3508. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> Unexpected Geometry %s" %
  3509. type(geom))
  3510. except Exception as e:
  3511. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> %s" % str(e))
  3512. return 'fail'
  3513. shape_list = list()
  3514. try:
  3515. for geo in geom:
  3516. shape_list.append(DrawToolShape(geo))
  3517. except TypeError:
  3518. shape_list.append(DrawToolShape(geom))
  3519. # Add shape
  3520. self.add_shape(shape_list)
  3521. # Remove any utility shapes
  3522. self.delete_utility_geometry()
  3523. self.tool_shape.clear(update=True)
  3524. # Replot and reset tool.
  3525. self.replot()
  3526. # self.active_tool = type(self.active_tool)(self)
  3527. @staticmethod
  3528. def make_storage():
  3529. # Shape storage.
  3530. storage = FlatCAMRTreeStorage()
  3531. storage.get_points = DrawToolShape.get_pts
  3532. return storage
  3533. def select_tool(self, toolname):
  3534. """
  3535. Selects a drawing tool. Impacts the object and GUI.
  3536. :param toolname: Name of the tool.
  3537. :return: None
  3538. """
  3539. self.tools[toolname]["button"].setChecked(True)
  3540. self.on_tool_select(toolname)
  3541. def set_selected(self, shape):
  3542. # Remove and add to the end.
  3543. if shape in self.selected:
  3544. self.selected.remove(shape)
  3545. self.selected.append(shape)
  3546. def set_unselected(self, shape):
  3547. if shape in self.selected:
  3548. self.selected.remove(shape)
  3549. def snap(self, x, y):
  3550. """
  3551. Adjusts coordinates to snap settings.
  3552. :param x: Input coordinate X
  3553. :param y: Input coordinate Y
  3554. :return: Snapped (x, y)
  3555. """
  3556. snap_x, snap_y = (x, y)
  3557. snap_distance = np.Inf
  3558. # # ## Object (corner?) snap
  3559. # # ## No need for the objects, just the coordinates
  3560. # # ## in the index.
  3561. if self.options["corner_snap"]:
  3562. try:
  3563. nearest_pt, shape = self.storage.nearest((x, y))
  3564. nearest_pt_distance = distance((x, y), nearest_pt)
  3565. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3566. snap_distance = nearest_pt_distance
  3567. snap_x, snap_y = nearest_pt
  3568. except (StopIteration, AssertionError):
  3569. pass
  3570. # # ## Grid snap
  3571. if self.options["grid_snap"]:
  3572. if self.options["global_gridx"] != 0:
  3573. try:
  3574. snap_x_ = round(x / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3575. except TypeError:
  3576. snap_x_ = x
  3577. else:
  3578. snap_x_ = x
  3579. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3580. # and it will use the snap distance from GridX entry
  3581. if self.app.ui.grid_gap_link_cb.isChecked():
  3582. if self.options["global_gridx"] != 0:
  3583. try:
  3584. snap_y_ = round(y / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3585. except TypeError:
  3586. snap_y_ = y
  3587. else:
  3588. snap_y_ = y
  3589. else:
  3590. if self.options["global_gridy"] != 0:
  3591. try:
  3592. snap_y_ = round(y / float(self.options["global_gridy"])) * float(self.options['global_gridy'])
  3593. except TypeError:
  3594. snap_y_ = y
  3595. else:
  3596. snap_y_ = y
  3597. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3598. if nearest_grid_distance < snap_distance:
  3599. snap_x, snap_y = (snap_x_, snap_y_)
  3600. return snap_x, snap_y
  3601. def update_fcgeometry(self, fcgeometry):
  3602. """
  3603. Transfers the geometry tool shape buffer to the selected geometry
  3604. object. The geometry already in the object are removed.
  3605. :param fcgeometry: FlatCAMGeometry
  3606. :return: None
  3607. """
  3608. if self.multigeo_tool:
  3609. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3610. # for shape in self.shape_buffer:
  3611. for shape in self.storage.get_objects():
  3612. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  3613. self.multigeo_tool = None
  3614. fcgeometry.solid_geometry = []
  3615. # for shape in self.shape_buffer:
  3616. for shape in self.storage.get_objects():
  3617. fcgeometry.solid_geometry.append(shape.geo)
  3618. def update_options(self, obj):
  3619. if self.paint_tooldia:
  3620. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3621. self.paint_tooldia = None
  3622. return True
  3623. else:
  3624. return False
  3625. def union(self):
  3626. """
  3627. Makes union of selected polygons. Original polygons
  3628. are deleted.
  3629. :return: None.
  3630. """
  3631. results = unary_union([t.geo for t in self.get_selected()])
  3632. # Delete originals.
  3633. for_deletion = [s for s in self.get_selected()]
  3634. for shape in for_deletion:
  3635. self.delete_shape(shape)
  3636. # Selected geometry is now gone!
  3637. self.selected = []
  3638. self.add_shape(DrawToolShape(results))
  3639. self.replot()
  3640. def intersection_2(self):
  3641. """
  3642. Makes intersection of selected polygons. Original polygons are deleted.
  3643. :return: None
  3644. """
  3645. geo_shapes = self.get_selected()
  3646. try:
  3647. results = geo_shapes[0].geo
  3648. except Exception as e:
  3649. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3650. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3651. _("A selection of at least 2 geo items is required to do Intersection."))
  3652. self.select_tool('select')
  3653. return
  3654. for shape_el in geo_shapes[1:]:
  3655. results = results.intersection(shape_el.geo)
  3656. # Delete originals.
  3657. for_deletion = [s for s in self.get_selected()]
  3658. for shape_el in for_deletion:
  3659. self.delete_shape(shape_el)
  3660. # Selected geometry is now gone!
  3661. self.selected = []
  3662. self.add_shape(DrawToolShape(results))
  3663. self.replot()
  3664. def intersection(self):
  3665. """
  3666. Makes intersection of selected polygons. Original polygons are deleted.
  3667. :return: None
  3668. """
  3669. geo_shapes = self.get_selected()
  3670. results = []
  3671. intact = []
  3672. try:
  3673. intersector = geo_shapes[0].geo
  3674. except Exception as e:
  3675. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3676. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3677. _("A selection of at least 2 geo items is required to do Intersection."))
  3678. self.select_tool('select')
  3679. return
  3680. for shape_el in geo_shapes[1:]:
  3681. if intersector.intersects(shape_el.geo):
  3682. results.append(intersector.intersection(shape_el.geo))
  3683. else:
  3684. intact.append(shape_el)
  3685. if len(results) != 0:
  3686. # Delete originals.
  3687. for_deletion = [s for s in self.get_selected()]
  3688. for shape_el in for_deletion:
  3689. if shape_el not in intact:
  3690. self.delete_shape(shape_el)
  3691. for geo in results:
  3692. self.add_shape(DrawToolShape(geo))
  3693. # Selected geometry is now gone!
  3694. self.selected = []
  3695. self.replot()
  3696. def subtract(self):
  3697. selected = self.get_selected()
  3698. try:
  3699. tools = selected[1:]
  3700. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3701. target = selected[0].geo
  3702. target = target.buffer(0.0000001)
  3703. result = target.difference(toolgeo)
  3704. for_deletion = [s for s in self.get_selected()]
  3705. for shape in for_deletion:
  3706. self.delete_shape(shape)
  3707. self.add_shape(DrawToolShape(result))
  3708. self.replot()
  3709. except Exception as e:
  3710. log.debug(str(e))
  3711. def subtract_2(self):
  3712. selected = self.get_selected()
  3713. try:
  3714. tools = selected[1:]
  3715. toolgeo = unary_union([shp.geo for shp in tools])
  3716. result = selected[0].geo.difference(toolgeo)
  3717. self.delete_shape(selected[0])
  3718. self.add_shape(DrawToolShape(result))
  3719. self.replot()
  3720. except Exception as e:
  3721. log.debug(str(e))
  3722. def cutpath(self):
  3723. selected = self.get_selected()
  3724. tools = selected[1:]
  3725. toolgeo = unary_union([shp.geo for shp in tools])
  3726. target = selected[0]
  3727. if type(target.geo) == Polygon:
  3728. for ring in poly2rings(target.geo):
  3729. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3730. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3731. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3732. elif type(target.geo) == MultiLineString:
  3733. try:
  3734. for linestring in target.geo:
  3735. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3736. except Exception as e:
  3737. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3738. else:
  3739. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3740. return
  3741. self.delete_shape(target)
  3742. self.replot()
  3743. def buffer(self, buf_distance, join_style):
  3744. selected = self.get_selected()
  3745. if buf_distance < 0:
  3746. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3747. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3748. "'inside' shape"))
  3749. # deselect everything
  3750. self.selected = []
  3751. self.replot()
  3752. return 'fail'
  3753. if len(selected) == 0:
  3754. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3755. _("Nothing selected for buffering."))
  3756. return 'fail'
  3757. if not isinstance(buf_distance, float):
  3758. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3759. _("Invalid distance for buffering."))
  3760. # deselect everything
  3761. self.selected = []
  3762. self.replot()
  3763. return 'fail'
  3764. results = []
  3765. for t in selected:
  3766. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3767. results.append(t.geo.exterior.buffer(
  3768. buf_distance - 1e-10,
  3769. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3770. join_style=join_style)
  3771. )
  3772. else:
  3773. results.append(t.geo.buffer(
  3774. buf_distance - 1e-10,
  3775. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3776. join_style=join_style)
  3777. )
  3778. if not results:
  3779. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3780. _("Failed, the result is empty. Choose a different buffer value."))
  3781. # deselect everything
  3782. self.selected = []
  3783. self.replot()
  3784. return 'fail'
  3785. for sha in results:
  3786. self.add_shape(DrawToolShape(sha))
  3787. self.replot()
  3788. self.app.inform.emit('[success] %s' %
  3789. _("Full buffer geometry created."))
  3790. def buffer_int(self, buf_distance, join_style):
  3791. selected = self.get_selected()
  3792. if buf_distance < 0:
  3793. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Negative buffer value is not accepted."))
  3794. # deselect everything
  3795. self.selected = []
  3796. self.replot()
  3797. return 'fail'
  3798. if len(selected) == 0:
  3799. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for buffering."))
  3800. return 'fail'
  3801. if not isinstance(buf_distance, float):
  3802. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Invalid distance for buffering."))
  3803. # deselect everything
  3804. self.selected = []
  3805. self.replot()
  3806. return 'fail'
  3807. results = []
  3808. for t in selected:
  3809. if isinstance(t.geo, LinearRing):
  3810. t.geo = Polygon(t.geo)
  3811. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3812. results.append(t.geo.buffer(
  3813. -buf_distance + 1e-10,
  3814. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3815. join_style=join_style)
  3816. )
  3817. if not results:
  3818. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3819. _("Failed, the result is empty. Choose a smaller buffer value."))
  3820. # deselect everything
  3821. self.selected = []
  3822. self.replot()
  3823. return 'fail'
  3824. for sha in results:
  3825. self.add_shape(DrawToolShape(sha))
  3826. self.replot()
  3827. self.app.inform.emit('[success] %s' % _("Interior buffer geometry created."))
  3828. def buffer_ext(self, buf_distance, join_style):
  3829. selected = self.get_selected()
  3830. if buf_distance < 0:
  3831. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3832. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3833. "'inside' shape"))
  3834. # deselect everything
  3835. self.selected = []
  3836. self.replot()
  3837. return
  3838. if len(selected) == 0:
  3839. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3840. _("Nothing selected for buffering."))
  3841. return
  3842. if not isinstance(buf_distance, float):
  3843. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3844. _("Invalid distance for buffering."))
  3845. # deselect everything
  3846. self.selected = []
  3847. self.replot()
  3848. return
  3849. results = []
  3850. for t in selected:
  3851. if isinstance(t.geo, LinearRing):
  3852. t.geo = Polygon(t.geo)
  3853. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3854. results.append(t.geo.buffer(
  3855. buf_distance,
  3856. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3857. join_style=join_style)
  3858. )
  3859. if not results:
  3860. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3861. _("Failed, the result is empty. Choose a different buffer value."))
  3862. # deselect everything
  3863. self.selected = []
  3864. self.replot()
  3865. return
  3866. for sha in results:
  3867. self.add_shape(DrawToolShape(sha))
  3868. self.replot()
  3869. self.app.inform.emit('[success] %s' % _("Exterior buffer geometry created."))
  3870. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3871. if overlap >= 100:
  3872. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3873. _("Could not do Paint. Overlap value has to be less than 100%%."))
  3874. return
  3875. self.paint_tooldia = tooldia
  3876. selected = self.get_selected()
  3877. if len(selected) == 0:
  3878. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for painting."))
  3879. return
  3880. for param in [tooldia, overlap, margin]:
  3881. if not isinstance(param, float):
  3882. param_name = [k for k, v in locals().items() if v is param][0]
  3883. self.app.inform.emit('[WARNING] %s: %s' % (_("Invalid value for"), str(param)))
  3884. results = []
  3885. def recurse(geometry, reset=True):
  3886. """
  3887. Creates a list of non-iterable linear geometry objects.
  3888. Results are placed in self.flat_geometry
  3889. :param geometry: Shapely type or list or list of list of such.
  3890. :param reset: Clears the contents of self.flat_geometry.
  3891. """
  3892. if geometry is None:
  3893. return
  3894. if reset:
  3895. self.flat_geo = []
  3896. # If iterable, expand recursively.
  3897. try:
  3898. for geo_el in geometry:
  3899. if geo_el is not None:
  3900. recurse(geometry=geo_el, reset=False)
  3901. # Not iterable, do the actual indexing and add.
  3902. except TypeError:
  3903. self.flat_geo.append(geometry)
  3904. return self.flat_geo
  3905. for geo in selected:
  3906. local_results = []
  3907. for geo_obj in recurse(geo.geo):
  3908. try:
  3909. if type(geo_obj) == Polygon:
  3910. poly_buf = geo_obj.buffer(-margin)
  3911. else:
  3912. poly_buf = Polygon(geo_obj).buffer(-margin)
  3913. if method == "seed":
  3914. cp = Geometry.clear_polygon2(self, polygon_to_clear=poly_buf, tooldia=tooldia,
  3915. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3916. overlap=overlap, contour=contour, connect=connect)
  3917. elif method == "lines":
  3918. cp = Geometry.clear_polygon3(self, polygon=poly_buf, tooldia=tooldia,
  3919. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3920. overlap=overlap, contour=contour, connect=connect)
  3921. else:
  3922. cp = Geometry.clear_polygon(self, polygon=poly_buf, tooldia=tooldia,
  3923. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3924. overlap=overlap, contour=contour, connect=connect)
  3925. if cp is not None:
  3926. local_results += list(cp.get_objects())
  3927. except Exception as e:
  3928. log.debug("Could not Paint the polygons. %s" % str(e))
  3929. self.app.inform.emit('[ERROR] %s\n%s' %
  3930. (_("Could not do Paint. Try a different combination of"
  3931. " parameters. Or a different method of Paint"),
  3932. str(e)
  3933. )
  3934. )
  3935. return
  3936. # add the result to the results list
  3937. results.append(cascaded_union(local_results))
  3938. # This is a dirty patch:
  3939. for r in results:
  3940. self.add_shape(DrawToolShape(r))
  3941. self.app.inform.emit(
  3942. '[success] %s' % _("Paint done."))
  3943. self.replot()
  3944. def flatten(self, geometry, orient_val=1, reset=True, pathonly=False):
  3945. """
  3946. Creates a list of non-iterable linear geometry objects.
  3947. Polygons are expanded into its exterior and interiors if specified.
  3948. Results are placed in self.flat_geometry
  3949. :param geometry: Shapely type or list or list of list of such.
  3950. :param orient_val: will orient the exterior coordinates CW if 1 and CCW for else (whatever else means ...)
  3951. https://shapely.readthedocs.io/en/stable/manual.html#polygons
  3952. :param reset: Clears the contents of self.flat_geometry.
  3953. :param pathonly: Expands polygons into linear elements.
  3954. """
  3955. if reset:
  3956. self.flat_geo = []
  3957. # ## If iterable, expand recursively.
  3958. try:
  3959. for geo in geometry:
  3960. if geo is not None:
  3961. self.flatten(geometry=geo,
  3962. orient_val=orient_val,
  3963. reset=False,
  3964. pathonly=pathonly)
  3965. # ## Not iterable, do the actual indexing and add.
  3966. except TypeError:
  3967. if type(geometry) == Polygon:
  3968. geometry = orient(geometry, orient_val)
  3969. if pathonly and type(geometry) == Polygon:
  3970. self.flat_geo.append(geometry.exterior)
  3971. self.flatten(geometry=geometry.interiors,
  3972. reset=False,
  3973. pathonly=True)
  3974. else:
  3975. self.flat_geo.append(geometry)
  3976. return self.flat_geo
  3977. def distance(pt1, pt2):
  3978. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3979. def mag(vec):
  3980. return np.sqrt(vec[0] ** 2 + vec[1] ** 2)
  3981. def poly2rings(poly):
  3982. return [poly.exterior] + [interior for interior in poly.interiors]
  3983. def get_shapely_list_bounds(geometry_list):
  3984. xmin = np.Inf
  3985. ymin = np.Inf
  3986. xmax = -np.Inf
  3987. ymax = -np.Inf
  3988. for gs in geometry_list:
  3989. try:
  3990. gxmin, gymin, gxmax, gymax = gs.bounds
  3991. xmin = min([xmin, gxmin])
  3992. ymin = min([ymin, gymin])
  3993. xmax = max([xmax, gxmax])
  3994. ymax = max([ymax, gymax])
  3995. except Exception as e:
  3996. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3997. return [xmin, ymin, xmax, ymax]