FlatCAMEditor.py 200 KB

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