FlatCAMEditor.py 198 KB

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