FlatCAMEditor.py 193 KB

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