FlatCAMGeoEditor.py 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554
  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. # ########################################################### #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. # ######################################################### ##
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. from camlib import *
  15. from FlatCAMTool import FlatCAMTool
  16. from flatcamGUI.ObjectUI import LengthEntry, RadioSet
  17. from shapely.geometry import LineString, LinearRing, MultiLineString
  18. # from shapely.geometry import mapping
  19. from shapely.ops import cascaded_union, unary_union
  20. import shapely.affinity as affinity
  21. from numpy import arctan2, Inf, array, sqrt, sign, dot
  22. from numpy.linalg import norm as numpy_norm
  23. from rtree import index as rtindex
  24. from flatcamGUI.GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCComboBox, FCTextAreaRich, \
  25. FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  26. from flatcamParsers.ParseFont import *
  27. # from vispy.io import read_png
  28. import gettext
  29. import FlatCAMTranslation as fcTranslate
  30. import builtins
  31. fcTranslate.apply_language('strings')
  32. if '_' not in builtins.__dict__:
  33. _ = gettext.gettext
  34. class BufferSelectionTool(FlatCAMTool):
  35. """
  36. Simple input for buffer distance.
  37. """
  38. toolName = "Buffer Selection"
  39. def __init__(self, app, draw_app):
  40. FlatCAMTool.__init__(self, app)
  41. self.draw_app = draw_app
  42. # Title
  43. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  44. title_label.setStyleSheet("""
  45. QLabel
  46. {
  47. font-size: 16px;
  48. font-weight: bold;
  49. }
  50. """)
  51. self.layout.addWidget(title_label)
  52. # this way I can hide/show the frame
  53. self.buffer_tool_frame = QtWidgets.QFrame()
  54. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  55. self.layout.addWidget(self.buffer_tool_frame)
  56. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  57. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  58. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  59. # Form Layout
  60. form_layout = QtWidgets.QFormLayout()
  61. self.buffer_tools_box.addLayout(form_layout)
  62. # Buffer distance
  63. self.buffer_distance_entry = FCDoubleSpinner()
  64. self.buffer_distance_entry.set_precision(4)
  65. self.buffer_distance_entry.set_range(0.0000, 999999.9999)
  66. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  67. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  68. self.buffer_corner_lbl.setToolTip(
  69. _("There are 3 types of corners:\n"
  70. " - 'Round': the corner is rounded for exterior buffer.\n"
  71. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  72. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  73. )
  74. self.buffer_corner_cb = FCComboBox()
  75. self.buffer_corner_cb.addItem(_("Round"))
  76. self.buffer_corner_cb.addItem(_("Square"))
  77. self.buffer_corner_cb.addItem(_("Beveled"))
  78. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  79. # Buttons
  80. hlay = QtWidgets.QHBoxLayout()
  81. self.buffer_tools_box.addLayout(hlay)
  82. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  83. hlay.addWidget(self.buffer_int_button)
  84. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  85. hlay.addWidget(self.buffer_ext_button)
  86. hlay1 = QtWidgets.QHBoxLayout()
  87. self.buffer_tools_box.addLayout(hlay1)
  88. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  89. hlay1.addWidget(self.buffer_button)
  90. self.layout.addStretch()
  91. # Signals
  92. self.buffer_button.clicked.connect(self.on_buffer)
  93. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  94. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  95. # Init GUI
  96. self.buffer_distance_entry.set_value(0.01)
  97. def run(self):
  98. self.app.report_usage("Geo Editor ToolBuffer()")
  99. FlatCAMTool.run(self)
  100. # if the splitter us hidden, display it
  101. if self.app.ui.splitter.sizes()[0] == 0:
  102. self.app.ui.splitter.setSizes([1, 1])
  103. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  104. def on_buffer(self):
  105. try:
  106. buffer_distance = float(self.buffer_distance_entry.get_value())
  107. except ValueError:
  108. # try to convert comma to decimal point. if it's still not working error message and return
  109. try:
  110. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  111. self.buffer_distance_entry.set_value(buffer_distance)
  112. except ValueError:
  113. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  114. "Add it and retry."))
  115. return
  116. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  117. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  118. join_style = self.buffer_corner_cb.currentIndex() + 1
  119. self.draw_app.buffer(buffer_distance, join_style)
  120. def on_buffer_int(self):
  121. try:
  122. buffer_distance = float(self.buffer_distance_entry.get_value())
  123. except ValueError:
  124. # try to convert comma to decimal point. if it's still not working error message and return
  125. try:
  126. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  127. self.buffer_distance_entry.set_value(buffer_distance)
  128. except ValueError:
  129. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  130. "Add it and retry."))
  131. return
  132. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  133. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  134. join_style = self.buffer_corner_cb.currentIndex() + 1
  135. self.draw_app.buffer_int(buffer_distance, join_style)
  136. def on_buffer_ext(self):
  137. try:
  138. buffer_distance = float(self.buffer_distance_entry.get_value())
  139. except ValueError:
  140. # try to convert comma to decimal point. if it's still not working error message and return
  141. try:
  142. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  143. self.buffer_distance_entry.set_value(buffer_distance)
  144. except ValueError:
  145. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  146. "Add it and retry."))
  147. return
  148. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  149. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  150. join_style = self.buffer_corner_cb.currentIndex() + 1
  151. self.draw_app.buffer_ext(buffer_distance, join_style)
  152. def hide_tool(self):
  153. self.buffer_tool_frame.hide()
  154. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  155. class TextInputTool(FlatCAMTool):
  156. """
  157. Simple input for buffer distance.
  158. """
  159. toolName = "Text Input Tool"
  160. def __init__(self, app):
  161. FlatCAMTool.__init__(self, app)
  162. self.app = app
  163. self.text_path = []
  164. self.f_parse = ParseFont(self)
  165. self.f_parse.get_fonts_by_types()
  166. # this way I can hide/show the frame
  167. self.text_tool_frame = QtWidgets.QFrame()
  168. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  169. self.layout.addWidget(self.text_tool_frame)
  170. self.text_tools_box = QtWidgets.QVBoxLayout()
  171. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  172. self.text_tool_frame.setLayout(self.text_tools_box)
  173. # Title
  174. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  175. title_label.setStyleSheet("""
  176. QLabel
  177. {
  178. font-size: 16px;
  179. font-weight: bold;
  180. }
  181. """)
  182. self.text_tools_box.addWidget(title_label)
  183. # Form Layout
  184. self.form_layout = QtWidgets.QFormLayout()
  185. self.text_tools_box.addLayout(self.form_layout)
  186. # Font type
  187. if sys.platform == "win32":
  188. f_current = QtGui.QFont("Arial")
  189. elif sys.platform == "linux":
  190. f_current = QtGui.QFont("FreeMono")
  191. else:
  192. f_current = QtGui.QFont("Helvetica Neue")
  193. self.font_name = f_current.family()
  194. self.font_type_cb = QtWidgets.QFontComboBox(self)
  195. self.font_type_cb.setCurrentFont(f_current)
  196. self.form_layout.addRow("Font:", self.font_type_cb)
  197. # Flag variables to show if font is bold, italic, both or none (regular)
  198. self.font_bold = False
  199. self.font_italic = False
  200. # # Create dictionaries with the filenames of the fonts
  201. # # Key: Fontname
  202. # # Value: Font File Name.ttf
  203. #
  204. # # regular fonts
  205. # self.ff_names_regular ={}
  206. # # bold fonts
  207. # self.ff_names_bold = {}
  208. # # italic fonts
  209. # self.ff_names_italic = {}
  210. # # bold and italic fonts
  211. # self.ff_names_bi = {}
  212. #
  213. # if sys.platform == 'win32':
  214. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  215. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  216. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  217. # try:
  218. # i = 0
  219. # while 1:
  220. # name_font, value, type = EnumValue(font_key, i)
  221. # k = name_font.replace(" (TrueType)", '')
  222. # if 'Bold' in k and 'Italic' in k:
  223. # k = k.replace(" Bold Italic", '')
  224. # self.ff_names_bi.update({k: value})
  225. # elif 'Bold' in k:
  226. # k = k.replace(" Bold", '')
  227. # self.ff_names_bold.update({k: value})
  228. # elif 'Italic' in k:
  229. # k = k.replace(" Italic", '')
  230. # self.ff_names_italic.update({k: value})
  231. # else:
  232. # self.ff_names_regular.update({k: value})
  233. # i += 1
  234. # except WindowsError:
  235. # pass
  236. # Font size
  237. self.font_size_cb = FCComboBox()
  238. self.font_size_cb.setEditable(True)
  239. self.font_size_cb.setMinimumContentsLength(3)
  240. self.font_size_cb.setMaximumWidth(70)
  241. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  242. '15', '16', '18', '20', '22', '24', '26', '28',
  243. '32', '36', '40', '44', '48', '54', '60', '66',
  244. '72', '80', '88', '96']
  245. for i in font_sizes:
  246. self.font_size_cb.addItem(i)
  247. self.font_size_cb.setCurrentIndex(4)
  248. hlay = QtWidgets.QHBoxLayout()
  249. hlay.addWidget(self.font_size_cb)
  250. hlay.addStretch()
  251. self.font_bold_tb = QtWidgets.QToolButton()
  252. self.font_bold_tb.setCheckable(True)
  253. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  254. hlay.addWidget(self.font_bold_tb)
  255. self.font_italic_tb = QtWidgets.QToolButton()
  256. self.font_italic_tb.setCheckable(True)
  257. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  258. hlay.addWidget(self.font_italic_tb)
  259. self.form_layout.addRow("Size:", hlay)
  260. # Text input
  261. self.text_input_entry = FCTextAreaRich()
  262. self.text_input_entry.setTabStopWidth(12)
  263. self.text_input_entry.setMinimumHeight(200)
  264. # self.text_input_entry.setMaximumHeight(150)
  265. self.text_input_entry.setCurrentFont(f_current)
  266. self.text_input_entry.setFontPointSize(10)
  267. self.form_layout.addRow("Text:", self.text_input_entry)
  268. # Buttons
  269. hlay1 = QtWidgets.QHBoxLayout()
  270. self.form_layout.addRow("", hlay1)
  271. hlay1.addStretch()
  272. self.apply_button = QtWidgets.QPushButton("Apply")
  273. hlay1.addWidget(self.apply_button)
  274. # self.layout.addStretch()
  275. # Signals
  276. self.apply_button.clicked.connect(self.on_apply_button)
  277. self.font_type_cb.currentFontChanged.connect(self.font_family)
  278. self.font_size_cb.activated.connect(self.font_size)
  279. self.font_bold_tb.clicked.connect(self.on_bold_button)
  280. self.font_italic_tb.clicked.connect(self.on_italic_button)
  281. def run(self):
  282. self.app.report_usage("Geo Editor TextInputTool()")
  283. FlatCAMTool.run(self)
  284. # if the splitter us hidden, display it
  285. if self.app.ui.splitter.sizes()[0] == 0:
  286. self.app.ui.splitter.setSizes([1, 1])
  287. self.app.ui.notebook.setTabText(2, _("Text Tool"))
  288. def on_apply_button(self):
  289. font_to_geo_type = ""
  290. if self.font_bold is True:
  291. font_to_geo_type = 'bold'
  292. elif self.font_italic is True:
  293. font_to_geo_type = 'italic'
  294. elif self.font_bold is True and self.font_italic is True:
  295. font_to_geo_type = 'bi'
  296. elif self.font_bold is False and self.font_italic is False:
  297. font_to_geo_type = 'regular'
  298. string_to_geo = self.text_input_entry.get_value()
  299. font_to_geo_size = self.font_size_cb.get_value()
  300. self.text_path = self.f_parse.font_to_geometry(
  301. char_string=string_to_geo,
  302. font_name=self.font_name,
  303. font_size=font_to_geo_size,
  304. font_type=font_to_geo_type,
  305. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  306. def font_family(self, font):
  307. self.text_input_entry.selectAll()
  308. font.setPointSize(float(self.font_size_cb.get_value()))
  309. self.text_input_entry.setCurrentFont(font)
  310. self.font_name = self.font_type_cb.currentFont().family()
  311. def font_size(self):
  312. self.text_input_entry.selectAll()
  313. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  314. def on_bold_button(self):
  315. if self.font_bold_tb.isChecked():
  316. self.text_input_entry.selectAll()
  317. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  318. self.font_bold = True
  319. else:
  320. self.text_input_entry.selectAll()
  321. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  322. self.font_bold = False
  323. def on_italic_button(self):
  324. if self.font_italic_tb.isChecked():
  325. self.text_input_entry.selectAll()
  326. self.text_input_entry.setFontItalic(True)
  327. self.font_italic = True
  328. else:
  329. self.text_input_entry.selectAll()
  330. self.text_input_entry.setFontItalic(False)
  331. self.font_italic = False
  332. def hide_tool(self):
  333. self.text_tool_frame.hide()
  334. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  335. self.app.ui.splitter.setSizes([0, 1])
  336. self.app.ui.notebook.setTabText(2, _("Tool"))
  337. class PaintOptionsTool(FlatCAMTool):
  338. """
  339. Inputs to specify how to paint the selected polygons.
  340. """
  341. toolName = "Paint Tool"
  342. def __init__(self, app, fcdraw):
  343. FlatCAMTool.__init__(self, app)
  344. self.app = app
  345. self.fcdraw = fcdraw
  346. # Title
  347. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  348. title_label.setStyleSheet("""
  349. QLabel
  350. {
  351. font-size: 16px;
  352. font-weight: bold;
  353. }
  354. """)
  355. self.layout.addWidget(title_label)
  356. grid = QtWidgets.QGridLayout()
  357. self.layout.addLayout(grid)
  358. # Tool dia
  359. ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
  360. ptdlabel.setToolTip(
  361. _("Diameter of the tool to\n"
  362. "be used in the operation.")
  363. )
  364. grid.addWidget(ptdlabel, 0, 0)
  365. self.painttooldia_entry = FCEntry()
  366. grid.addWidget(self.painttooldia_entry, 0, 1)
  367. # Overlap
  368. ovlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  369. ovlabel.setToolTip(
  370. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  371. "Example:\n"
  372. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  373. "Adjust the value starting with lower values\n"
  374. "and increasing it if areas that should be painted are still \n"
  375. "not painted.\n"
  376. "Lower values = faster processing, faster execution on PCB.\n"
  377. "Higher values = slow processing and slow execution on CNC\n"
  378. "due of too many paths.")
  379. )
  380. grid.addWidget(ovlabel, 1, 0)
  381. self.paintoverlap_entry = FCEntry()
  382. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  383. grid.addWidget(self.paintoverlap_entry, 1, 1)
  384. # Margin
  385. marginlabel = QtWidgets.QLabel(_('Margin:'))
  386. marginlabel.setToolTip(
  387. _("Distance by which to avoid\n"
  388. "the edges of the polygon to\n"
  389. "be painted.")
  390. )
  391. grid.addWidget(marginlabel, 2, 0)
  392. self.paintmargin_entry = FCEntry()
  393. grid.addWidget(self.paintmargin_entry, 2, 1)
  394. # Method
  395. methodlabel = QtWidgets.QLabel(_('Method:'))
  396. methodlabel.setToolTip(
  397. _("Algorithm to paint the polygon:<BR>"
  398. "<B>Standard</B>: Fixed step inwards.<BR>"
  399. "<B>Seed-based</B>: Outwards from seed.")
  400. )
  401. grid.addWidget(methodlabel, 3, 0)
  402. self.paintmethod_combo = RadioSet([
  403. {"label": _("Standard"), "value": "standard"},
  404. {"label": _("Seed-based"), "value": "seed"},
  405. {"label": _("Straight lines"), "value": "lines"}
  406. ], orientation='vertical', stretch=False)
  407. grid.addWidget(self.paintmethod_combo, 3, 1)
  408. # Connect lines
  409. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  410. pathconnectlabel.setToolTip(
  411. _("Draw lines between resulting\n"
  412. "segments to minimize tool lifts.")
  413. )
  414. grid.addWidget(pathconnectlabel, 4, 0)
  415. self.pathconnect_cb = FCCheckBox()
  416. grid.addWidget(self.pathconnect_cb, 4, 1)
  417. contourlabel = QtWidgets.QLabel(_("Contour:"))
  418. contourlabel.setToolTip(
  419. _("Cut around the perimeter of the polygon\n"
  420. "to trim rough edges.")
  421. )
  422. grid.addWidget(contourlabel, 5, 0)
  423. self.paintcontour_cb = FCCheckBox()
  424. grid.addWidget(self.paintcontour_cb, 5, 1)
  425. # Buttons
  426. hlay = QtWidgets.QHBoxLayout()
  427. self.layout.addLayout(hlay)
  428. hlay.addStretch()
  429. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  430. hlay.addWidget(self.paint_button)
  431. self.layout.addStretch()
  432. # Signals
  433. self.paint_button.clicked.connect(self.on_paint)
  434. self.set_tool_ui()
  435. def run(self):
  436. self.app.report_usage("Geo Editor ToolPaint()")
  437. FlatCAMTool.run(self)
  438. # if the splitter us hidden, display it
  439. if self.app.ui.splitter.sizes()[0] == 0:
  440. self.app.ui.splitter.setSizes([1, 1])
  441. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  442. def set_tool_ui(self):
  443. # Init GUI
  444. if self.app.defaults["tools_painttooldia"]:
  445. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  446. else:
  447. self.painttooldia_entry.set_value(0.0)
  448. if self.app.defaults["tools_paintoverlap"]:
  449. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  450. else:
  451. self.paintoverlap_entry.set_value(0.0)
  452. if self.app.defaults["tools_paintmargin"]:
  453. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  454. else:
  455. self.paintmargin_entry.set_value(0.0)
  456. if self.app.defaults["tools_paintmethod"]:
  457. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  458. else:
  459. self.paintmethod_combo.set_value("seed")
  460. if self.app.defaults["tools_pathconnect"]:
  461. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  462. else:
  463. self.pathconnect_cb.set_value(False)
  464. if self.app.defaults["tools_paintcontour"]:
  465. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  466. else:
  467. self.paintcontour_cb.set_value(False)
  468. def on_paint(self):
  469. if not self.fcdraw.selected:
  470. self.app.inform.emit(_("[WARNING_NOTCL] Paint cancelled. No shape selected."))
  471. return
  472. try:
  473. tooldia = float(self.painttooldia_entry.get_value())
  474. except ValueError:
  475. # try to convert comma to decimal point. if it's still not working error message and return
  476. try:
  477. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  478. self.painttooldia_entry.set_value(tooldia)
  479. except ValueError:
  480. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  481. "Add it and retry."))
  482. return
  483. try:
  484. overlap = float(self.paintoverlap_entry.get_value())
  485. except ValueError:
  486. # try to convert comma to decimal point. if it's still not working error message and return
  487. try:
  488. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  489. self.paintoverlap_entry.set_value(overlap)
  490. except ValueError:
  491. self.app.inform.emit(_("[WARNING_NOTCL] Overlap value is missing or wrong format. "
  492. "Add it and retry."))
  493. return
  494. try:
  495. margin = float(self.paintmargin_entry.get_value())
  496. except ValueError:
  497. # try to convert comma to decimal point. if it's still not working error message and return
  498. try:
  499. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  500. self.paintmargin_entry.set_value(margin)
  501. except ValueError:
  502. self.app.inform.emit(_("[WARNING_NOTCL] Margin distance value is missing or wrong format. "
  503. "Add it and retry."))
  504. return
  505. method = self.paintmethod_combo.get_value()
  506. contour = self.paintcontour_cb.get_value()
  507. connect = self.pathconnect_cb.get_value()
  508. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  509. self.fcdraw.select_tool("select")
  510. self.app.ui.notebook.setTabText(2, _("Tools"))
  511. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  512. self.app.ui.splitter.setSizes([0, 1])
  513. class TransformEditorTool(FlatCAMTool):
  514. """
  515. Inputs to specify how to paint the selected polygons.
  516. """
  517. toolName = _("Transform Tool")
  518. rotateName = _("Rotate")
  519. skewName = _("Skew/Shear")
  520. scaleName = _("Scale")
  521. flipName = _("Mirror (Flip)")
  522. offsetName = _("Offset")
  523. def __init__(self, app, draw_app):
  524. FlatCAMTool.__init__(self, app)
  525. self.app = app
  526. self.draw_app = draw_app
  527. self.transform_lay = QtWidgets.QVBoxLayout()
  528. self.layout.addLayout(self.transform_lay)
  529. # ## Title
  530. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  531. title_label.setStyleSheet("""
  532. QLabel
  533. {
  534. font-size: 16px;
  535. font-weight: bold;
  536. }
  537. """)
  538. self.transform_lay.addWidget(title_label)
  539. self.empty_label = QtWidgets.QLabel("")
  540. self.empty_label.setMinimumWidth(50)
  541. self.empty_label1 = QtWidgets.QLabel("")
  542. self.empty_label1.setMinimumWidth(70)
  543. self.empty_label2 = QtWidgets.QLabel("")
  544. self.empty_label2.setMinimumWidth(70)
  545. self.empty_label3 = QtWidgets.QLabel("")
  546. self.empty_label3.setMinimumWidth(70)
  547. self.empty_label4 = QtWidgets.QLabel("")
  548. self.empty_label4.setMinimumWidth(70)
  549. self.transform_lay.addWidget(self.empty_label)
  550. # Rotate Title
  551. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  552. self.transform_lay.addWidget(rotate_title_label)
  553. # Layout
  554. form_layout = QtWidgets.QFormLayout()
  555. self.transform_lay.addLayout(form_layout)
  556. form_child = QtWidgets.QHBoxLayout()
  557. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  558. self.rotate_label.setToolTip(
  559. _("Angle for Rotation action, in degrees.\n"
  560. "Float number between -360 and 359.\n"
  561. "Positive numbers for CW motion.\n"
  562. "Negative numbers for CCW motion.")
  563. )
  564. self.rotate_label.setFixedWidth(50)
  565. self.rotate_entry = FCEntry()
  566. # self.rotate_entry.setFixedWidth(60)
  567. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  568. self.rotate_button = FCButton()
  569. self.rotate_button.set_value(_("Rotate"))
  570. self.rotate_button.setToolTip(
  571. _("Rotate the selected shape(s).\n"
  572. "The point of reference is the middle of\n"
  573. "the bounding box for all selected shapes.")
  574. )
  575. self.rotate_button.setFixedWidth(60)
  576. form_child.addWidget(self.rotate_entry)
  577. form_child.addWidget(self.rotate_button)
  578. form_layout.addRow(self.rotate_label, form_child)
  579. self.transform_lay.addWidget(self.empty_label1)
  580. # Skew Title
  581. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  582. self.transform_lay.addWidget(skew_title_label)
  583. # Form Layout
  584. form1_layout = QtWidgets.QFormLayout()
  585. self.transform_lay.addLayout(form1_layout)
  586. form1_child_1 = QtWidgets.QHBoxLayout()
  587. form1_child_2 = QtWidgets.QHBoxLayout()
  588. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  589. self.skewx_label.setToolTip(
  590. _("Angle for Skew action, in degrees.\n"
  591. "Float number between -360 and 359.")
  592. )
  593. self.skewx_label.setFixedWidth(50)
  594. self.skewx_entry = FCEntry()
  595. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  596. # self.skewx_entry.setFixedWidth(60)
  597. self.skewx_button = FCButton()
  598. self.skewx_button.set_value(_("Skew X"))
  599. self.skewx_button.setToolTip(
  600. _("Skew/shear the selected shape(s).\n"
  601. "The point of reference is the middle of\n"
  602. "the bounding box for all selected shapes."))
  603. self.skewx_button.setFixedWidth(60)
  604. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  605. self.skewy_label.setToolTip(
  606. _("Angle for Skew action, in degrees.\n"
  607. "Float number between -360 and 359.")
  608. )
  609. self.skewy_label.setFixedWidth(50)
  610. self.skewy_entry = FCEntry()
  611. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  612. # self.skewy_entry.setFixedWidth(60)
  613. self.skewy_button = FCButton()
  614. self.skewy_button.set_value(_("Skew Y"))
  615. self.skewy_button.setToolTip(
  616. _("Skew/shear the selected shape(s).\n"
  617. "The point of reference is the middle of\n"
  618. "the bounding box for all selected shapes."))
  619. self.skewy_button.setFixedWidth(60)
  620. form1_child_1.addWidget(self.skewx_entry)
  621. form1_child_1.addWidget(self.skewx_button)
  622. form1_child_2.addWidget(self.skewy_entry)
  623. form1_child_2.addWidget(self.skewy_button)
  624. form1_layout.addRow(self.skewx_label, form1_child_1)
  625. form1_layout.addRow(self.skewy_label, form1_child_2)
  626. self.transform_lay.addWidget(self.empty_label2)
  627. # Scale Title
  628. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  629. self.transform_lay.addWidget(scale_title_label)
  630. # Form Layout
  631. form2_layout = QtWidgets.QFormLayout()
  632. self.transform_lay.addLayout(form2_layout)
  633. form2_child_1 = QtWidgets.QHBoxLayout()
  634. form2_child_2 = QtWidgets.QHBoxLayout()
  635. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  636. self.scalex_label.setToolTip(
  637. _("Factor for Scale action over X axis.")
  638. )
  639. self.scalex_label.setFixedWidth(50)
  640. self.scalex_entry = FCEntry()
  641. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  642. # self.scalex_entry.setFixedWidth(60)
  643. self.scalex_button = FCButton()
  644. self.scalex_button.set_value(_("Scale X"))
  645. self.scalex_button.setToolTip(
  646. _("Scale the selected shape(s).\n"
  647. "The point of reference depends on \n"
  648. "the Scale reference checkbox state."))
  649. self.scalex_button.setFixedWidth(60)
  650. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  651. self.scaley_label.setToolTip(
  652. _("Factor for Scale action over Y axis.")
  653. )
  654. self.scaley_label.setFixedWidth(50)
  655. self.scaley_entry = FCEntry()
  656. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  657. # self.scaley_entry.setFixedWidth(60)
  658. self.scaley_button = FCButton()
  659. self.scaley_button.set_value(_("Scale Y"))
  660. self.scaley_button.setToolTip(
  661. _("Scale the selected shape(s).\n"
  662. "The point of reference depends on \n"
  663. "the Scale reference checkbox state."))
  664. self.scaley_button.setFixedWidth(60)
  665. self.scale_link_cb = FCCheckBox()
  666. self.scale_link_cb.set_value(True)
  667. self.scale_link_cb.setText(_("Link"))
  668. self.scale_link_cb.setToolTip(
  669. _("Scale the selected shape(s)\n"
  670. "using the Scale Factor X for both axis."))
  671. self.scale_link_cb.setFixedWidth(50)
  672. self.scale_zero_ref_cb = FCCheckBox()
  673. self.scale_zero_ref_cb.set_value(True)
  674. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  675. self.scale_zero_ref_cb.setToolTip(
  676. _("Scale the selected shape(s)\n"
  677. "using the origin reference when checked,\n"
  678. "and the center of the biggest bounding box\n"
  679. "of the selected shapes when unchecked."))
  680. form2_child_1.addWidget(self.scalex_entry)
  681. form2_child_1.addWidget(self.scalex_button)
  682. form2_child_2.addWidget(self.scaley_entry)
  683. form2_child_2.addWidget(self.scaley_button)
  684. form2_layout.addRow(self.scalex_label, form2_child_1)
  685. form2_layout.addRow(self.scaley_label, form2_child_2)
  686. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  687. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  688. self.transform_lay.addWidget(self.empty_label3)
  689. # Offset Title
  690. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  691. self.transform_lay.addWidget(offset_title_label)
  692. # Form Layout
  693. form3_layout = QtWidgets.QFormLayout()
  694. self.transform_lay.addLayout(form3_layout)
  695. form3_child_1 = QtWidgets.QHBoxLayout()
  696. form3_child_2 = QtWidgets.QHBoxLayout()
  697. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  698. self.offx_label.setToolTip(
  699. _("Value for Offset action on X axis.")
  700. )
  701. self.offx_label.setFixedWidth(50)
  702. self.offx_entry = FCEntry()
  703. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  704. # self.offx_entry.setFixedWidth(60)
  705. self.offx_button = FCButton()
  706. self.offx_button.set_value(_("Offset X"))
  707. self.offx_button.setToolTip(
  708. _("Offset the selected shape(s).\n"
  709. "The point of reference is the middle of\n"
  710. "the bounding box for all selected shapes.\n")
  711. )
  712. self.offx_button.setFixedWidth(60)
  713. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  714. self.offy_label.setToolTip(
  715. _("Value for Offset action on Y axis.")
  716. )
  717. self.offy_label.setFixedWidth(50)
  718. self.offy_entry = FCEntry()
  719. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  720. # self.offy_entry.setFixedWidth(60)
  721. self.offy_button = FCButton()
  722. self.offy_button.set_value(_("Offset Y"))
  723. self.offy_button.setToolTip(
  724. _("Offset the selected shape(s).\n"
  725. "The point of reference is the middle of\n"
  726. "the bounding box for all selected shapes.\n")
  727. )
  728. self.offy_button.setFixedWidth(60)
  729. form3_child_1.addWidget(self.offx_entry)
  730. form3_child_1.addWidget(self.offx_button)
  731. form3_child_2.addWidget(self.offy_entry)
  732. form3_child_2.addWidget(self.offy_button)
  733. form3_layout.addRow(self.offx_label, form3_child_1)
  734. form3_layout.addRow(self.offy_label, form3_child_2)
  735. self.transform_lay.addWidget(self.empty_label4)
  736. # Flip Title
  737. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  738. self.transform_lay.addWidget(flip_title_label)
  739. # Form Layout
  740. form4_layout = QtWidgets.QFormLayout()
  741. form4_child_hlay = QtWidgets.QHBoxLayout()
  742. self.transform_lay.addLayout(form4_child_hlay)
  743. self.transform_lay.addLayout(form4_layout)
  744. form4_child_1 = QtWidgets.QHBoxLayout()
  745. self.flipx_button = FCButton()
  746. self.flipx_button.set_value(_("Flip on X"))
  747. self.flipx_button.setToolTip(
  748. _("Flip the selected shape(s) over the X axis.\n"
  749. "Does not create a new shape.")
  750. )
  751. self.flipx_button.setFixedWidth(60)
  752. self.flipy_button = FCButton()
  753. self.flipy_button.set_value(_("Flip on Y"))
  754. self.flipy_button.setToolTip(
  755. _("Flip the selected shape(s) over the X axis.\n"
  756. "Does not create a new shape.")
  757. )
  758. self.flipy_button.setFixedWidth(60)
  759. self.flip_ref_cb = FCCheckBox()
  760. self.flip_ref_cb.set_value(True)
  761. self.flip_ref_cb.setText(_("Ref Pt"))
  762. self.flip_ref_cb.setToolTip(
  763. _("Flip the selected shape(s)\n"
  764. "around the point in Point Entry Field.\n"
  765. "\n"
  766. "The point coordinates can be captured by\n"
  767. "left click on canvas together with pressing\n"
  768. "SHIFT key. \n"
  769. "Then click Add button to insert coordinates.\n"
  770. "Or enter the coords in format (x, y) in the\n"
  771. "Point Entry field and click Flip on X(Y)")
  772. )
  773. self.flip_ref_cb.setFixedWidth(50)
  774. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  775. self.flip_ref_label.setToolTip(
  776. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  777. "The 'x' in (x, y) will be used when using Flip on X and\n"
  778. "the 'y' in (x, y) will be used when using Flip on Y.")
  779. )
  780. self.flip_ref_label.setFixedWidth(50)
  781. self.flip_ref_entry = EvalEntry2("(0, 0)")
  782. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  783. # self.flip_ref_entry.setFixedWidth(60)
  784. self.flip_ref_button = FCButton()
  785. self.flip_ref_button.set_value(_("Add"))
  786. self.flip_ref_button.setToolTip(
  787. _("The point coordinates can be captured by\n"
  788. "left click on canvas together with pressing\n"
  789. "SHIFT key. Then click Add button to insert.")
  790. )
  791. self.flip_ref_button.setFixedWidth(60)
  792. form4_child_hlay.addStretch()
  793. form4_child_hlay.addWidget(self.flipx_button)
  794. form4_child_hlay.addWidget(self.flipy_button)
  795. form4_child_1.addWidget(self.flip_ref_entry)
  796. form4_child_1.addWidget(self.flip_ref_button)
  797. form4_layout.addRow(self.flip_ref_cb)
  798. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  799. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  800. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  801. self.transform_lay.addStretch()
  802. # Signals
  803. self.rotate_button.clicked.connect(self.on_rotate)
  804. self.skewx_button.clicked.connect(self.on_skewx)
  805. self.skewy_button.clicked.connect(self.on_skewy)
  806. self.scalex_button.clicked.connect(self.on_scalex)
  807. self.scaley_button.clicked.connect(self.on_scaley)
  808. self.offx_button.clicked.connect(self.on_offx)
  809. self.offy_button.clicked.connect(self.on_offy)
  810. self.flipx_button.clicked.connect(self.on_flipx)
  811. self.flipy_button.clicked.connect(self.on_flipy)
  812. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  813. self.rotate_entry.returnPressed.connect(self.on_rotate)
  814. self.skewx_entry.returnPressed.connect(self.on_skewx)
  815. self.skewy_entry.returnPressed.connect(self.on_skewy)
  816. self.scalex_entry.returnPressed.connect(self.on_scalex)
  817. self.scaley_entry.returnPressed.connect(self.on_scaley)
  818. self.offx_entry.returnPressed.connect(self.on_offx)
  819. self.offy_entry.returnPressed.connect(self.on_offy)
  820. self.set_tool_ui()
  821. def run(self):
  822. self.app.report_usage("Geo Editor Transform Tool()")
  823. FlatCAMTool.run(self)
  824. self.set_tool_ui()
  825. # if the splitter us hidden, display it
  826. if self.app.ui.splitter.sizes()[0] == 0:
  827. self.app.ui.splitter.setSizes([1, 1])
  828. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  829. def install(self, icon=None, separator=None, **kwargs):
  830. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  831. def set_tool_ui(self):
  832. # Initialize form
  833. if self.app.defaults["tools_transform_rotate"]:
  834. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  835. else:
  836. self.rotate_entry.set_value(0.0)
  837. if self.app.defaults["tools_transform_skew_x"]:
  838. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  839. else:
  840. self.skewx_entry.set_value(0.0)
  841. if self.app.defaults["tools_transform_skew_y"]:
  842. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  843. else:
  844. self.skewy_entry.set_value(0.0)
  845. if self.app.defaults["tools_transform_scale_x"]:
  846. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  847. else:
  848. self.scalex_entry.set_value(1.0)
  849. if self.app.defaults["tools_transform_scale_y"]:
  850. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  851. else:
  852. self.scaley_entry.set_value(1.0)
  853. if self.app.defaults["tools_transform_scale_link"]:
  854. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  855. else:
  856. self.scale_link_cb.set_value(True)
  857. if self.app.defaults["tools_transform_scale_reference"]:
  858. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  859. else:
  860. self.scale_zero_ref_cb.set_value(True)
  861. if self.app.defaults["tools_transform_offset_x"]:
  862. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  863. else:
  864. self.offx_entry.set_value(0.0)
  865. if self.app.defaults["tools_transform_offset_y"]:
  866. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  867. else:
  868. self.offy_entry.set_value(0.0)
  869. if self.app.defaults["tools_transform_mirror_reference"]:
  870. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  871. else:
  872. self.flip_ref_cb.set_value(False)
  873. if self.app.defaults["tools_transform_mirror_point"]:
  874. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  875. else:
  876. self.flip_ref_entry.set_value((0, 0))
  877. def template(self):
  878. if not self.fcdraw.selected:
  879. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  880. return
  881. self.draw_app.select_tool("select")
  882. self.app.ui.notebook.setTabText(2, "Tools")
  883. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  884. self.app.ui.splitter.setSizes([0, 1])
  885. def on_rotate(self, sig=None, val=None):
  886. if val:
  887. value = val
  888. else:
  889. try:
  890. value = float(self.rotate_entry.get_value())
  891. except ValueError:
  892. # try to convert comma to decimal point. if it's still not working error message and return
  893. try:
  894. value = float(self.rotate_entry.get_value().replace(',', '.'))
  895. except ValueError:
  896. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  897. "use a number."))
  898. return
  899. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  900. 'params': [value]})
  901. # self.on_rotate_action(value)
  902. return
  903. def on_flipx(self):
  904. # self.on_flip("Y")
  905. axis = 'Y'
  906. self.app.worker_task.emit({'fcn': self.on_flip,
  907. 'params': [axis]})
  908. return
  909. def on_flipy(self):
  910. # self.on_flip("X")
  911. axis = 'X'
  912. self.app.worker_task.emit({'fcn': self.on_flip,
  913. 'params': [axis]})
  914. return
  915. def on_flip_add_coords(self):
  916. val = self.app.clipboard.text()
  917. self.flip_ref_entry.set_value(val)
  918. def on_skewx(self, sig=None, val=None):
  919. if val:
  920. value = val
  921. else:
  922. try:
  923. value = float(self.skewx_entry.get_value())
  924. except ValueError:
  925. # try to convert comma to decimal point. if it's still not working error message and return
  926. try:
  927. value = float(self.skewx_entry.get_value().replace(',', '.'))
  928. except ValueError:
  929. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  930. "use a number."))
  931. return
  932. # self.on_skew("X", value)
  933. axis = 'X'
  934. self.app.worker_task.emit({'fcn': self.on_skew,
  935. 'params': [axis, value]})
  936. return
  937. def on_skewy(self, sig=None, val=None):
  938. if val:
  939. value = val
  940. else:
  941. try:
  942. value = float(self.skewy_entry.get_value())
  943. except ValueError:
  944. # try to convert comma to decimal point. if it's still not working error message and return
  945. try:
  946. value = float(self.skewy_entry.get_value().replace(',', '.'))
  947. except ValueError:
  948. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  949. "use a number."))
  950. return
  951. # self.on_skew("Y", value)
  952. axis = 'Y'
  953. self.app.worker_task.emit({'fcn': self.on_skew,
  954. 'params': [axis, value]})
  955. return
  956. def on_scalex(self, sig=None, val=None):
  957. if val:
  958. xvalue = val
  959. else:
  960. try:
  961. xvalue = float(self.scalex_entry.get_value())
  962. except ValueError:
  963. # try to convert comma to decimal point. if it's still not working error message and return
  964. try:
  965. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  966. except ValueError:
  967. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  968. "use a number."))
  969. return
  970. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  971. if xvalue == 0:
  972. xvalue = 1
  973. if self.scale_link_cb.get_value():
  974. yvalue = xvalue
  975. else:
  976. yvalue = 1
  977. axis = 'X'
  978. point = (0, 0)
  979. if self.scale_zero_ref_cb.get_value():
  980. self.app.worker_task.emit({'fcn': self.on_scale,
  981. 'params': [axis, xvalue, yvalue, point]})
  982. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  983. else:
  984. # self.on_scale("X", xvalue, yvalue)
  985. self.app.worker_task.emit({'fcn': self.on_scale,
  986. 'params': [axis, xvalue, yvalue]})
  987. return
  988. def on_scaley(self, sig=None, val=None):
  989. xvalue = 1
  990. if val:
  991. yvalue = val
  992. else:
  993. try:
  994. yvalue = float(self.scaley_entry.get_value())
  995. except ValueError:
  996. # try to convert comma to decimal point. if it's still not working error message and return
  997. try:
  998. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  999. except ValueError:
  1000. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  1001. "use a number."))
  1002. return
  1003. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  1004. if yvalue == 0:
  1005. yvalue = 1
  1006. axis = 'Y'
  1007. point = (0, 0)
  1008. if self.scale_zero_ref_cb.get_value():
  1009. self.app.worker_task.emit({'fcn': self.on_scale,
  1010. 'params': [axis, xvalue, yvalue, point]})
  1011. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1012. else:
  1013. # self.on_scale("Y", xvalue, yvalue)
  1014. self.app.worker_task.emit({'fcn': self.on_scale,
  1015. 'params': [axis, xvalue, yvalue]})
  1016. return
  1017. def on_offx(self, sig=None, val=None):
  1018. if val:
  1019. value = val
  1020. else:
  1021. try:
  1022. value = float(self.offx_entry.get_value())
  1023. except ValueError:
  1024. # try to convert comma to decimal point. if it's still not working error message and return
  1025. try:
  1026. value = float(self.offx_entry.get_value().replace(',', '.'))
  1027. except ValueError:
  1028. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  1029. "use a number."))
  1030. return
  1031. # self.on_offset("X", value)
  1032. axis = 'X'
  1033. self.app.worker_task.emit({'fcn': self.on_offset,
  1034. 'params': [axis, value]})
  1035. return
  1036. def on_offy(self, sig=None, val=None):
  1037. if val:
  1038. value = val
  1039. else:
  1040. try:
  1041. value = float(self.offy_entry.get_value())
  1042. except ValueError:
  1043. # try to convert comma to decimal point. if it's still not working error message and return
  1044. try:
  1045. value = float(self.offy_entry.get_value().replace(',', '.'))
  1046. except ValueError:
  1047. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  1048. "use a number."))
  1049. return
  1050. # self.on_offset("Y", value)
  1051. axis = 'Y'
  1052. self.app.worker_task.emit({'fcn': self.on_offset,
  1053. 'params': [axis, value]})
  1054. return
  1055. def on_rotate_action(self, num):
  1056. shape_list = self.draw_app.selected
  1057. xminlist = []
  1058. yminlist = []
  1059. xmaxlist = []
  1060. ymaxlist = []
  1061. if not shape_list:
  1062. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  1063. return
  1064. else:
  1065. with self.app.proc_container.new(_("Appying Rotate")):
  1066. try:
  1067. # first get a bounding box to fit all
  1068. for sha in shape_list:
  1069. xmin, ymin, xmax, ymax = sha.bounds()
  1070. xminlist.append(xmin)
  1071. yminlist.append(ymin)
  1072. xmaxlist.append(xmax)
  1073. ymaxlist.append(ymax)
  1074. # get the minimum x,y and maximum x,y for all objects selected
  1075. xminimal = min(xminlist)
  1076. yminimal = min(yminlist)
  1077. xmaximal = max(xmaxlist)
  1078. ymaximal = max(ymaxlist)
  1079. self.app.progress.emit(20)
  1080. for sel_sha in shape_list:
  1081. px = 0.5 * (xminimal + xmaximal)
  1082. py = 0.5 * (yminimal + ymaximal)
  1083. sel_sha.rotate(-num, point=(px, py))
  1084. self.draw_app.replot()
  1085. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1086. # self.draw_app.transform_complete.emit()
  1087. self.app.inform.emit(_("[success] Done. Rotate completed."))
  1088. self.app.progress.emit(100)
  1089. except Exception as e:
  1090. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  1091. return
  1092. def on_flip(self, axis):
  1093. shape_list = self.draw_app.selected
  1094. xminlist = []
  1095. yminlist = []
  1096. xmaxlist = []
  1097. ymaxlist = []
  1098. if not shape_list:
  1099. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  1100. return
  1101. else:
  1102. with self.app.proc_container.new(_("Applying Flip")):
  1103. try:
  1104. # get mirroring coords from the point entry
  1105. if self.flip_ref_cb.isChecked():
  1106. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1107. # get mirroing coords from the center of an all-enclosing bounding box
  1108. else:
  1109. # first get a bounding box to fit all
  1110. for sha in shape_list:
  1111. xmin, ymin, xmax, ymax = sha.bounds()
  1112. xminlist.append(xmin)
  1113. yminlist.append(ymin)
  1114. xmaxlist.append(xmax)
  1115. ymaxlist.append(ymax)
  1116. # get the minimum x,y and maximum x,y for all objects selected
  1117. xminimal = min(xminlist)
  1118. yminimal = min(yminlist)
  1119. xmaximal = max(xmaxlist)
  1120. ymaximal = max(ymaxlist)
  1121. px = 0.5 * (xminimal + xmaximal)
  1122. py = 0.5 * (yminimal + ymaximal)
  1123. self.app.progress.emit(20)
  1124. # execute mirroring
  1125. for sha in shape_list:
  1126. if axis is 'X':
  1127. sha.mirror('X', (px, py))
  1128. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  1129. elif axis is 'Y':
  1130. sha.mirror('Y', (px, py))
  1131. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  1132. self.draw_app.replot()
  1133. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1134. #
  1135. # self.draw_app.transform_complete.emit()
  1136. self.app.progress.emit(100)
  1137. except Exception as e:
  1138. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  1139. return
  1140. def on_skew(self, axis, num):
  1141. shape_list = self.draw_app.selected
  1142. xminlist = []
  1143. yminlist = []
  1144. if not shape_list:
  1145. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  1146. return
  1147. else:
  1148. with self.app.proc_container.new(_("Applying Skew")):
  1149. try:
  1150. # first get a bounding box to fit all
  1151. for sha in shape_list:
  1152. xmin, ymin, xmax, ymax = sha.bounds()
  1153. xminlist.append(xmin)
  1154. yminlist.append(ymin)
  1155. # get the minimum x,y and maximum x,y for all objects selected
  1156. xminimal = min(xminlist)
  1157. yminimal = min(yminlist)
  1158. self.app.progress.emit(20)
  1159. for sha in shape_list:
  1160. if axis is 'X':
  1161. sha.skew(num, 0, point=(xminimal, yminimal))
  1162. elif axis is 'Y':
  1163. sha.skew(0, num, point=(xminimal, yminimal))
  1164. self.draw_app.replot()
  1165. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1166. #
  1167. # self.draw_app.transform_complete.emit()
  1168. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  1169. self.app.progress.emit(100)
  1170. except Exception as e:
  1171. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  1172. return
  1173. def on_scale(self, axis, xfactor, yfactor, point=None):
  1174. shape_list = self.draw_app.selected
  1175. xminlist = []
  1176. yminlist = []
  1177. xmaxlist = []
  1178. ymaxlist = []
  1179. if not shape_list:
  1180. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  1181. return
  1182. else:
  1183. with self.app.proc_container.new(_("Applying Scale")):
  1184. try:
  1185. # first get a bounding box to fit all
  1186. for sha in shape_list:
  1187. xmin, ymin, xmax, ymax = sha.bounds()
  1188. xminlist.append(xmin)
  1189. yminlist.append(ymin)
  1190. xmaxlist.append(xmax)
  1191. ymaxlist.append(ymax)
  1192. # get the minimum x,y and maximum x,y for all objects selected
  1193. xminimal = min(xminlist)
  1194. yminimal = min(yminlist)
  1195. xmaximal = max(xmaxlist)
  1196. ymaximal = max(ymaxlist)
  1197. self.app.progress.emit(20)
  1198. if point is None:
  1199. px = 0.5 * (xminimal + xmaximal)
  1200. py = 0.5 * (yminimal + ymaximal)
  1201. else:
  1202. px = 0
  1203. py = 0
  1204. for sha in shape_list:
  1205. sha.scale(xfactor, yfactor, point=(px, py))
  1206. self.draw_app.replot()
  1207. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1208. #
  1209. # self.draw_app.transform_complete.emit()
  1210. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  1211. self.app.progress.emit(100)
  1212. except Exception as e:
  1213. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  1214. return
  1215. def on_offset(self, axis, num):
  1216. shape_list = self.draw_app.selected
  1217. xminlist = []
  1218. yminlist = []
  1219. if not shape_list:
  1220. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  1221. return
  1222. else:
  1223. with self.app.proc_container.new(_("Applying Offset")):
  1224. try:
  1225. self.app.progress.emit(20)
  1226. for sha in shape_list:
  1227. if axis is 'X':
  1228. sha.offset((num, 0))
  1229. elif axis is 'Y':
  1230. sha.offset((0, num))
  1231. self.draw_app.replot()
  1232. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  1233. self.app.progress.emit(100)
  1234. except Exception as e:
  1235. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  1236. return
  1237. def on_rotate_key(self):
  1238. val_box = FCInputDialog(title=_("Rotate ..."),
  1239. text=_('Enter an Angle Value (degrees):'),
  1240. min=-359.9999, max=360.0000, decimals=4,
  1241. init_val=float(self.app.defaults['tools_transform_rotate']))
  1242. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1243. val, ok = val_box.get_value()
  1244. if ok:
  1245. self.on_rotate(val=val)
  1246. self.app.inform.emit(
  1247. _("[success] Geometry shape rotate done...")
  1248. )
  1249. return
  1250. else:
  1251. self.app.inform.emit(
  1252. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  1253. )
  1254. def on_offx_key(self):
  1255. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1256. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1257. text=(_('Enter a distance Value (%s):') % str(units)),
  1258. min=-9999.9999, max=10000.0000, decimals=4,
  1259. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1260. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1261. val, ok = val_box.get_value()
  1262. if ok:
  1263. self.on_offx(val=val)
  1264. self.app.inform.emit(
  1265. _("[success] Geometry shape offset on X axis done..."))
  1266. return
  1267. else:
  1268. self.app.inform.emit(
  1269. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  1270. def on_offy_key(self):
  1271. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1272. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1273. text=(_('Enter a distance Value (%s):') % str(units)),
  1274. min=-9999.9999, max=10000.0000, decimals=4,
  1275. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1276. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1277. val, ok = val_box.get_value()
  1278. if ok:
  1279. self.on_offx(val=val)
  1280. self.app.inform.emit(
  1281. _("[success] Geometry shape offset on Y axis done..."))
  1282. return
  1283. else:
  1284. self.app.inform.emit(
  1285. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  1286. def on_skewx_key(self):
  1287. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1288. text=_('Enter an Angle Value (degrees):'),
  1289. min=-359.9999, max=360.0000, decimals=4,
  1290. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1291. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1292. val, ok = val_box.get_value()
  1293. if ok:
  1294. self.on_skewx(val=val)
  1295. self.app.inform.emit(
  1296. _("[success] Geometry shape skew on X axis done..."))
  1297. return
  1298. else:
  1299. self.app.inform.emit(
  1300. _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  1301. def on_skewy_key(self):
  1302. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1303. text=_('Enter an Angle Value (degrees):'),
  1304. min=-359.9999, max=360.0000, decimals=4,
  1305. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1306. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1307. val, ok = val_box.get_value()
  1308. if ok:
  1309. self.on_skewx(val=val)
  1310. self.app.inform.emit(
  1311. _("[success] Geometry shape skew on Y axis done..."))
  1312. return
  1313. else:
  1314. self.app.inform.emit(
  1315. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))
  1316. class DrawToolShape(object):
  1317. """
  1318. Encapsulates "shapes" under a common class.
  1319. """
  1320. tolerance = None
  1321. @staticmethod
  1322. def get_pts(o):
  1323. """
  1324. Returns a list of all points in the object, where
  1325. the object can be a Polygon, Not a polygon, or a list
  1326. of such. Search is done recursively.
  1327. :param: geometric object
  1328. :return: List of points
  1329. :rtype: list
  1330. """
  1331. pts = []
  1332. # Iterable: descend into each item.
  1333. try:
  1334. for subo in o:
  1335. pts += DrawToolShape.get_pts(subo)
  1336. # Non-iterable
  1337. except TypeError:
  1338. if o is not None:
  1339. # DrawToolShape: descend into .geo.
  1340. if isinstance(o, DrawToolShape):
  1341. pts += DrawToolShape.get_pts(o.geo)
  1342. # Descend into .exerior and .interiors
  1343. elif type(o) == Polygon:
  1344. pts += DrawToolShape.get_pts(o.exterior)
  1345. for i in o.interiors:
  1346. pts += DrawToolShape.get_pts(i)
  1347. elif type(o) == MultiLineString:
  1348. for line in o:
  1349. pts += DrawToolShape.get_pts(line)
  1350. # Has .coords: list them.
  1351. else:
  1352. if DrawToolShape.tolerance is not None:
  1353. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1354. else:
  1355. pts += list(o.coords)
  1356. else:
  1357. return
  1358. return pts
  1359. def __init__(self, geo=[]):
  1360. # Shapely type or list of such
  1361. self.geo = geo
  1362. self.utility = False
  1363. def get_all_points(self):
  1364. return DrawToolShape.get_pts(self)
  1365. def bounds(self):
  1366. """
  1367. Returns coordinates of rectangular bounds
  1368. of geometry: (xmin, ymin, xmax, ymax).
  1369. """
  1370. # fixed issue of getting bounds only for one level lists of objects
  1371. # now it can get bounds for nested lists of objects
  1372. def bounds_rec(shape_el):
  1373. if type(shape_el) is list:
  1374. minx = Inf
  1375. miny = Inf
  1376. maxx = -Inf
  1377. maxy = -Inf
  1378. for k in shape_el:
  1379. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1380. minx = min(minx, minx_)
  1381. miny = min(miny, miny_)
  1382. maxx = max(maxx, maxx_)
  1383. maxy = max(maxy, maxy_)
  1384. return minx, miny, maxx, maxy
  1385. else:
  1386. # it's a Shapely object, return it's bounds
  1387. return shape_el.bounds
  1388. bounds_coords = bounds_rec(self.geo)
  1389. return bounds_coords
  1390. def mirror(self, axis, point):
  1391. """
  1392. Mirrors the shape around a specified axis passing through
  1393. the given point.
  1394. :param axis: "X" or "Y" indicates around which axis to mirror.
  1395. :type axis: str
  1396. :param point: [x, y] point belonging to the mirror axis.
  1397. :type point: list
  1398. :return: None
  1399. """
  1400. px, py = point
  1401. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1402. def mirror_geom(shape_el):
  1403. if type(shape_el) is list:
  1404. new_obj = []
  1405. for g in shape_el:
  1406. new_obj.append(mirror_geom(g))
  1407. return new_obj
  1408. else:
  1409. return affinity.scale(shape_el, xscale, yscale, origin=(px, py))
  1410. try:
  1411. self.geo = mirror_geom(self.geo)
  1412. except AttributeError:
  1413. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1414. def rotate(self, angle, point):
  1415. """
  1416. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1417. Parameters
  1418. ----------
  1419. The angle of rotation are specified in degrees (default). Positive angles are
  1420. counter-clockwise and negative are clockwise rotations.
  1421. The point of origin can be a keyword 'center' for the bounding box
  1422. center (default), 'centroid' for the geometry's centroid, a Point object
  1423. or a coordinate tuple (x0, y0).
  1424. See shapely manual for more information:
  1425. http://toblerity.org/shapely/manual.html#affine-transformations
  1426. """
  1427. px, py = point
  1428. def rotate_geom(shape_el):
  1429. if type(shape_el) is list:
  1430. new_obj = []
  1431. for g in shape_el:
  1432. new_obj.append(rotate_geom(g))
  1433. return new_obj
  1434. else:
  1435. return affinity.rotate(shape_el, angle, origin=(px, py))
  1436. try:
  1437. self.geo = rotate_geom(self.geo)
  1438. except AttributeError:
  1439. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1440. def skew(self, angle_x, angle_y, point):
  1441. """
  1442. Shear/Skew a shape by angles along x and y dimensions.
  1443. Parameters
  1444. ----------
  1445. angle_x, angle_y : float, float
  1446. The shear angle(s) for the x and y axes respectively. These can be
  1447. specified in either degrees (default) or radians by setting
  1448. use_radians=True.
  1449. point: tuple of coordinates (x,y)
  1450. See shapely manual for more information:
  1451. http://toblerity.org/shapely/manual.html#affine-transformations
  1452. """
  1453. px, py = point
  1454. def skew_geom(shape_el):
  1455. if type(shape_el) is list:
  1456. new_obj = []
  1457. for g in shape_el:
  1458. new_obj.append(skew_geom(g))
  1459. return new_obj
  1460. else:
  1461. return affinity.skew(shape_el, angle_x, angle_y, origin=(px, py))
  1462. try:
  1463. self.geo = skew_geom(self.geo)
  1464. except AttributeError:
  1465. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1466. def offset(self, vect):
  1467. """
  1468. Offsets all shapes by a given vector/
  1469. :param vect: (x, y) vector by which to offset the shape geometry
  1470. :type vect: tuple
  1471. :return: None
  1472. :rtype: None
  1473. """
  1474. try:
  1475. dx, dy = vect
  1476. except TypeError:
  1477. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1478. "Probable you entered only one value in the Offset field.")
  1479. return
  1480. def translate_recursion(geom):
  1481. if type(geom) == list:
  1482. geoms = list()
  1483. for local_geom in geom:
  1484. geoms.append(translate_recursion(local_geom))
  1485. return geoms
  1486. else:
  1487. return affinity.translate(geom, xoff=dx, yoff=dy)
  1488. try:
  1489. self.geo = translate_recursion(self.geo)
  1490. except AttributeError:
  1491. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1492. def scale(self, xfactor, yfactor=None, point=None):
  1493. """
  1494. Scales all shape geometry by a given factor.
  1495. :param xfactor: Factor by which to scale the shape's geometry/
  1496. :type xfactor: float
  1497. :param yfactor: Factor by which to scale the shape's geometry/
  1498. :type yfactor: float
  1499. :return: None
  1500. :rtype: None
  1501. """
  1502. try:
  1503. xfactor = float(xfactor)
  1504. except:
  1505. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1506. return
  1507. if yfactor is None:
  1508. yfactor = xfactor
  1509. else:
  1510. try:
  1511. yfactor = float(yfactor)
  1512. except:
  1513. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1514. return
  1515. if point is None:
  1516. px = 0
  1517. py = 0
  1518. else:
  1519. px, py = point
  1520. def scale_recursion(geom):
  1521. if type(geom) == list:
  1522. geoms = list()
  1523. for local_geom in geom:
  1524. geoms.append(scale_recursion(local_geom))
  1525. return geoms
  1526. else:
  1527. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1528. try:
  1529. self.geo = scale_recursion(self.geo)
  1530. except AttributeError:
  1531. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1532. class DrawToolUtilityShape(DrawToolShape):
  1533. """
  1534. Utility shapes are temporary geometry in the editor
  1535. to assist in the creation of shapes. For example it
  1536. will show the outline of a rectangle from the first
  1537. point to the current mouse pointer before the second
  1538. point is clicked and the final geometry is created.
  1539. """
  1540. def __init__(self, geo=[]):
  1541. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1542. self.utility = True
  1543. class DrawTool(object):
  1544. """
  1545. Abstract Class representing a tool in the drawing
  1546. program. Can generate geometry, including temporary
  1547. utility geometry that is updated on user clicks
  1548. and mouse motion.
  1549. """
  1550. def __init__(self, draw_app):
  1551. self.draw_app = draw_app
  1552. self.complete = False
  1553. self.points = []
  1554. self.geometry = None # DrawToolShape or None
  1555. def click(self, point):
  1556. """
  1557. :param point: [x, y] Coordinate pair.
  1558. """
  1559. return ""
  1560. def click_release(self, point):
  1561. """
  1562. :param point: [x, y] Coordinate pair.
  1563. """
  1564. return ""
  1565. def on_key(self, key):
  1566. return None
  1567. def utility_geometry(self, data=None):
  1568. return None
  1569. def bounds(self, obj):
  1570. def bounds_rec(o):
  1571. if type(o) is list:
  1572. minx = Inf
  1573. miny = Inf
  1574. maxx = -Inf
  1575. maxy = -Inf
  1576. for k in o:
  1577. try:
  1578. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1579. except Exception as e:
  1580. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1581. return
  1582. minx = min(minx, minx_)
  1583. miny = min(miny, miny_)
  1584. maxx = max(maxx, maxx_)
  1585. maxy = max(maxy, maxy_)
  1586. return minx, miny, maxx, maxy
  1587. else:
  1588. # it's a Shapely object, return it's bounds
  1589. return o.geo.bounds
  1590. bounds_coords = bounds_rec(obj)
  1591. return bounds_coords
  1592. class FCShapeTool(DrawTool):
  1593. """
  1594. Abstract class for tools that create a shape.
  1595. """
  1596. def __init__(self, draw_app):
  1597. DrawTool.__init__(self, draw_app)
  1598. def make(self):
  1599. pass
  1600. class FCCircle(FCShapeTool):
  1601. """
  1602. Resulting type: Polygon
  1603. """
  1604. def __init__(self, draw_app):
  1605. DrawTool.__init__(self, draw_app)
  1606. self.name = 'circle'
  1607. try:
  1608. QtGui.QGuiApplication.restoreOverrideCursor()
  1609. except Exception as e:
  1610. pass
  1611. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_circle_geo.png'))
  1612. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1613. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1614. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1615. def click(self, point):
  1616. self.points.append(point)
  1617. if len(self.points) == 1:
  1618. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1619. return "Click on perimeter to complete ..."
  1620. if len(self.points) == 2:
  1621. self.make()
  1622. return "Done."
  1623. return ""
  1624. def utility_geometry(self, data=None):
  1625. if len(self.points) == 1:
  1626. p1 = self.points[0]
  1627. p2 = data
  1628. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1629. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1630. return None
  1631. def make(self):
  1632. try:
  1633. QtGui.QGuiApplication.restoreOverrideCursor()
  1634. except Exception as e:
  1635. pass
  1636. p1 = self.points[0]
  1637. p2 = self.points[1]
  1638. radius = distance(p1, p2)
  1639. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1640. self.complete = True
  1641. self.draw_app.app.inform.emit(_("[success] Done. Adding Circle completed."))
  1642. class FCArc(FCShapeTool):
  1643. def __init__(self, draw_app):
  1644. DrawTool.__init__(self, draw_app)
  1645. self.name = 'arc'
  1646. try:
  1647. QtGui.QGuiApplication.restoreOverrideCursor()
  1648. except Exception as e:
  1649. pass
  1650. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_arc.png'))
  1651. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1652. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1653. # Direction of rotation between point 1 and 2.
  1654. # 'cw' or 'ccw'. Switch direction by hitting the
  1655. # 'o' key.
  1656. self.direction = "cw"
  1657. # Mode
  1658. # C12 = Center, p1, p2
  1659. # 12C = p1, p2, Center
  1660. # 132 = p1, p3, p2
  1661. self.mode = "c12" # Center, p1, p2
  1662. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1663. def click(self, point):
  1664. self.points.append(point)
  1665. if len(self.points) == 1:
  1666. if self.mode == 'c12':
  1667. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1668. elif self.mode == '132':
  1669. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1670. else:
  1671. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1672. return "Click on 1st point ..."
  1673. if len(self.points) == 2:
  1674. if self.mode == 'c12':
  1675. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1676. elif self.mode == '132':
  1677. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1678. else:
  1679. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1680. return "Click on 2nd point to complete ..."
  1681. if len(self.points) == 3:
  1682. self.make()
  1683. return "Done."
  1684. return ""
  1685. def on_key(self, key):
  1686. if key == 'D' or key == QtCore.Qt.Key_D:
  1687. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1688. return _('Direction: %s') % self.direction.upper()
  1689. if key == 'M' or key == QtCore.Qt.Key_M:
  1690. # delete the possible points made before this action; we want to start anew
  1691. self.points[:] = []
  1692. # and delete the utility geometry made up until this point
  1693. self.draw_app.delete_utility_geometry()
  1694. if self.mode == 'c12':
  1695. self.mode = '12c'
  1696. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1697. elif self.mode == '12c':
  1698. self.mode = '132'
  1699. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1700. else:
  1701. self.mode = 'c12'
  1702. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1703. def utility_geometry(self, data=None):
  1704. if len(self.points) == 1: # Show the radius
  1705. center = self.points[0]
  1706. p1 = data
  1707. return DrawToolUtilityShape(LineString([center, p1]))
  1708. if len(self.points) == 2: # Show the arc
  1709. if self.mode == 'c12':
  1710. center = self.points[0]
  1711. p1 = self.points[1]
  1712. p2 = data
  1713. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1714. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1715. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1716. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1717. self.direction, self.steps_per_circ)),
  1718. Point(center)])
  1719. elif self.mode == '132':
  1720. p1 = array(self.points[0])
  1721. p3 = array(self.points[1])
  1722. p2 = array(data)
  1723. try:
  1724. center, radius, t = three_point_circle(p1, p2, p3)
  1725. except TypeError:
  1726. return
  1727. direction = 'cw' if sign(t) > 0 else 'ccw'
  1728. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1729. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1730. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1731. direction, self.steps_per_circ)),
  1732. Point(center), Point(p1), Point(p3)])
  1733. else: # '12c'
  1734. p1 = array(self.points[0])
  1735. p2 = array(self.points[1])
  1736. # Midpoint
  1737. a = (p1 + p2) / 2.0
  1738. # Parallel vector
  1739. c = p2 - p1
  1740. # Perpendicular vector
  1741. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1742. b /= numpy_norm(b)
  1743. # Distance
  1744. t = distance(data, a)
  1745. # Which side? Cross product with c.
  1746. # cross(M-A, B-A), where line is AB and M is test point.
  1747. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1748. t *= sign(side)
  1749. # Center = a + bt
  1750. center = a + b * t
  1751. radius = numpy_norm(center - p1)
  1752. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1753. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1754. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1755. self.direction, self.steps_per_circ)),
  1756. Point(center)])
  1757. return None
  1758. def make(self):
  1759. if self.mode == 'c12':
  1760. center = self.points[0]
  1761. p1 = self.points[1]
  1762. p2 = self.points[2]
  1763. radius = distance(center, p1)
  1764. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1765. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1766. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1767. self.direction, self.steps_per_circ)))
  1768. elif self.mode == '132':
  1769. p1 = array(self.points[0])
  1770. p3 = array(self.points[1])
  1771. p2 = array(self.points[2])
  1772. center, radius, t = three_point_circle(p1, p2, p3)
  1773. direction = 'cw' if sign(t) > 0 else 'ccw'
  1774. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1775. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1776. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1777. direction, self.steps_per_circ)))
  1778. else: # self.mode == '12c'
  1779. p1 = array(self.points[0])
  1780. p2 = array(self.points[1])
  1781. pc = array(self.points[2])
  1782. # Midpoint
  1783. a = (p1 + p2) / 2.0
  1784. # Parallel vector
  1785. c = p2 - p1
  1786. # Perpendicular vector
  1787. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1788. b /= numpy_norm(b)
  1789. # Distance
  1790. t = distance(pc, a)
  1791. # Which side? Cross product with c.
  1792. # cross(M-A, B-A), where line is AB and M is test point.
  1793. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1794. t *= sign(side)
  1795. # Center = a + bt
  1796. center = a + b * t
  1797. radius = numpy_norm(center - p1)
  1798. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1799. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1800. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1801. self.direction, self.steps_per_circ)))
  1802. self.complete = True
  1803. self.draw_app.app.inform.emit(_("[success] Done. Arc completed."))
  1804. class FCRectangle(FCShapeTool):
  1805. """
  1806. Resulting type: Polygon
  1807. """
  1808. def __init__(self, draw_app):
  1809. DrawTool.__init__(self, draw_app)
  1810. self.name = 'rectangle'
  1811. try:
  1812. QtGui.QGuiApplication.restoreOverrideCursor()
  1813. except Exception as e:
  1814. pass
  1815. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1816. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1817. self.draw_app.app.inform.emit( _("Click on 1st corner ..."))
  1818. def click(self, point):
  1819. self.points.append(point)
  1820. if len(self.points) == 1:
  1821. self.draw_app.app.inform.emit(_("Click on opposite corner to complete ..."))
  1822. return "Click on opposite corner to complete ..."
  1823. if len(self.points) == 2:
  1824. self.make()
  1825. return "Done."
  1826. return ""
  1827. def utility_geometry(self, data=None):
  1828. if len(self.points) == 1:
  1829. p1 = self.points[0]
  1830. p2 = data
  1831. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1832. return None
  1833. def make(self):
  1834. try:
  1835. QtGui.QGuiApplication.restoreOverrideCursor()
  1836. except Exception as e:
  1837. pass
  1838. p1 = self.points[0]
  1839. p2 = self.points[1]
  1840. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1841. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1842. self.complete = True
  1843. self.draw_app.app.inform.emit(_("[success] Done. Rectangle completed."))
  1844. class FCPolygon(FCShapeTool):
  1845. """
  1846. Resulting type: Polygon
  1847. """
  1848. def __init__(self, draw_app):
  1849. DrawTool.__init__(self, draw_app)
  1850. self.name = 'polygon'
  1851. try:
  1852. QtGui.QGuiApplication.restoreOverrideCursor()
  1853. except Exception as e:
  1854. pass
  1855. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1856. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1857. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1858. def click(self, point):
  1859. self.draw_app.in_action = True
  1860. self.points.append(point)
  1861. if len(self.points) > 0:
  1862. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1863. return "Click on next point or hit ENTER to complete ..."
  1864. return ""
  1865. def utility_geometry(self, data=None):
  1866. if len(self.points) == 1:
  1867. temp_points = [x for x in self.points]
  1868. temp_points.append(data)
  1869. return DrawToolUtilityShape(LineString(temp_points))
  1870. if len(self.points) > 1:
  1871. temp_points = [x for x in self.points]
  1872. temp_points.append(data)
  1873. return DrawToolUtilityShape(LinearRing(temp_points))
  1874. return None
  1875. def make(self):
  1876. try:
  1877. QtGui.QGuiApplication.restoreOverrideCursor()
  1878. except Exception as e:
  1879. pass
  1880. # self.geometry = LinearRing(self.points)
  1881. self.geometry = DrawToolShape(Polygon(self.points))
  1882. self.draw_app.in_action = False
  1883. self.complete = True
  1884. self.draw_app.app.inform.emit(_("[success] Done. Polygon completed."))
  1885. def on_key(self, key):
  1886. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1887. if len(self.points) > 0:
  1888. self.points = self.points[0:-1]
  1889. # Remove any previous utility shape
  1890. self.draw_app.tool_shape.clear(update=False)
  1891. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1892. self.draw_app.draw_utility_geometry(geo=geo)
  1893. return _("Backtracked one point ...")
  1894. class FCPath(FCPolygon):
  1895. """
  1896. Resulting type: LineString
  1897. """
  1898. def __init__(self, draw_app):
  1899. FCPolygon.__init__(self, draw_app)
  1900. try:
  1901. QtGui.QGuiApplication.restoreOverrideCursor()
  1902. except Exception as e:
  1903. pass
  1904. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path5.png'))
  1905. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1906. def make(self):
  1907. self.geometry = DrawToolShape(LineString(self.points))
  1908. self.name = 'path'
  1909. try:
  1910. QtGui.QGuiApplication.restoreOverrideCursor()
  1911. except Exception as e:
  1912. pass
  1913. self.draw_app.in_action = False
  1914. self.complete = True
  1915. self.draw_app.app.inform.emit(_("[success] Done. Path completed."))
  1916. def utility_geometry(self, data=None):
  1917. if len(self.points) > 0:
  1918. temp_points = [x for x in self.points]
  1919. temp_points.append(data)
  1920. return DrawToolUtilityShape(LineString(temp_points))
  1921. return None
  1922. def on_key(self, key):
  1923. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1924. if len(self.points) > 0:
  1925. self.points = self.points[0:-1]
  1926. # Remove any previous utility shape
  1927. self.draw_app.tool_shape.clear(update=False)
  1928. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1929. self.draw_app.draw_utility_geometry(geo=geo)
  1930. return _("Backtracked one point ...")
  1931. class FCSelect(DrawTool):
  1932. def __init__(self, draw_app):
  1933. DrawTool.__init__(self, draw_app)
  1934. self.name = 'select'
  1935. try:
  1936. QtGui.QGuiApplication.restoreOverrideCursor()
  1937. except Exception as e:
  1938. pass
  1939. self.storage = self.draw_app.storage
  1940. # self.shape_buffer = self.draw_app.shape_buffer
  1941. # self.selected = self.draw_app.selected
  1942. def click_release(self, point):
  1943. self.select_shapes(point)
  1944. return ""
  1945. def select_shapes(self, pos):
  1946. # list where we store the overlapped shapes under our mouse left click position
  1947. over_shape_list = []
  1948. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1949. for obj_shape in self.storage.get_objects():
  1950. # first method of click selection -> inconvenient
  1951. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1952. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1953. # over_shape_list.append(obj_shape)
  1954. # second method of click selection -> slow
  1955. # outside = obj_shape.geo.buffer(0.1)
  1956. # inside = obj_shape.geo.buffer(-0.1)
  1957. # shape_band = outside.difference(inside)
  1958. # if Point(pos).within(shape_band):
  1959. # over_shape_list.append(obj_shape)
  1960. # 3rd method of click selection -> inconvenient
  1961. try:
  1962. _, closest_shape = self.storage.nearest(pos)
  1963. except StopIteration:
  1964. return ""
  1965. over_shape_list.append(closest_shape)
  1966. try:
  1967. # if there is no shape under our click then deselect all shapes
  1968. # it will not work for 3rd method of click selection
  1969. if not over_shape_list:
  1970. self.draw_app.selected = []
  1971. FlatCAMGeoEditor.draw_shape_idx = -1
  1972. else:
  1973. # if there are shapes under our click then advance through the list of them, one at the time in a
  1974. # circular way
  1975. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1976. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1977. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1978. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1979. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1980. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1981. if key_modifier == Qt.ControlModifier:
  1982. if obj_to_add in self.draw_app.selected:
  1983. self.draw_app.selected.remove(obj_to_add)
  1984. else:
  1985. self.draw_app.selected.append(obj_to_add)
  1986. else:
  1987. self.draw_app.selected = []
  1988. self.draw_app.selected.append(obj_to_add)
  1989. else:
  1990. if key_modifier == Qt.ShiftModifier:
  1991. if obj_to_add in self.draw_app.selected:
  1992. self.draw_app.selected.remove(obj_to_add)
  1993. else:
  1994. self.draw_app.selected.append(obj_to_add)
  1995. else:
  1996. self.draw_app.selected = []
  1997. self.draw_app.selected.append(obj_to_add)
  1998. except Exception as e:
  1999. log.error("[ERROR] Something went bad. %s" % str(e))
  2000. raise
  2001. class FCMove(FCShapeTool):
  2002. def __init__(self, draw_app):
  2003. FCShapeTool.__init__(self, draw_app)
  2004. self.name = 'move'
  2005. try:
  2006. QtGui.QGuiApplication.restoreOverrideCursor()
  2007. except Exception as e:
  2008. pass
  2009. self.storage = self.draw_app.storage
  2010. self.origin = None
  2011. self.destination = None
  2012. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2013. self.selection_shape = self.selection_bbox()
  2014. if len(self.draw_app.get_selected()) == 0:
  2015. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] MOVE: No shape selected. Select a shape to move ..."))
  2016. else:
  2017. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2018. def set_origin(self, origin):
  2019. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2020. self.origin = origin
  2021. def click(self, point):
  2022. if len(self.draw_app.get_selected()) == 0:
  2023. # self.complete = True
  2024. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2025. self.select_shapes(point)
  2026. self.draw_app.replot()
  2027. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2028. return
  2029. if self.origin is None:
  2030. self.set_origin(point)
  2031. self.selection_shape = self.selection_bbox()
  2032. return "Click on final location."
  2033. else:
  2034. self.destination = point
  2035. self.make()
  2036. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2037. # 'params': []}))
  2038. return "Done."
  2039. def make(self):
  2040. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2041. # Create new geometry
  2042. dx = self.destination[0] - self.origin[0]
  2043. dy = self.destination[1] - self.origin[1]
  2044. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2045. for geom in self.draw_app.get_selected()]
  2046. # Delete old
  2047. self.draw_app.delete_selected()
  2048. self.complete = True
  2049. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Move completed."))
  2050. def selection_bbox(self):
  2051. geo_list = []
  2052. for select_shape in self.draw_app.get_selected():
  2053. geometric_data = select_shape.geo
  2054. try:
  2055. for g in geometric_data:
  2056. geo_list.append(g)
  2057. except TypeError:
  2058. geo_list.append(geometric_data)
  2059. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2060. pt1 = (xmin, ymin)
  2061. pt2 = (xmax, ymin)
  2062. pt3 = (xmax, ymax)
  2063. pt4 = (xmin, ymax)
  2064. return Polygon([pt1, pt2, pt3, pt4])
  2065. def utility_geometry(self, data=None):
  2066. """
  2067. Temporary geometry on screen while using this tool.
  2068. :param data:
  2069. :return:
  2070. """
  2071. geo_list = []
  2072. if self.origin is None:
  2073. return None
  2074. if len(self.draw_app.get_selected()) == 0:
  2075. return None
  2076. dx = data[0] - self.origin[0]
  2077. dy = data[1] - self.origin[1]
  2078. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2079. try:
  2080. for geom in self.draw_app.get_selected():
  2081. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2082. except AttributeError:
  2083. self.draw_app.select_tool('select')
  2084. self.draw_app.selected = []
  2085. return
  2086. return DrawToolUtilityShape(geo_list)
  2087. else:
  2088. try:
  2089. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2090. except ValueError:
  2091. ss_el = None
  2092. return DrawToolUtilityShape(ss_el)
  2093. def select_shapes(self, pos):
  2094. # list where we store the overlapped shapes under our mouse left click position
  2095. over_shape_list = []
  2096. try:
  2097. _, closest_shape = self.storage.nearest(pos)
  2098. except StopIteration:
  2099. return ""
  2100. over_shape_list.append(closest_shape)
  2101. try:
  2102. # if there is no shape under our click then deselect all shapes
  2103. # it will not work for 3rd method of click selection
  2104. if not over_shape_list:
  2105. self.draw_app.selected = []
  2106. self.draw_app.draw_shape_idx = -1
  2107. else:
  2108. # if there are shapes under our click then advance through the list of them, one at the time in a
  2109. # circular way
  2110. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2111. try:
  2112. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2113. except IndexError:
  2114. return
  2115. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2116. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2117. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2118. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2119. if key_modifier == Qt.ControlModifier:
  2120. if obj_to_add in self.draw_app.selected:
  2121. self.draw_app.selected.remove(obj_to_add)
  2122. else:
  2123. self.draw_app.selected.append(obj_to_add)
  2124. else:
  2125. self.draw_app.selected = []
  2126. self.draw_app.selected.append(obj_to_add)
  2127. else:
  2128. if key_modifier == Qt.ShiftModifier:
  2129. if obj_to_add in self.draw_app.selected:
  2130. self.draw_app.selected.remove(obj_to_add)
  2131. else:
  2132. self.draw_app.selected.append(obj_to_add)
  2133. else:
  2134. self.draw_app.selected = []
  2135. self.draw_app.selected.append(obj_to_add)
  2136. except Exception as e:
  2137. log.error("[ERROR] Something went bad. %s" % str(e))
  2138. raise
  2139. class FCCopy(FCMove):
  2140. def __init__(self, draw_app):
  2141. FCMove.__init__(self, draw_app)
  2142. self.name = 'copy'
  2143. def make(self):
  2144. # Create new geometry
  2145. dx = self.destination[0] - self.origin[0]
  2146. dy = self.destination[1] - self.origin[1]
  2147. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2148. for geom in self.draw_app.get_selected()]
  2149. self.complete = True
  2150. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Copy completed."))
  2151. class FCText(FCShapeTool):
  2152. def __init__(self, draw_app):
  2153. FCShapeTool.__init__(self, draw_app)
  2154. self.name = 'text'
  2155. try:
  2156. QtGui.QGuiApplication.restoreOverrideCursor()
  2157. except Exception as e:
  2158. pass
  2159. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_text.png'))
  2160. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2161. # self.shape_buffer = self.draw_app.shape_buffer
  2162. self.draw_app = draw_app
  2163. self.app = draw_app.app
  2164. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  2165. self.origin = (0, 0)
  2166. self.text_gui = TextInputTool(self.app)
  2167. self.text_gui.run()
  2168. def click(self, point):
  2169. # Create new geometry
  2170. dx = point[0]
  2171. dy = point[1]
  2172. if self.text_gui.text_path:
  2173. try:
  2174. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2175. except Exception as e:
  2176. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2177. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2178. "supported. Error: %s") % str(e))
  2179. self.text_gui.text_path = []
  2180. self.text_gui.hide_tool()
  2181. self.draw_app.select_tool('select')
  2182. return
  2183. else:
  2184. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] No text to add."))
  2185. return
  2186. self.text_gui.text_path = []
  2187. self.text_gui.hide_tool()
  2188. self.complete = True
  2189. self.draw_app.app.inform.emit(_("[success] Done. Adding Text completed."))
  2190. def utility_geometry(self, data=None):
  2191. """
  2192. Temporary geometry on screen while using this tool.
  2193. :param data: mouse position coords
  2194. :return:
  2195. """
  2196. dx = data[0] - self.origin[0]
  2197. dy = data[1] - self.origin[1]
  2198. try:
  2199. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2200. except:
  2201. return
  2202. class FCBuffer(FCShapeTool):
  2203. def __init__(self, draw_app):
  2204. FCShapeTool.__init__(self, draw_app)
  2205. self.name = 'buffer'
  2206. # self.shape_buffer = self.draw_app.shape_buffer
  2207. self.draw_app = draw_app
  2208. self.app = draw_app.app
  2209. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2210. self.origin = (0, 0)
  2211. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2212. self.buff_tool.run()
  2213. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2214. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2215. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2216. self.activate()
  2217. def on_buffer(self):
  2218. if not self.draw_app.selected:
  2219. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2220. return
  2221. try:
  2222. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2223. except ValueError:
  2224. # try to convert comma to decimal point. if it's still not working error message and return
  2225. try:
  2226. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2227. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2228. except ValueError:
  2229. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2230. "Add it and retry."))
  2231. return
  2232. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2233. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2234. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2235. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2236. self.app.ui.notebook.setTabText(2, _("Tools"))
  2237. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2238. self.disactivate()
  2239. if ret_val == 'fail':
  2240. return
  2241. self.draw_app.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2242. def on_buffer_int(self):
  2243. if not self.draw_app.selected:
  2244. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2245. return
  2246. try:
  2247. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2248. except ValueError:
  2249. # try to convert comma to decimal point. if it's still not working error message and return
  2250. try:
  2251. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2252. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2253. except ValueError:
  2254. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2255. "Add it and retry."))
  2256. return
  2257. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2258. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2259. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2260. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2261. self.app.ui.notebook.setTabText(2, _("Tools"))
  2262. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2263. self.disactivate()
  2264. if ret_val == 'fail':
  2265. return
  2266. self.draw_app.app.inform.emit(_("[success] Done. Buffer Int Tool completed."))
  2267. def on_buffer_ext(self):
  2268. if not self.draw_app.selected:
  2269. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2270. return
  2271. try:
  2272. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2273. except ValueError:
  2274. # try to convert comma to decimal point. if it's still not working error message and return
  2275. try:
  2276. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2277. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2278. except ValueError:
  2279. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2280. "Add it and retry."))
  2281. return
  2282. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2283. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2284. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2285. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2286. self.app.ui.notebook.setTabText(2, _("Tools"))
  2287. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2288. self.disactivate()
  2289. if ret_val == 'fail':
  2290. return
  2291. self.draw_app.app.inform.emit(_("[success] Done. Buffer Ext Tool completed."))
  2292. def activate(self):
  2293. self.buff_tool.buffer_button.clicked.disconnect()
  2294. self.buff_tool.buffer_int_button.clicked.disconnect()
  2295. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2296. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2297. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2298. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2299. def disactivate(self):
  2300. self.buff_tool.buffer_button.clicked.disconnect()
  2301. self.buff_tool.buffer_int_button.clicked.disconnect()
  2302. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2303. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2304. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2305. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2306. self.complete = True
  2307. self.draw_app.select_tool("select")
  2308. self.buff_tool.hide_tool()
  2309. class FCEraser(FCShapeTool):
  2310. def __init__(self, draw_app):
  2311. DrawTool.__init__(self, draw_app)
  2312. self.name = 'eraser'
  2313. self.origin = None
  2314. self.destination = None
  2315. if len(self.draw_app.get_selected()) == 0:
  2316. if self.draw_app.launched_from_shortcuts is True:
  2317. self.draw_app.launched_from_shortcuts = False
  2318. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2319. else:
  2320. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2321. self.geometry = []
  2322. self.storage = self.draw_app.storage
  2323. # Switch notebook to Selected page
  2324. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2325. def set_origin(self, origin):
  2326. self.origin = origin
  2327. def click(self, point):
  2328. if len(self.draw_app.get_selected()) == 0:
  2329. for obj_shape in self.storage.get_objects():
  2330. try:
  2331. __, closest_shape = self.storage.nearest(point)
  2332. self.draw_app.selected.append(closest_shape)
  2333. except StopIteration:
  2334. if len(self.draw_app.selected) > 0:
  2335. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2336. return ""
  2337. if len(self.draw_app.get_selected()) == 0:
  2338. return "Nothing to ersase."
  2339. else:
  2340. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2341. if self.origin is None:
  2342. self.set_origin(point)
  2343. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2344. return
  2345. else:
  2346. self.destination = point
  2347. self.make()
  2348. # self.draw_app.select_tool("select")
  2349. return
  2350. def make(self):
  2351. eraser_sel_shapes = []
  2352. # create the eraser shape from selection
  2353. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2354. temp_shape = eraser_shape.buffer(0.0000001)
  2355. temp_shape = Polygon(temp_shape.exterior)
  2356. eraser_sel_shapes.append(temp_shape)
  2357. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2358. for obj_shape in self.storage.get_objects():
  2359. try:
  2360. geometric_data = obj_shape.geo
  2361. if eraser_sel_shapes.intersects(geometric_data):
  2362. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2363. except KeyError:
  2364. pass
  2365. self.draw_app.delete_utility_geometry()
  2366. self.draw_app.plot_all()
  2367. self.draw_app.app.inform.emit(_("[success] Done. Eraser tool action completed."))
  2368. def utility_geometry(self, data=None):
  2369. """
  2370. Temporary geometry on screen while using this tool.
  2371. :param data:
  2372. :return:
  2373. """
  2374. geo_list = []
  2375. if self.origin is None:
  2376. return None
  2377. if len(self.draw_app.get_selected()) == 0:
  2378. return None
  2379. dx = data[0] - self.origin[0]
  2380. dy = data[1] - self.origin[1]
  2381. try:
  2382. for geom in self.draw_app.get_selected():
  2383. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2384. except AttributeError:
  2385. self.draw_app.select_tool('select')
  2386. self.draw_app.selected = []
  2387. return
  2388. return DrawToolUtilityShape(geo_list)
  2389. def clean_up(self):
  2390. self.draw_app.selected = []
  2391. self.draw_app.plot_all()
  2392. class FCPaint(FCShapeTool):
  2393. def __init__(self, draw_app):
  2394. FCShapeTool.__init__(self, draw_app)
  2395. self.name = 'paint'
  2396. # self.shape_buffer = self.draw_app.shape_buffer
  2397. self.draw_app = draw_app
  2398. self.app = draw_app.app
  2399. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2400. self.origin = (0, 0)
  2401. self.draw_app.paint_tool.run()
  2402. class FCTransform(FCShapeTool):
  2403. def __init__(self, draw_app):
  2404. FCShapeTool.__init__(self, draw_app)
  2405. self.name = 'transformation'
  2406. # self.shape_buffer = self.draw_app.shape_buffer
  2407. self.draw_app = draw_app
  2408. self.app = draw_app.app
  2409. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2410. self.origin = (0, 0)
  2411. self.draw_app.transform_tool.run()
  2412. # ###############################################
  2413. # ################ Main Application #############
  2414. # ###############################################
  2415. class FlatCAMGeoEditor(QtCore.QObject):
  2416. transform_complete = QtCore.pyqtSignal()
  2417. draw_shape_idx = -1
  2418. def __init__(self, app, disabled=False):
  2419. assert isinstance(app, FlatCAMApp.App), \
  2420. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2421. super(FlatCAMGeoEditor, self).__init__()
  2422. self.app = app
  2423. self.canvas = app.plotcanvas
  2424. # ## Toolbar events and properties
  2425. self.tools = {
  2426. "select": {"button": self.app.ui.geo_select_btn,
  2427. "constructor": FCSelect},
  2428. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2429. "constructor": FCArc},
  2430. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2431. "constructor": FCCircle},
  2432. "path": {"button": self.app.ui.geo_add_path_btn,
  2433. "constructor": FCPath},
  2434. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2435. "constructor": FCRectangle},
  2436. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2437. "constructor": FCPolygon},
  2438. "text": {"button": self.app.ui.geo_add_text_btn,
  2439. "constructor": FCText},
  2440. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2441. "constructor": FCBuffer},
  2442. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2443. "constructor": FCPaint},
  2444. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2445. "constructor": FCEraser},
  2446. "move": {"button": self.app.ui.geo_move_btn,
  2447. "constructor": FCMove},
  2448. "transform": {"button": self.app.ui.geo_transform_btn,
  2449. "constructor": FCTransform},
  2450. "copy": {"button": self.app.ui.geo_copy_btn,
  2451. "constructor": FCCopy}
  2452. }
  2453. # # ## Data
  2454. self.active_tool = None
  2455. self.storage = FlatCAMGeoEditor.make_storage()
  2456. self.utility = []
  2457. # VisPy visuals
  2458. self.fcgeometry = None
  2459. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2460. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2461. self.app.pool_recreated.connect(self.pool_recreated)
  2462. # Remove from scene
  2463. self.shapes.enabled = False
  2464. self.tool_shape.enabled = False
  2465. # List of selected shapes.
  2466. self.selected = []
  2467. self.flat_geo = []
  2468. self.move_timer = QtCore.QTimer()
  2469. self.move_timer.setSingleShot(True)
  2470. # this var will store the state of the toolbar before starting the editor
  2471. self.toolbar_old_state = False
  2472. self.key = None # Currently pressed key
  2473. self.geo_key_modifiers = None
  2474. self.x = None # Current mouse cursor pos
  2475. self.y = None
  2476. # if we edit a multigeo geometry store here the tool number
  2477. self.multigeo_tool = None
  2478. # Current snapped mouse pos
  2479. self.snap_x = None
  2480. self.snap_y = None
  2481. self.pos = None
  2482. # signal that there is an action active like polygon or path
  2483. self.in_action = False
  2484. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2485. self.launched_from_shortcuts = False
  2486. def make_callback(thetool):
  2487. def f():
  2488. self.on_tool_select(thetool)
  2489. return f
  2490. for tool in self.tools:
  2491. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2492. self.tools[tool]["button"].setCheckable(True) # Checkable
  2493. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2494. self.app.ui.corner_snap_btn.setCheckable(True)
  2495. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2496. self.options = {
  2497. "global_gridx": 0.1,
  2498. "global_gridy": 0.1,
  2499. "global_snap_max": 0.05,
  2500. "grid_snap": True,
  2501. "corner_snap": False,
  2502. "grid_gap_link": True
  2503. }
  2504. self.app.options_read_form()
  2505. for option in self.options:
  2506. if option in self.app.options:
  2507. self.options[option] = self.app.options[option]
  2508. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2509. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2510. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2511. self.app.ui.grid_gap_link_cb.setChecked(True)
  2512. self.rtree_index = rtindex.Index()
  2513. def entry2option(option, entry):
  2514. try:
  2515. self.options[option] = float(entry.text())
  2516. except Exception as e:
  2517. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2518. return
  2519. def gridx_changed(goption, gentry):
  2520. entry2option(option=goption, entry=gentry)
  2521. # if the grid link is checked copy the value in the GridX field to GridY
  2522. try:
  2523. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2524. except ValueError:
  2525. return
  2526. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2527. dec = 6 if units == 'IN' else 4
  2528. if self.app.ui.grid_gap_link_cb.isChecked():
  2529. self.app.ui.grid_gap_y_entry.set_value(val, decimals=dec)
  2530. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2531. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2532. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2533. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2534. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2535. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2536. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2537. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2538. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2539. # if using Paint store here the tool diameter used
  2540. self.paint_tooldia = None
  2541. self.paint_tool = PaintOptionsTool(self.app, self)
  2542. self.transform_tool = TransformEditorTool(self.app, self)
  2543. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2544. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2545. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2546. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2547. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2548. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2549. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2550. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2551. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2552. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2553. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2554. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2555. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2556. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2557. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2558. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2559. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2560. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2561. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2562. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2563. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2564. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2565. self.transform_complete.connect(self.on_transform_complete)
  2566. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2567. self.editor_active = False
  2568. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2569. def pool_recreated(self, pool):
  2570. self.shapes.pool = pool
  2571. self.tool_shape.pool = pool
  2572. def on_transform_complete(self):
  2573. self.delete_selected()
  2574. self.replot()
  2575. def activate(self):
  2576. # adjust the status of the menu entries related to the editor
  2577. self.app.ui.menueditedit.setDisabled(True)
  2578. self.app.ui.menueditok.setDisabled(False)
  2579. # adjust the visibility of some of the canvas context menu
  2580. self.app.ui.popmenu_edit.setVisible(False)
  2581. self.app.ui.popmenu_save.setVisible(True)
  2582. self.connect_canvas_event_handlers()
  2583. # initialize working objects
  2584. self.storage = FlatCAMGeoEditor.make_storage()
  2585. self.utility = []
  2586. self.selected = []
  2587. self.shapes.enabled = True
  2588. self.tool_shape.enabled = True
  2589. self.app.app_cursor.enabled = True
  2590. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2591. self.app.ui.corner_snap_btn.setEnabled(True)
  2592. self.app.ui.snap_magnet.setVisible(True)
  2593. self.app.ui.corner_snap_btn.setVisible(True)
  2594. self.app.ui.geo_editor_menu.setDisabled(False)
  2595. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2596. self.app.ui.update_obj_btn.setEnabled(True)
  2597. self.app.ui.g_editor_cmenu.setEnabled(True)
  2598. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2599. self.app.ui.geo_edit_toolbar.setVisible(True)
  2600. self.app.ui.snap_toolbar.setDisabled(False)
  2601. self.app.ui.popmenu_disable.setVisible(False)
  2602. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2603. self.app.ui.popmenu_properties.setVisible(False)
  2604. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2605. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2606. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2607. for w in sel_tab_widget_list:
  2608. w.setEnabled(False)
  2609. # Tell the App that the editor is active
  2610. self.editor_active = True
  2611. log.debug("Finished activating the Geometry Editor...")
  2612. def deactivate(self):
  2613. try:
  2614. QtGui.QGuiApplication.restoreOverrideCursor()
  2615. except Exception as e:
  2616. pass
  2617. # adjust the status of the menu entries related to the editor
  2618. self.app.ui.menueditedit.setDisabled(False)
  2619. self.app.ui.menueditok.setDisabled(True)
  2620. # adjust the visibility of some of the canvas context menu
  2621. self.app.ui.popmenu_edit.setVisible(True)
  2622. self.app.ui.popmenu_save.setVisible(False)
  2623. self.disconnect_canvas_event_handlers()
  2624. self.clear()
  2625. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2626. settings = QSettings("Open Source", "FlatCAM")
  2627. if settings.contains("layout"):
  2628. layout = settings.value('layout', type=str)
  2629. if layout == 'standard':
  2630. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2631. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2632. self.app.ui.corner_snap_btn.setEnabled(False)
  2633. self.app.ui.snap_magnet.setVisible(False)
  2634. self.app.ui.corner_snap_btn.setVisible(False)
  2635. elif layout == 'compact':
  2636. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2637. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2638. self.app.ui.corner_snap_btn.setEnabled(False)
  2639. else:
  2640. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2641. self.app.ui.snap_magnet.setVisible(False)
  2642. self.app.ui.corner_snap_btn.setVisible(False)
  2643. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2644. self.app.ui.corner_snap_btn.setEnabled(False)
  2645. # set the Editor Toolbar visibility to what was before entering in the Editor
  2646. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2647. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2648. # Disable visuals
  2649. self.shapes.enabled = False
  2650. self.tool_shape.enabled = False
  2651. self.app.app_cursor.enabled = False
  2652. self.app.ui.geo_editor_menu.setDisabled(True)
  2653. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2654. self.app.ui.update_obj_btn.setEnabled(False)
  2655. self.app.ui.g_editor_cmenu.setEnabled(False)
  2656. self.app.ui.e_editor_cmenu.setEnabled(False)
  2657. # Tell the app that the editor is no longer active
  2658. self.editor_active = False
  2659. self.app.ui.popmenu_disable.setVisible(True)
  2660. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2661. self.app.ui.popmenu_properties.setVisible(True)
  2662. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2663. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2664. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2665. try:
  2666. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2667. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2668. for w in sel_tab_widget_list:
  2669. w.setEnabled(True)
  2670. except Exception as e:
  2671. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2672. # Show original geometry
  2673. if self.fcgeometry:
  2674. self.fcgeometry.visible = True
  2675. log.debug("Finished deactivating the Geometry Editor...")
  2676. def connect_canvas_event_handlers(self):
  2677. # Canvas events
  2678. # first connect to new, then disconnect the old handlers
  2679. # don't ask why but if there is nothing connected I've seen issues
  2680. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2681. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2682. self.canvas.vis_connect('mouse_release', self.on_geo_click_release)
  2683. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2684. # but those from FlatCAMGeoEditor
  2685. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2686. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2687. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2688. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2689. # self.app.collection.view.clicked.disconnect()
  2690. self.app.ui.popmenu_copy.triggered.disconnect()
  2691. self.app.ui.popmenu_delete.triggered.disconnect()
  2692. self.app.ui.popmenu_move.triggered.disconnect()
  2693. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  2694. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2695. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  2696. # Geometry Editor
  2697. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  2698. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  2699. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  2700. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  2701. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  2702. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  2703. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  2704. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  2705. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  2706. self.app.ui.draw_union.triggered.connect(self.union)
  2707. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  2708. self.app.ui.draw_substract.triggered.connect(self.subtract)
  2709. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  2710. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  2711. self.app.ui.draw_move.triggered.connect(self.on_move)
  2712. def disconnect_canvas_event_handlers(self):
  2713. # we restore the key and mouse control to FlatCAMApp method
  2714. # first connect to new, then disconnect the old handlers
  2715. # don't ask why but if there is nothing connected I've seen issues
  2716. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2717. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2718. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2719. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2720. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2721. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2722. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2723. self.canvas.vis_disconnect('mouse_release', self.on_geo_click_release)
  2724. try:
  2725. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  2726. except (TypeError, AttributeError):
  2727. pass
  2728. try:
  2729. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2730. except (TypeError, AttributeError):
  2731. pass
  2732. try:
  2733. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  2734. except (TypeError, AttributeError):
  2735. pass
  2736. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2737. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2738. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2739. # Geometry Editor
  2740. try:
  2741. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  2742. except (TypeError, AttributeError):
  2743. pass
  2744. try:
  2745. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  2746. except (TypeError, AttributeError):
  2747. pass
  2748. try:
  2749. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  2750. except (TypeError, AttributeError):
  2751. pass
  2752. try:
  2753. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  2754. except (TypeError, AttributeError):
  2755. pass
  2756. try:
  2757. self.app.ui.draw_circle.triggered.disconnect()
  2758. except (TypeError, AttributeError):
  2759. pass
  2760. try:
  2761. self.app.ui.draw_poly.triggered.disconnect()
  2762. except (TypeError, AttributeError):
  2763. pass
  2764. try:
  2765. self.app.ui.draw_arc.triggered.disconnect()
  2766. except (TypeError, AttributeError):
  2767. pass
  2768. try:
  2769. self.app.ui.draw_text.triggered.disconnect()
  2770. except (TypeError, AttributeError):
  2771. pass
  2772. try:
  2773. self.app.ui.draw_buffer.triggered.disconnect()
  2774. except (TypeError, AttributeError):
  2775. pass
  2776. try:
  2777. self.app.ui.draw_paint.triggered.disconnect()
  2778. except (TypeError, AttributeError):
  2779. pass
  2780. try:
  2781. self.app.ui.draw_eraser.triggered.disconnect()
  2782. except (TypeError, AttributeError):
  2783. pass
  2784. try:
  2785. self.app.ui.draw_union.triggered.disconnect(self.union)
  2786. except (TypeError, AttributeError):
  2787. pass
  2788. try:
  2789. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  2790. except (TypeError, AttributeError):
  2791. pass
  2792. try:
  2793. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  2794. except (TypeError, AttributeError):
  2795. pass
  2796. try:
  2797. self.app.ui.draw_transform.triggered.disconnect()
  2798. except (TypeError, AttributeError):
  2799. pass
  2800. def add_shape(self, shape):
  2801. """
  2802. Adds a shape to the shape storage.
  2803. :param shape: Shape to be added.
  2804. :type shape: DrawToolShape
  2805. :return: None
  2806. """
  2807. if shape is None:
  2808. return
  2809. # List of DrawToolShape?
  2810. if isinstance(shape, list):
  2811. for subshape in shape:
  2812. self.add_shape(subshape)
  2813. return
  2814. assert isinstance(shape, DrawToolShape), \
  2815. "Expected a DrawToolShape, got %s" % type(shape)
  2816. assert shape.geo is not None, \
  2817. "Shape object has empty geometry (None)"
  2818. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2819. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  2820. if isinstance(shape, DrawToolUtilityShape):
  2821. self.utility.append(shape)
  2822. else:
  2823. self.storage.insert(shape) # TODO: Check performance
  2824. def delete_utility_geometry(self):
  2825. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2826. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2827. for_deletion = [shape for shape in self.utility]
  2828. for shape in for_deletion:
  2829. self.delete_shape(shape)
  2830. self.tool_shape.clear(update=True)
  2831. self.tool_shape.redraw()
  2832. def toolbar_tool_toggle(self, key):
  2833. self.options[key] = self.sender().isChecked()
  2834. return 1 if self.options[key] == True else 0
  2835. def clear(self):
  2836. self.active_tool = None
  2837. # self.shape_buffer = []
  2838. self.selected = []
  2839. self.shapes.clear(update=True)
  2840. self.tool_shape.clear(update=True)
  2841. # self.storage = FlatCAMGeoEditor.make_storage()
  2842. self.replot()
  2843. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2844. """
  2845. Imports the geometry from the given FlatCAM Geometry object
  2846. into the editor.
  2847. :param fcgeometry: FlatCAMGeometry
  2848. :param multigeo_tool: a tool for the case of multigeo
  2849. :return: None
  2850. """
  2851. assert isinstance(fcgeometry, Geometry), \
  2852. "Expected a Geometry, got %s" % type(fcgeometry)
  2853. self.deactivate()
  2854. self.activate()
  2855. # Hide original geometry
  2856. self.fcgeometry = fcgeometry
  2857. fcgeometry.visible = False
  2858. # Set selection tolerance
  2859. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2860. self.select_tool("select")
  2861. # Link shapes into editor.
  2862. if multigeo_tool:
  2863. self.multigeo_tool = multigeo_tool
  2864. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2865. self.app.inform.emit(_("[WARNING_NOTCL] Editing MultiGeo Geometry, tool: {tool} with diameter: {dia}").
  2866. format(tool=self.multigeo_tool, dia=fcgeometry.tools[self.multigeo_tool]['tooldia']))
  2867. else:
  2868. geo_to_edit = fcgeometry.flatten()
  2869. for shape in geo_to_edit:
  2870. if shape is not None: # TODO: Make flatten never create a None
  2871. if type(shape) == Polygon:
  2872. self.add_shape(DrawToolShape(shape.exterior))
  2873. for inter in shape.interiors:
  2874. self.add_shape(DrawToolShape(inter))
  2875. else:
  2876. self.add_shape(DrawToolShape(shape))
  2877. self.replot()
  2878. # start with GRID toolbar activated
  2879. if self.app.ui.grid_snap_btn.isChecked() is False:
  2880. self.app.ui.grid_snap_btn.trigger()
  2881. def on_buffer_tool(self):
  2882. buff_tool = BufferSelectionTool(self.app, self)
  2883. buff_tool.run()
  2884. def on_paint_tool(self):
  2885. paint_tool = PaintOptionsTool(self.app, self)
  2886. paint_tool.run()
  2887. def on_tool_select(self, tool):
  2888. """
  2889. Behavior of the toolbar. Tool initialization.
  2890. :rtype : None
  2891. """
  2892. self.app.log.debug("on_tool_select('%s')" % tool)
  2893. # This is to make the group behave as radio group
  2894. if tool in self.tools:
  2895. if self.tools[tool]["button"].isChecked():
  2896. self.app.log.debug("%s is checked." % tool)
  2897. for t in self.tools:
  2898. if t != tool:
  2899. self.tools[t]["button"].setChecked(False)
  2900. self.active_tool = self.tools[tool]["constructor"](self)
  2901. else:
  2902. self.app.log.debug("%s is NOT checked." % tool)
  2903. for t in self.tools:
  2904. self.tools[t]["button"].setChecked(False)
  2905. self.select_tool('select')
  2906. self.active_tool = FCSelect(self)
  2907. def draw_tool_path(self):
  2908. self.select_tool('path')
  2909. return
  2910. def draw_tool_rectangle(self):
  2911. self.select_tool('rectangle')
  2912. return
  2913. def on_grid_toggled(self):
  2914. self.toolbar_tool_toggle("grid_snap")
  2915. # make sure that the cursor shape is enabled/disabled, too
  2916. if self.options['grid_snap'] is True:
  2917. self.app.app_cursor.enabled = True
  2918. else:
  2919. self.app.app_cursor.enabled = False
  2920. def on_canvas_click(self, event):
  2921. """
  2922. event.x and .y have canvas coordinates
  2923. event.xdaya and .ydata have plot coordinates
  2924. :param event: Event object dispatched by Matplotlib
  2925. :return: None
  2926. """
  2927. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2928. if self.app.grid_status() == True:
  2929. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2930. self.app.app_cursor.enabled = True
  2931. # Update cursor
  2932. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2933. size=20)
  2934. else:
  2935. self.pos = (self.pos[0], self.pos[1])
  2936. self.app.app_cursor.enabled = False
  2937. if event.button == 1:
  2938. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2939. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2940. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2941. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2942. if modifiers == QtCore.Qt.ShiftModifier:
  2943. self.app.clipboard.setText(
  2944. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2945. return
  2946. # Selection with left mouse button
  2947. if self.active_tool is not None and event.button is 1:
  2948. # Dispatch event to active_tool
  2949. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  2950. # If it is a shape generating tool
  2951. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2952. self.on_shape_complete()
  2953. if isinstance(self.active_tool, FCText):
  2954. self.select_tool("select")
  2955. else:
  2956. self.select_tool(self.active_tool.name)
  2957. if isinstance(self.active_tool, FCSelect):
  2958. # self.app.log.debug("Replotting after click.")
  2959. self.replot()
  2960. else:
  2961. self.app.log.debug("No active tool to respond to click!")
  2962. def on_canvas_move(self, event):
  2963. """
  2964. Called on 'mouse_move' event
  2965. event.pos have canvas screen coordinates
  2966. :param event: Event object dispatched by VisPy SceneCavas
  2967. :return: None
  2968. """
  2969. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2970. event.xdata, event.ydata = pos[0], pos[1]
  2971. self.x = event.xdata
  2972. self.y = event.ydata
  2973. self.app.ui.popMenu.mouse_is_panning = False
  2974. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2975. if event.button == 2:
  2976. if event.is_dragging:
  2977. self.app.ui.popMenu.mouse_is_panning = True
  2978. # return
  2979. else:
  2980. self.app.ui.popMenu.mouse_is_panning = False
  2981. if self.active_tool is None:
  2982. return
  2983. try:
  2984. x = float(event.xdata)
  2985. y = float(event.ydata)
  2986. except TypeError:
  2987. return
  2988. # ### Snap coordinates ###
  2989. if self.app.grid_status() == True:
  2990. x, y = self.snap(x, y)
  2991. self.app.app_cursor.enabled = True
  2992. # Update cursor
  2993. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2994. else:
  2995. self.app.app_cursor.enabled = False
  2996. self.snap_x = x
  2997. self.snap_y = y
  2998. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2999. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3000. "<b>Y</b>: %.4f" % (x, y))
  3001. if self.pos is None:
  3002. self.pos = (0, 0)
  3003. dx = x - self.pos[0]
  3004. dy = y - self.pos[1]
  3005. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3006. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3007. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3008. if event.button == 1 and event.is_dragging and isinstance(self.active_tool, FCEraser):
  3009. pass
  3010. else:
  3011. # ### Utility geometry (animated) ###
  3012. geo = self.active_tool.utility_geometry(data=(x, y))
  3013. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3014. # Remove any previous utility shape
  3015. self.tool_shape.clear(update=True)
  3016. self.draw_utility_geometry(geo=geo)
  3017. # ### Selection area on canvas section ###
  3018. dx = pos[0] - self.pos[0]
  3019. if event.is_dragging and event.button == 1:
  3020. self.app.delete_selection_shape()
  3021. if dx < 0:
  3022. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3023. color=self.app.defaults["global_alt_sel_line"],
  3024. face_color=self.app.defaults['global_alt_sel_fill'])
  3025. self.app.selection_type = False
  3026. else:
  3027. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3028. self.app.selection_type = True
  3029. else:
  3030. self.app.selection_type = None
  3031. def on_geo_click_release(self, event):
  3032. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  3033. if self.app.grid_status() == True:
  3034. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3035. else:
  3036. pos = (pos_canvas[0], pos_canvas[1])
  3037. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3038. # canvas menu
  3039. try:
  3040. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3041. # selection and then select a type of selection ("enclosing" or "touching")
  3042. if event.button == 1: # left click
  3043. if self.app.selection_type is not None:
  3044. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3045. self.app.selection_type = None
  3046. elif isinstance(self.active_tool, FCSelect):
  3047. # Dispatch event to active_tool
  3048. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3049. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3050. # self.app.inform.emit(msg)
  3051. self.replot()
  3052. elif event.button == 2: # right click
  3053. if self.app.ui.popMenu.mouse_is_panning == False:
  3054. if self.in_action is False:
  3055. try:
  3056. QtGui.QGuiApplication.restoreOverrideCursor()
  3057. except Exception as e:
  3058. pass
  3059. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3060. self.active_tool.complete = True
  3061. self.in_action = False
  3062. self.delete_utility_geometry()
  3063. self.app.inform.emit(_("[success] Done."))
  3064. self.select_tool('select')
  3065. else:
  3066. self.app.cursor = QtGui.QCursor()
  3067. self.app.populate_cmenu_grids()
  3068. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3069. else:
  3070. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3071. # right mouse click will finish the action
  3072. if isinstance(self.active_tool, FCShapeTool):
  3073. self.active_tool.click(self.snap(self.x, self.y))
  3074. self.active_tool.make()
  3075. if self.active_tool.complete:
  3076. self.on_shape_complete()
  3077. self.app.inform.emit(_("[success] Done."))
  3078. self.select_tool(self.active_tool.name)
  3079. except Exception as e:
  3080. log.warning("Error: %s" % str(e))
  3081. return
  3082. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3083. """
  3084. :param start_pos: mouse position when the selection LMB click was done
  3085. :param end_pos: mouse position when the left mouse button is released
  3086. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3087. :return:
  3088. """
  3089. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3090. self.app.delete_selection_shape()
  3091. for obj in self.storage.get_objects():
  3092. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3093. poly_selection.intersects(obj.geo)):
  3094. if self.key == self.app.defaults["global_mselect_key"]:
  3095. if obj in self.selected:
  3096. self.selected.remove(obj)
  3097. else:
  3098. # add the object to the selected shapes
  3099. self.selected.append(obj)
  3100. else:
  3101. if obj not in self.selected:
  3102. self.selected.append(obj)
  3103. self.replot()
  3104. def draw_utility_geometry(self, geo):
  3105. # Add the new utility shape
  3106. try:
  3107. # this case is for the Font Parse
  3108. for el in list(geo.geo):
  3109. if type(el) == MultiPolygon:
  3110. for poly in el:
  3111. self.tool_shape.add(
  3112. shape=poly,
  3113. color=(self.app.defaults["global_draw_color"] + '80'),
  3114. update=False,
  3115. layer=0,
  3116. tolerance=None
  3117. )
  3118. elif type(el) == MultiLineString:
  3119. for linestring in el:
  3120. self.tool_shape.add(
  3121. shape=linestring,
  3122. color=(self.app.defaults["global_draw_color"] + '80'),
  3123. update=False,
  3124. layer=0,
  3125. tolerance=None
  3126. )
  3127. else:
  3128. self.tool_shape.add(
  3129. shape=el,
  3130. color=(self.app.defaults["global_draw_color"] + '80'),
  3131. update=False,
  3132. layer=0,
  3133. tolerance=None
  3134. )
  3135. except TypeError:
  3136. self.tool_shape.add(
  3137. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3138. update=False, layer=0, tolerance=None)
  3139. self.tool_shape.redraw()
  3140. def on_delete_btn(self):
  3141. self.delete_selected()
  3142. self.replot()
  3143. def delete_selected(self):
  3144. tempref = [s for s in self.selected]
  3145. for shape in tempref:
  3146. self.delete_shape(shape)
  3147. self.selected = []
  3148. def delete_shape(self, shape):
  3149. if shape in self.utility:
  3150. self.utility.remove(shape)
  3151. return
  3152. self.storage.remove(shape)
  3153. if shape in self.selected:
  3154. self.selected.remove(shape) # TODO: Check performance
  3155. def on_move(self):
  3156. # if not self.selected:
  3157. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3158. # return
  3159. self.app.ui.geo_move_btn.setChecked(True)
  3160. self.on_tool_select('move')
  3161. def on_move_click(self):
  3162. self.on_move()
  3163. self.active_tool.set_origin(self.snap(self.x, self.y))
  3164. def on_copy_click(self):
  3165. if not self.selected:
  3166. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3167. return
  3168. self.app.ui.geo_copy_btn.setChecked(True)
  3169. self.app.geo_editor.on_tool_select('copy')
  3170. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3171. self.app.geo_editor.x, self.app.geo_editor.y))
  3172. self.app.inform.emit(_("Click on target point."))
  3173. def on_corner_snap(self):
  3174. self.app.ui.corner_snap_btn.trigger()
  3175. def get_selected(self):
  3176. """
  3177. Returns list of shapes that are selected in the editor.
  3178. :return: List of shapes.
  3179. """
  3180. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3181. return self.selected
  3182. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3183. """
  3184. Plots a geometric object or list of objects without rendering. Plotted objects
  3185. are returned as a list. This allows for efficient/animated rendering.
  3186. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3187. :param color: Shape color
  3188. :param linewidth: Width of lines in # of pixels.
  3189. :return: List of plotted elements.
  3190. """
  3191. plot_elements = []
  3192. if geometry is None:
  3193. geometry = self.active_tool.geometry
  3194. try:
  3195. for geo in geometry:
  3196. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3197. # Non-iterable
  3198. except TypeError:
  3199. # DrawToolShape
  3200. if isinstance(geometry, DrawToolShape):
  3201. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3202. # Polygon: Descend into exterior and each interior.
  3203. if type(geometry) == Polygon:
  3204. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3205. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3206. if type(geometry) == LineString or type(geometry) == LinearRing:
  3207. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3208. tolerance=self.fcgeometry.drawing_tolerance))
  3209. if type(geometry) == Point:
  3210. pass
  3211. return plot_elements
  3212. def plot_all(self):
  3213. """
  3214. Plots all shapes in the editor.
  3215. :return: None
  3216. :rtype: None
  3217. """
  3218. # self.app.log.debug("plot_all()")
  3219. self.shapes.clear(update=True)
  3220. for shape in self.storage.get_objects():
  3221. if shape.geo is None: # TODO: This shouldn't have happened
  3222. continue
  3223. if shape in self.selected:
  3224. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3225. continue
  3226. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3227. for shape in self.utility:
  3228. self.plot_shape(geometry=shape.geo, linewidth=1)
  3229. continue
  3230. self.shapes.redraw()
  3231. def replot(self):
  3232. self.plot_all()
  3233. def on_shape_complete(self):
  3234. self.app.log.debug("on_shape_complete()")
  3235. # Add shape
  3236. self.add_shape(self.active_tool.geometry)
  3237. # Remove any utility shapes
  3238. self.delete_utility_geometry()
  3239. self.tool_shape.clear(update=True)
  3240. # Replot and reset tool.
  3241. self.replot()
  3242. # self.active_tool = type(self.active_tool)(self)
  3243. @staticmethod
  3244. def make_storage():
  3245. # Shape storage.
  3246. storage = FlatCAMRTreeStorage()
  3247. storage.get_points = DrawToolShape.get_pts
  3248. return storage
  3249. def select_tool(self, toolname):
  3250. """
  3251. Selects a drawing tool. Impacts the object and GUI.
  3252. :param toolname: Name of the tool.
  3253. :return: None
  3254. """
  3255. self.tools[toolname]["button"].setChecked(True)
  3256. self.on_tool_select(toolname)
  3257. def set_selected(self, shape):
  3258. # Remove and add to the end.
  3259. if shape in self.selected:
  3260. self.selected.remove(shape)
  3261. self.selected.append(shape)
  3262. def set_unselected(self, shape):
  3263. if shape in self.selected:
  3264. self.selected.remove(shape)
  3265. def snap(self, x, y):
  3266. """
  3267. Adjusts coordinates to snap settings.
  3268. :param x: Input coordinate X
  3269. :param y: Input coordinate Y
  3270. :return: Snapped (x, y)
  3271. """
  3272. snap_x, snap_y = (x, y)
  3273. snap_distance = Inf
  3274. # # ## Object (corner?) snap
  3275. # # ## No need for the objects, just the coordinates
  3276. # # ## in the index.
  3277. if self.options["corner_snap"]:
  3278. try:
  3279. nearest_pt, shape = self.storage.nearest((x, y))
  3280. nearest_pt_distance = distance((x, y), nearest_pt)
  3281. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3282. snap_distance = nearest_pt_distance
  3283. snap_x, snap_y = nearest_pt
  3284. except (StopIteration, AssertionError):
  3285. pass
  3286. # # ## Grid snap
  3287. if self.options["grid_snap"]:
  3288. if self.options["global_gridx"] != 0:
  3289. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3290. else:
  3291. snap_x_ = x
  3292. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3293. # and it will use the snap distance from GridX entry
  3294. if self.app.ui.grid_gap_link_cb.isChecked():
  3295. if self.options["global_gridx"] != 0:
  3296. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3297. else:
  3298. snap_y_ = y
  3299. else:
  3300. if self.options["global_gridy"] != 0:
  3301. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3302. else:
  3303. snap_y_ = y
  3304. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3305. if nearest_grid_distance < snap_distance:
  3306. snap_x, snap_y = (snap_x_, snap_y_)
  3307. return snap_x, snap_y
  3308. def update_fcgeometry(self, fcgeometry):
  3309. """
  3310. Transfers the geometry tool shape buffer to the selected geometry
  3311. object. The geometry already in the object are removed.
  3312. :param fcgeometry: FlatCAMGeometry
  3313. :return: None
  3314. """
  3315. if self.multigeo_tool:
  3316. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3317. # for shape in self.shape_buffer:
  3318. for shape in self.storage.get_objects():
  3319. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  3320. self.multigeo_tool = None
  3321. else:
  3322. fcgeometry.solid_geometry = []
  3323. # for shape in self.shape_buffer:
  3324. for shape in self.storage.get_objects():
  3325. fcgeometry.solid_geometry.append(shape.geo)
  3326. def update_options(self, obj):
  3327. if self.paint_tooldia:
  3328. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3329. self.paint_tooldia = None
  3330. return True
  3331. else:
  3332. return False
  3333. def union(self):
  3334. """
  3335. Makes union of selected polygons. Original polygons
  3336. are deleted.
  3337. :return: None.
  3338. """
  3339. results = unary_union([t.geo for t in self.get_selected()])
  3340. # Delete originals.
  3341. for_deletion = [s for s in self.get_selected()]
  3342. for shape in for_deletion:
  3343. self.delete_shape(shape)
  3344. # Selected geometry is now gone!
  3345. self.selected = []
  3346. self.add_shape(DrawToolShape(results))
  3347. self.replot()
  3348. def intersection_2(self):
  3349. """
  3350. Makes intersection of selected polygons. Original polygons are deleted.
  3351. :return: None
  3352. """
  3353. geo_shapes = self.get_selected()
  3354. try:
  3355. results = geo_shapes[0].geo
  3356. except Exception as e:
  3357. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3358. self.app.inform.emit(
  3359. _("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3360. self.select_tool('select')
  3361. return
  3362. for shape_el in geo_shapes[1:]:
  3363. results = results.intersection(shape_el.geo)
  3364. # Delete originals.
  3365. for_deletion = [s for s in self.get_selected()]
  3366. for shape_el in for_deletion:
  3367. self.delete_shape(shape_el)
  3368. # Selected geometry is now gone!
  3369. self.selected = []
  3370. self.add_shape(DrawToolShape(results))
  3371. self.replot()
  3372. def intersection(self):
  3373. """
  3374. Makes intersection of selected polygons. Original polygons are deleted.
  3375. :return: None
  3376. """
  3377. geo_shapes = self.get_selected()
  3378. results = []
  3379. intact = []
  3380. try:
  3381. intersector = geo_shapes[0].geo
  3382. except Exception as e:
  3383. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3384. self.app.inform.emit(
  3385. _("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3386. self.select_tool('select')
  3387. return
  3388. for shape_el in geo_shapes[1:]:
  3389. if intersector.intersects(shape_el.geo):
  3390. results.append(intersector.intersection(shape_el.geo))
  3391. else:
  3392. intact.append(shape_el)
  3393. if len(results) != 0:
  3394. # Delete originals.
  3395. for_deletion = [s for s in self.get_selected()]
  3396. for shape_el in for_deletion:
  3397. if shape_el not in intact:
  3398. self.delete_shape(shape_el)
  3399. for geo in results:
  3400. self.add_shape(DrawToolShape(geo))
  3401. # Selected geometry is now gone!
  3402. self.selected = []
  3403. self.replot()
  3404. def subtract(self):
  3405. selected = self.get_selected()
  3406. try:
  3407. tools = selected[1:]
  3408. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3409. target = selected[0].geo
  3410. target = target.buffer(0.0000001)
  3411. result = target.difference(toolgeo)
  3412. for_deletion = [s for s in self.get_selected()]
  3413. for shape in for_deletion:
  3414. self.delete_shape(shape)
  3415. self.add_shape(DrawToolShape(result))
  3416. self.replot()
  3417. except Exception as e:
  3418. log.debug(str(e))
  3419. def subtract_2(self):
  3420. selected = self.get_selected()
  3421. try:
  3422. tools = selected[1:]
  3423. toolgeo = unary_union([shp.geo for shp in tools])
  3424. result = selected[0].geo.difference(toolgeo)
  3425. self.delete_shape(selected[0])
  3426. self.add_shape(DrawToolShape(result))
  3427. self.replot()
  3428. except Exception as e:
  3429. log.debug(str(e))
  3430. def cutpath(self):
  3431. selected = self.get_selected()
  3432. tools = selected[1:]
  3433. toolgeo = unary_union([shp.geo for shp in tools])
  3434. target = selected[0]
  3435. if type(target.geo) == Polygon:
  3436. for ring in poly2rings(target.geo):
  3437. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3438. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3439. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3440. elif type(target.geo) == MultiLineString:
  3441. try:
  3442. for linestring in target.geo:
  3443. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3444. except Exception as e:
  3445. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3446. else:
  3447. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3448. return
  3449. self.delete_shape(target)
  3450. self.replot()
  3451. def buffer(self, buf_distance, join_style):
  3452. selected = self.get_selected()
  3453. if buf_distance < 0:
  3454. self.app.inform.emit(
  3455. _("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3456. "Use Buffer interior to generate an 'inside' shape"))
  3457. # deselect everything
  3458. self.selected = []
  3459. self.replot()
  3460. return 'fail'
  3461. if len(selected) == 0:
  3462. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3463. return 'fail'
  3464. if not isinstance(buf_distance, float):
  3465. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3466. # deselect everything
  3467. self.selected = []
  3468. self.replot()
  3469. return 'fail'
  3470. results = []
  3471. for t in selected:
  3472. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3473. results.append((t.geo.exterior).buffer(
  3474. buf_distance - 1e-10,
  3475. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3476. join_style=join_style)
  3477. )
  3478. else:
  3479. results.append(t.geo.buffer(
  3480. buf_distance - 1e-10,
  3481. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3482. join_style=join_style)
  3483. )
  3484. if not results:
  3485. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3486. # deselect everything
  3487. self.selected = []
  3488. self.replot()
  3489. return 'fail'
  3490. for sha in results:
  3491. self.add_shape(DrawToolShape(sha))
  3492. self.replot()
  3493. self.app.inform.emit(_("[success] Full buffer geometry created."))
  3494. def buffer_int(self, buf_distance, join_style):
  3495. selected = self.get_selected()
  3496. if buf_distance < 0:
  3497. self.app.inform.emit(
  3498. _("[ERROR_NOTCL] Negative buffer value is not accepted.")
  3499. )
  3500. # deselect everything
  3501. self.selected = []
  3502. self.replot()
  3503. return 'fail'
  3504. if len(selected) == 0:
  3505. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3506. return 'fail'
  3507. if not isinstance(buf_distance, float):
  3508. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3509. # deselect everything
  3510. self.selected = []
  3511. self.replot()
  3512. return 'fail'
  3513. results = []
  3514. for t in selected:
  3515. if isinstance(t.geo, LinearRing):
  3516. t.geo = Polygon(t.geo)
  3517. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3518. results.append((t.geo).buffer(
  3519. -buf_distance + 1e-10,
  3520. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3521. join_style=join_style)
  3522. )
  3523. if not results:
  3524. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a smaller buffer value."))
  3525. # deselect everything
  3526. self.selected = []
  3527. self.replot()
  3528. return 'fail'
  3529. for sha in results:
  3530. self.add_shape(DrawToolShape(sha))
  3531. self.replot()
  3532. self.app.inform.emit(_("[success] Interior buffer geometry created."))
  3533. def buffer_ext(self, buf_distance, join_style):
  3534. selected = self.get_selected()
  3535. if buf_distance < 0:
  3536. self.app.inform.emit(_("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3537. "Use Buffer interior to generate an 'inside' shape"))
  3538. # deselect everything
  3539. self.selected = []
  3540. self.replot()
  3541. return
  3542. if len(selected) == 0:
  3543. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3544. return
  3545. if not isinstance(buf_distance, float):
  3546. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3547. # deselect everything
  3548. self.selected = []
  3549. self.replot()
  3550. return
  3551. results = []
  3552. for t in selected:
  3553. if isinstance(t.geo, LinearRing):
  3554. t.geo = Polygon(t.geo)
  3555. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3556. results.append((t.geo).buffer(
  3557. buf_distance,
  3558. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3559. join_style=join_style)
  3560. )
  3561. if not results:
  3562. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3563. # deselect everything
  3564. self.selected = []
  3565. self.replot()
  3566. return
  3567. for sha in results:
  3568. self.add_shape(DrawToolShape(sha))
  3569. self.replot()
  3570. self.app.inform.emit(_("[success] Exterior buffer geometry created."))
  3571. # def paint(self, tooldia, overlap, margin, method):
  3572. # selected = self.get_selected()
  3573. #
  3574. # if len(selected) == 0:
  3575. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3576. # return
  3577. #
  3578. # for param in [tooldia, overlap, margin]:
  3579. # if not isinstance(param, float):
  3580. # param_name = [k for k, v in locals().items() if v is param][0]
  3581. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3582. #
  3583. # # Todo: Check for valid method.
  3584. #
  3585. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3586. #
  3587. # results = []
  3588. #
  3589. # def recurse(geo):
  3590. # try:
  3591. # for subg in geo:
  3592. # for subsubg in recurse(subg):
  3593. # yield subsubg
  3594. # except TypeError:
  3595. # if isinstance(geo, LinearRing):
  3596. # yield geo
  3597. #
  3598. # raise StopIteration
  3599. #
  3600. # for geo in selected:
  3601. # print(type(geo.geo))
  3602. #
  3603. # local_results = []
  3604. # for poly in recurse(geo.geo):
  3605. # if method == "seed":
  3606. # # Type(cp) == FlatCAMRTreeStorage | None
  3607. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3608. # tooldia, overlap=overlap)
  3609. #
  3610. # else:
  3611. # # Type(cp) == FlatCAMRTreeStorage | None
  3612. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3613. # tooldia, overlap=overlap)
  3614. #
  3615. # if cp is not None:
  3616. # local_results += list(cp.get_objects())
  3617. #
  3618. # results.append(cascaded_union(local_results))
  3619. #
  3620. # # This is a dirty patch:
  3621. # for r in results:
  3622. # self.add_shape(DrawToolShape(r))
  3623. #
  3624. # self.replot()
  3625. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3626. self.paint_tooldia = tooldia
  3627. selected = self.get_selected()
  3628. if len(selected) == 0:
  3629. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for painting."))
  3630. return
  3631. for param in [tooldia, overlap, margin]:
  3632. if not isinstance(param, float):
  3633. param_name = [k for k, v in locals().items() if v is param][0]
  3634. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3635. results = []
  3636. if overlap >= 1:
  3637. self.app.inform.emit(
  3638. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3639. return
  3640. def recurse(geometry, reset=True):
  3641. """
  3642. Creates a list of non-iterable linear geometry objects.
  3643. Results are placed in self.flat_geometry
  3644. :param geometry: Shapely type or list or list of list of such.
  3645. :param reset: Clears the contents of self.flat_geometry.
  3646. """
  3647. if geometry is None:
  3648. return
  3649. if reset:
  3650. self.flat_geo = []
  3651. # If iterable, expand recursively.
  3652. try:
  3653. for geo_el in geometry:
  3654. if geo_el is not None:
  3655. recurse(geometry=geo_el, reset=False)
  3656. # Not iterable, do the actual indexing and add.
  3657. except TypeError:
  3658. self.flat_geo.append(geometry)
  3659. return self.flat_geo
  3660. for geo in selected:
  3661. local_results = []
  3662. for geo_obj in recurse(geo.geo):
  3663. try:
  3664. if type(geo_obj) == Polygon:
  3665. poly_buf = geo_obj.buffer(-margin)
  3666. else:
  3667. poly_buf = Polygon(geo_obj).buffer(-margin)
  3668. if method == "seed":
  3669. cp = Geometry.clear_polygon2(poly_buf,
  3670. tooldia, self.app.defaults["geometry_circle_steps"],
  3671. overlap=overlap, contour=contour, connect=connect)
  3672. elif method == "lines":
  3673. cp = Geometry.clear_polygon3(poly_buf,
  3674. tooldia, self.app.defaults["geometry_circle_steps"],
  3675. overlap=overlap, contour=contour, connect=connect)
  3676. else:
  3677. cp = Geometry.clear_polygon(poly_buf,
  3678. tooldia, self.app.defaults["geometry_circle_steps"],
  3679. overlap=overlap, contour=contour, connect=connect)
  3680. if cp is not None:
  3681. local_results += list(cp.get_objects())
  3682. except Exception as e:
  3683. log.debug("Could not Paint the polygons. %s" % str(e))
  3684. self.app.inform.emit(
  3685. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3686. "Or a different method of Paint\n%s") % str(e))
  3687. return
  3688. # add the result to the results list
  3689. results.append(cascaded_union(local_results))
  3690. # This is a dirty patch:
  3691. for r in results:
  3692. self.add_shape(DrawToolShape(r))
  3693. self.app.inform.emit(
  3694. _("[success] Paint done."))
  3695. self.replot()
  3696. def distance(pt1, pt2):
  3697. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3698. def mag(vec):
  3699. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3700. def poly2rings(poly):
  3701. return [poly.exterior] + [interior for interior in poly.interiors]
  3702. def get_shapely_list_bounds(geometry_list):
  3703. xmin = Inf
  3704. ymin = Inf
  3705. xmax = -Inf
  3706. ymax = -Inf
  3707. for gs in geometry_list:
  3708. try:
  3709. gxmin, gymin, gxmax, gymax = gs.bounds
  3710. xmin = min([xmin, gxmin])
  3711. ymin = min([ymin, gymin])
  3712. xmax = max([xmax, gxmax])
  3713. ymax = max([ymax, gymax])
  3714. except Exception as e:
  3715. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3716. return [xmin, ymin, xmax, ymax]