FlatCAMEditor.py 191 KB

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