FlatCAMEditor.py 200 KB

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