FlatCAMGeoEditor.py 179 KB

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