FlatCAMGeoEditor.py 193 KB

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