FlatCAMEditor.py 193 KB

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