FlatCAMGeoEditor.py 178 KB

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