FlatCAMGeoEditor.py 178 KB

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