FlatCAMGeoEditor.py 178 KB

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