FlatCAMGeoEditor.py 181 KB

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