FlatCAMGeoEditor.py 183 KB

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