FlatCAMGeoEditor.py 194 KB

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