FlatCAMGeoEditor.py 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563
  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. # list where we store the overlapped shapes under our mouse left click position
  1944. over_shape_list = []
  1945. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1946. for obj_shape in self.storage.get_objects():
  1947. # first method of click selection -> inconvenient
  1948. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1949. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1950. # over_shape_list.append(obj_shape)
  1951. # second method of click selection -> slow
  1952. # outside = obj_shape.geo.buffer(0.1)
  1953. # inside = obj_shape.geo.buffer(-0.1)
  1954. # shape_band = outside.difference(inside)
  1955. # if Point(pos).within(shape_band):
  1956. # over_shape_list.append(obj_shape)
  1957. # 3rd method of click selection -> inconvenient
  1958. try:
  1959. _, closest_shape = self.storage.nearest(point)
  1960. except StopIteration:
  1961. return ""
  1962. over_shape_list.append(closest_shape)
  1963. try:
  1964. # if there is no shape under our click then deselect all shapes
  1965. # it will not work for 3rd method of click selection
  1966. if not over_shape_list:
  1967. self.draw_app.selected = []
  1968. FlatCAMGeoEditor.draw_shape_idx = -1
  1969. else:
  1970. # if there are shapes under our click then advance through the list of them, one at the time in a
  1971. # circular way
  1972. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1973. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1974. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1975. if key_modifier == QtCore.Qt.ShiftModifier:
  1976. mod_key = 'Shift'
  1977. elif key_modifier == QtCore.Qt.ControlModifier:
  1978. mod_key = 'Control'
  1979. else:
  1980. mod_key = None
  1981. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  1982. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  1983. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1984. if obj_to_add in self.draw_app.selected:
  1985. self.draw_app.selected.remove(obj_to_add)
  1986. else:
  1987. self.draw_app.selected.append(obj_to_add)
  1988. else:
  1989. self.draw_app.selected = []
  1990. self.draw_app.selected.append(obj_to_add)
  1991. except Exception as e:
  1992. log.error("[ERROR] Something went bad. %s" % str(e))
  1993. raise
  1994. return ""
  1995. class FCMove(FCShapeTool):
  1996. def __init__(self, draw_app):
  1997. FCShapeTool.__init__(self, draw_app)
  1998. self.name = 'move'
  1999. try:
  2000. QtGui.QGuiApplication.restoreOverrideCursor()
  2001. except Exception as e:
  2002. pass
  2003. self.storage = self.draw_app.storage
  2004. self.origin = None
  2005. self.destination = None
  2006. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2007. self.selection_shape = self.selection_bbox()
  2008. if len(self.draw_app.get_selected()) == 0:
  2009. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] MOVE: No shape selected. Select a shape to move ..."))
  2010. else:
  2011. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2012. def set_origin(self, origin):
  2013. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2014. self.origin = origin
  2015. def click(self, point):
  2016. if len(self.draw_app.get_selected()) == 0:
  2017. # self.complete = True
  2018. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2019. self.select_shapes(point)
  2020. self.draw_app.replot()
  2021. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2022. return
  2023. if self.origin is None:
  2024. self.set_origin(point)
  2025. self.selection_shape = self.selection_bbox()
  2026. return "Click on final location."
  2027. else:
  2028. self.destination = point
  2029. self.make()
  2030. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2031. # 'params': []}))
  2032. return "Done."
  2033. def make(self):
  2034. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2035. # Create new geometry
  2036. dx = self.destination[0] - self.origin[0]
  2037. dy = self.destination[1] - self.origin[1]
  2038. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2039. for geom in self.draw_app.get_selected()]
  2040. # Delete old
  2041. self.draw_app.delete_selected()
  2042. self.complete = True
  2043. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Move completed."))
  2044. def selection_bbox(self):
  2045. geo_list = []
  2046. for select_shape in self.draw_app.get_selected():
  2047. geometric_data = select_shape.geo
  2048. try:
  2049. for g in geometric_data:
  2050. geo_list.append(g)
  2051. except TypeError:
  2052. geo_list.append(geometric_data)
  2053. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2054. pt1 = (xmin, ymin)
  2055. pt2 = (xmax, ymin)
  2056. pt3 = (xmax, ymax)
  2057. pt4 = (xmin, ymax)
  2058. return Polygon([pt1, pt2, pt3, pt4])
  2059. def utility_geometry(self, data=None):
  2060. """
  2061. Temporary geometry on screen while using this tool.
  2062. :param data:
  2063. :return:
  2064. """
  2065. geo_list = []
  2066. if self.origin is None:
  2067. return None
  2068. if len(self.draw_app.get_selected()) == 0:
  2069. return None
  2070. dx = data[0] - self.origin[0]
  2071. dy = data[1] - self.origin[1]
  2072. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2073. try:
  2074. for geom in self.draw_app.get_selected():
  2075. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2076. except AttributeError:
  2077. self.draw_app.select_tool('select')
  2078. self.draw_app.selected = []
  2079. return
  2080. return DrawToolUtilityShape(geo_list)
  2081. else:
  2082. try:
  2083. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2084. except ValueError:
  2085. ss_el = None
  2086. return DrawToolUtilityShape(ss_el)
  2087. def select_shapes(self, pos):
  2088. # list where we store the overlapped shapes under our mouse left click position
  2089. over_shape_list = []
  2090. try:
  2091. _, closest_shape = self.storage.nearest(pos)
  2092. except StopIteration:
  2093. return ""
  2094. over_shape_list.append(closest_shape)
  2095. try:
  2096. # if there is no shape under our click then deselect all shapes
  2097. # it will not work for 3rd method of click selection
  2098. if not over_shape_list:
  2099. self.draw_app.selected = []
  2100. self.draw_app.draw_shape_idx = -1
  2101. else:
  2102. # if there are shapes under our click then advance through the list of them, one at the time in a
  2103. # circular way
  2104. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2105. try:
  2106. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2107. except IndexError:
  2108. return
  2109. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2110. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2111. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2112. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2113. if key_modifier == Qt.ControlModifier:
  2114. if obj_to_add in self.draw_app.selected:
  2115. self.draw_app.selected.remove(obj_to_add)
  2116. else:
  2117. self.draw_app.selected.append(obj_to_add)
  2118. else:
  2119. self.draw_app.selected = []
  2120. self.draw_app.selected.append(obj_to_add)
  2121. else:
  2122. if key_modifier == Qt.ShiftModifier:
  2123. if obj_to_add in self.draw_app.selected:
  2124. self.draw_app.selected.remove(obj_to_add)
  2125. else:
  2126. self.draw_app.selected.append(obj_to_add)
  2127. else:
  2128. self.draw_app.selected = []
  2129. self.draw_app.selected.append(obj_to_add)
  2130. except Exception as e:
  2131. log.error("[ERROR] Something went bad. %s" % str(e))
  2132. raise
  2133. class FCCopy(FCMove):
  2134. def __init__(self, draw_app):
  2135. FCMove.__init__(self, draw_app)
  2136. self.name = 'copy'
  2137. def make(self):
  2138. # Create new geometry
  2139. dx = self.destination[0] - self.origin[0]
  2140. dy = self.destination[1] - self.origin[1]
  2141. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2142. for geom in self.draw_app.get_selected()]
  2143. self.complete = True
  2144. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Copy completed."))
  2145. class FCText(FCShapeTool):
  2146. def __init__(self, draw_app):
  2147. FCShapeTool.__init__(self, draw_app)
  2148. self.name = 'text'
  2149. try:
  2150. QtGui.QGuiApplication.restoreOverrideCursor()
  2151. except Exception as e:
  2152. pass
  2153. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_text.png'))
  2154. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2155. # self.shape_buffer = self.draw_app.shape_buffer
  2156. self.draw_app = draw_app
  2157. self.app = draw_app.app
  2158. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  2159. self.origin = (0, 0)
  2160. self.text_gui = TextInputTool(self.app)
  2161. self.text_gui.run()
  2162. def click(self, point):
  2163. # Create new geometry
  2164. dx = point[0]
  2165. dy = point[1]
  2166. if self.text_gui.text_path:
  2167. try:
  2168. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2169. except Exception as e:
  2170. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2171. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2172. "supported. Error: %s") % str(e))
  2173. self.text_gui.text_path = []
  2174. self.text_gui.hide_tool()
  2175. self.draw_app.select_tool('select')
  2176. return
  2177. else:
  2178. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] No text to add."))
  2179. return
  2180. self.text_gui.text_path = []
  2181. self.text_gui.hide_tool()
  2182. self.complete = True
  2183. self.draw_app.app.inform.emit(_("[success] Done. Adding Text completed."))
  2184. def utility_geometry(self, data=None):
  2185. """
  2186. Temporary geometry on screen while using this tool.
  2187. :param data: mouse position coords
  2188. :return:
  2189. """
  2190. dx = data[0] - self.origin[0]
  2191. dy = data[1] - self.origin[1]
  2192. try:
  2193. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2194. except:
  2195. return
  2196. class FCBuffer(FCShapeTool):
  2197. def __init__(self, draw_app):
  2198. FCShapeTool.__init__(self, draw_app)
  2199. self.name = 'buffer'
  2200. # self.shape_buffer = self.draw_app.shape_buffer
  2201. self.draw_app = draw_app
  2202. self.app = draw_app.app
  2203. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2204. self.origin = (0, 0)
  2205. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2206. self.buff_tool.run()
  2207. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2208. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2209. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2210. self.activate()
  2211. def on_buffer(self):
  2212. if not self.draw_app.selected:
  2213. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2214. return
  2215. try:
  2216. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2217. except ValueError:
  2218. # try to convert comma to decimal point. if it's still not working error message and return
  2219. try:
  2220. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2221. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2222. except ValueError:
  2223. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2224. "Add it and retry."))
  2225. return
  2226. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2227. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2228. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2229. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2230. self.app.ui.notebook.setTabText(2, _("Tools"))
  2231. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2232. self.disactivate()
  2233. if ret_val == 'fail':
  2234. return
  2235. self.draw_app.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2236. def on_buffer_int(self):
  2237. if not self.draw_app.selected:
  2238. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2239. return
  2240. try:
  2241. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2242. except ValueError:
  2243. # try to convert comma to decimal point. if it's still not working error message and return
  2244. try:
  2245. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2246. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2247. except ValueError:
  2248. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2249. "Add it and retry."))
  2250. return
  2251. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2252. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2253. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2254. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2255. self.app.ui.notebook.setTabText(2, _("Tools"))
  2256. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2257. self.disactivate()
  2258. if ret_val == 'fail':
  2259. return
  2260. self.draw_app.app.inform.emit(_("[success] Done. Buffer Int Tool completed."))
  2261. def on_buffer_ext(self):
  2262. if not self.draw_app.selected:
  2263. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2264. return
  2265. try:
  2266. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2267. except ValueError:
  2268. # try to convert comma to decimal point. if it's still not working error message and return
  2269. try:
  2270. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2271. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2272. except ValueError:
  2273. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2274. "Add it and retry."))
  2275. return
  2276. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2277. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2278. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2279. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2280. self.app.ui.notebook.setTabText(2, _("Tools"))
  2281. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2282. self.disactivate()
  2283. if ret_val == 'fail':
  2284. return
  2285. self.draw_app.app.inform.emit(_("[success] Done. Buffer Ext Tool completed."))
  2286. def activate(self):
  2287. self.buff_tool.buffer_button.clicked.disconnect()
  2288. self.buff_tool.buffer_int_button.clicked.disconnect()
  2289. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2290. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2291. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2292. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2293. def disactivate(self):
  2294. self.buff_tool.buffer_button.clicked.disconnect()
  2295. self.buff_tool.buffer_int_button.clicked.disconnect()
  2296. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2297. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2298. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2299. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2300. self.complete = True
  2301. self.draw_app.select_tool("select")
  2302. self.buff_tool.hide_tool()
  2303. class FCEraser(FCShapeTool):
  2304. def __init__(self, draw_app):
  2305. DrawTool.__init__(self, draw_app)
  2306. self.name = 'eraser'
  2307. self.origin = None
  2308. self.destination = None
  2309. if len(self.draw_app.get_selected()) == 0:
  2310. if self.draw_app.launched_from_shortcuts is True:
  2311. self.draw_app.launched_from_shortcuts = False
  2312. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2313. else:
  2314. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2315. self.geometry = []
  2316. self.storage = self.draw_app.storage
  2317. # Switch notebook to Selected page
  2318. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2319. def set_origin(self, origin):
  2320. self.origin = origin
  2321. def click(self, point):
  2322. if len(self.draw_app.get_selected()) == 0:
  2323. for obj_shape in self.storage.get_objects():
  2324. try:
  2325. __, closest_shape = self.storage.nearest(point)
  2326. self.draw_app.selected.append(closest_shape)
  2327. except StopIteration:
  2328. if len(self.draw_app.selected) > 0:
  2329. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2330. return ""
  2331. if len(self.draw_app.get_selected()) == 0:
  2332. return "Nothing to ersase."
  2333. else:
  2334. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2335. if self.origin is None:
  2336. self.set_origin(point)
  2337. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2338. return
  2339. else:
  2340. self.destination = point
  2341. self.make()
  2342. # self.draw_app.select_tool("select")
  2343. return
  2344. def make(self):
  2345. eraser_sel_shapes = []
  2346. # create the eraser shape from selection
  2347. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2348. temp_shape = eraser_shape.buffer(0.0000001)
  2349. temp_shape = Polygon(temp_shape.exterior)
  2350. eraser_sel_shapes.append(temp_shape)
  2351. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2352. for obj_shape in self.storage.get_objects():
  2353. try:
  2354. geometric_data = obj_shape.geo
  2355. if eraser_sel_shapes.intersects(geometric_data):
  2356. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2357. except KeyError:
  2358. pass
  2359. self.draw_app.delete_utility_geometry()
  2360. self.draw_app.plot_all()
  2361. self.draw_app.app.inform.emit(_("[success] Done. Eraser tool action completed."))
  2362. def utility_geometry(self, data=None):
  2363. """
  2364. Temporary geometry on screen while using this tool.
  2365. :param data:
  2366. :return:
  2367. """
  2368. geo_list = []
  2369. if self.origin is None:
  2370. return None
  2371. if len(self.draw_app.get_selected()) == 0:
  2372. return None
  2373. dx = data[0] - self.origin[0]
  2374. dy = data[1] - self.origin[1]
  2375. try:
  2376. for geom in self.draw_app.get_selected():
  2377. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2378. except AttributeError:
  2379. self.draw_app.select_tool('select')
  2380. self.draw_app.selected = []
  2381. return
  2382. return DrawToolUtilityShape(geo_list)
  2383. def clean_up(self):
  2384. self.draw_app.selected = []
  2385. self.draw_app.plot_all()
  2386. class FCPaint(FCShapeTool):
  2387. def __init__(self, draw_app):
  2388. FCShapeTool.__init__(self, draw_app)
  2389. self.name = 'paint'
  2390. # self.shape_buffer = self.draw_app.shape_buffer
  2391. self.draw_app = draw_app
  2392. self.app = draw_app.app
  2393. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2394. self.origin = (0, 0)
  2395. self.draw_app.paint_tool.run()
  2396. class FCTransform(FCShapeTool):
  2397. def __init__(self, draw_app):
  2398. FCShapeTool.__init__(self, draw_app)
  2399. self.name = 'transformation'
  2400. # self.shape_buffer = self.draw_app.shape_buffer
  2401. self.draw_app = draw_app
  2402. self.app = draw_app.app
  2403. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2404. self.origin = (0, 0)
  2405. self.draw_app.transform_tool.run()
  2406. # ###############################################
  2407. # ################ Main Application #############
  2408. # ###############################################
  2409. class FlatCAMGeoEditor(QtCore.QObject):
  2410. transform_complete = QtCore.pyqtSignal()
  2411. draw_shape_idx = -1
  2412. def __init__(self, app, disabled=False):
  2413. assert isinstance(app, FlatCAMApp.App), \
  2414. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2415. super(FlatCAMGeoEditor, self).__init__()
  2416. self.app = app
  2417. self.canvas = app.plotcanvas
  2418. # ## Toolbar events and properties
  2419. self.tools = {
  2420. "select": {"button": self.app.ui.geo_select_btn,
  2421. "constructor": FCSelect},
  2422. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2423. "constructor": FCArc},
  2424. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2425. "constructor": FCCircle},
  2426. "path": {"button": self.app.ui.geo_add_path_btn,
  2427. "constructor": FCPath},
  2428. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2429. "constructor": FCRectangle},
  2430. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2431. "constructor": FCPolygon},
  2432. "text": {"button": self.app.ui.geo_add_text_btn,
  2433. "constructor": FCText},
  2434. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2435. "constructor": FCBuffer},
  2436. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2437. "constructor": FCPaint},
  2438. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2439. "constructor": FCEraser},
  2440. "move": {"button": self.app.ui.geo_move_btn,
  2441. "constructor": FCMove},
  2442. "transform": {"button": self.app.ui.geo_transform_btn,
  2443. "constructor": FCTransform},
  2444. "copy": {"button": self.app.ui.geo_copy_btn,
  2445. "constructor": FCCopy}
  2446. }
  2447. # # ## Data
  2448. self.active_tool = None
  2449. self.storage = FlatCAMGeoEditor.make_storage()
  2450. self.utility = []
  2451. # VisPy visuals
  2452. self.fcgeometry = None
  2453. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2454. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2455. self.app.pool_recreated.connect(self.pool_recreated)
  2456. # Remove from scene
  2457. self.shapes.enabled = False
  2458. self.tool_shape.enabled = False
  2459. # List of selected shapes.
  2460. self.selected = []
  2461. self.flat_geo = []
  2462. self.move_timer = QtCore.QTimer()
  2463. self.move_timer.setSingleShot(True)
  2464. # this var will store the state of the toolbar before starting the editor
  2465. self.toolbar_old_state = False
  2466. self.key = None # Currently pressed key
  2467. self.geo_key_modifiers = None
  2468. self.x = None # Current mouse cursor pos
  2469. self.y = None
  2470. # if we edit a multigeo geometry store here the tool number
  2471. self.multigeo_tool = None
  2472. # Current snapped mouse pos
  2473. self.snap_x = None
  2474. self.snap_y = None
  2475. self.pos = None
  2476. # signal that there is an action active like polygon or path
  2477. self.in_action = False
  2478. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2479. self.launched_from_shortcuts = False
  2480. def make_callback(thetool):
  2481. def f():
  2482. self.on_tool_select(thetool)
  2483. return f
  2484. for tool in self.tools:
  2485. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2486. self.tools[tool]["button"].setCheckable(True) # Checkable
  2487. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2488. self.app.ui.corner_snap_btn.setCheckable(True)
  2489. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2490. self.options = {
  2491. "global_gridx": 0.1,
  2492. "global_gridy": 0.1,
  2493. "global_snap_max": 0.05,
  2494. "grid_snap": True,
  2495. "corner_snap": False,
  2496. "grid_gap_link": True
  2497. }
  2498. self.app.options_read_form()
  2499. for option in self.options:
  2500. if option in self.app.options:
  2501. self.options[option] = self.app.options[option]
  2502. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2503. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2504. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2505. self.app.ui.grid_gap_link_cb.setChecked(True)
  2506. self.rtree_index = rtindex.Index()
  2507. def entry2option(option, entry):
  2508. try:
  2509. self.options[option] = float(entry.text())
  2510. except Exception as e:
  2511. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2512. return
  2513. def gridx_changed(goption, gentry):
  2514. entry2option(option=goption, entry=gentry)
  2515. # if the grid link is checked copy the value in the GridX field to GridY
  2516. try:
  2517. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2518. except ValueError:
  2519. return
  2520. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2521. dec = 6 if units == 'IN' else 4
  2522. if self.app.ui.grid_gap_link_cb.isChecked():
  2523. self.app.ui.grid_gap_y_entry.set_value(val, decimals=dec)
  2524. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2525. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2526. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2527. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2528. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2529. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2530. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2531. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2532. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2533. # if using Paint store here the tool diameter used
  2534. self.paint_tooldia = None
  2535. self.paint_tool = PaintOptionsTool(self.app, self)
  2536. self.transform_tool = TransformEditorTool(self.app, self)
  2537. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2538. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2539. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2540. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2541. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2542. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2543. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2544. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2545. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2546. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2547. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2548. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2549. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2550. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2551. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2552. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2553. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2554. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2555. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2556. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2557. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2558. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2559. self.transform_complete.connect(self.on_transform_complete)
  2560. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2561. self.editor_active = False
  2562. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2563. def pool_recreated(self, pool):
  2564. self.shapes.pool = pool
  2565. self.tool_shape.pool = pool
  2566. def on_transform_complete(self):
  2567. self.delete_selected()
  2568. self.replot()
  2569. def activate(self):
  2570. # adjust the status of the menu entries related to the editor
  2571. self.app.ui.menueditedit.setDisabled(True)
  2572. self.app.ui.menueditok.setDisabled(False)
  2573. # adjust the visibility of some of the canvas context menu
  2574. self.app.ui.popmenu_edit.setVisible(False)
  2575. self.app.ui.popmenu_save.setVisible(True)
  2576. self.connect_canvas_event_handlers()
  2577. # initialize working objects
  2578. self.storage = FlatCAMGeoEditor.make_storage()
  2579. self.utility = []
  2580. self.selected = []
  2581. self.shapes.enabled = True
  2582. self.tool_shape.enabled = True
  2583. self.app.app_cursor.enabled = True
  2584. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2585. self.app.ui.corner_snap_btn.setEnabled(True)
  2586. self.app.ui.snap_magnet.setVisible(True)
  2587. self.app.ui.corner_snap_btn.setVisible(True)
  2588. self.app.ui.geo_editor_menu.setDisabled(False)
  2589. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2590. self.app.ui.update_obj_btn.setEnabled(True)
  2591. self.app.ui.g_editor_cmenu.setEnabled(True)
  2592. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2593. self.app.ui.geo_edit_toolbar.setVisible(True)
  2594. self.app.ui.snap_toolbar.setDisabled(False)
  2595. self.app.ui.popmenu_disable.setVisible(False)
  2596. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2597. self.app.ui.popmenu_properties.setVisible(False)
  2598. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2599. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2600. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2601. for w in sel_tab_widget_list:
  2602. w.setEnabled(False)
  2603. # Tell the App that the editor is active
  2604. self.editor_active = True
  2605. log.debug("Finished activating the Geometry Editor...")
  2606. def deactivate(self):
  2607. try:
  2608. QtGui.QGuiApplication.restoreOverrideCursor()
  2609. except Exception as e:
  2610. pass
  2611. # adjust the status of the menu entries related to the editor
  2612. self.app.ui.menueditedit.setDisabled(False)
  2613. self.app.ui.menueditok.setDisabled(True)
  2614. # adjust the visibility of some of the canvas context menu
  2615. self.app.ui.popmenu_edit.setVisible(True)
  2616. self.app.ui.popmenu_save.setVisible(False)
  2617. self.disconnect_canvas_event_handlers()
  2618. self.clear()
  2619. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2620. settings = QSettings("Open Source", "FlatCAM")
  2621. if settings.contains("layout"):
  2622. layout = settings.value('layout', type=str)
  2623. if layout == 'standard':
  2624. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2625. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2626. self.app.ui.corner_snap_btn.setEnabled(False)
  2627. self.app.ui.snap_magnet.setVisible(False)
  2628. self.app.ui.corner_snap_btn.setVisible(False)
  2629. elif layout == 'compact':
  2630. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2631. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2632. self.app.ui.corner_snap_btn.setEnabled(False)
  2633. else:
  2634. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2635. self.app.ui.snap_magnet.setVisible(False)
  2636. self.app.ui.corner_snap_btn.setVisible(False)
  2637. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2638. self.app.ui.corner_snap_btn.setEnabled(False)
  2639. # set the Editor Toolbar visibility to what was before entering in the Editor
  2640. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2641. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2642. # Disable visuals
  2643. self.shapes.enabled = False
  2644. self.tool_shape.enabled = False
  2645. self.app.app_cursor.enabled = False
  2646. self.app.ui.geo_editor_menu.setDisabled(True)
  2647. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2648. self.app.ui.update_obj_btn.setEnabled(False)
  2649. self.app.ui.g_editor_cmenu.setEnabled(False)
  2650. self.app.ui.e_editor_cmenu.setEnabled(False)
  2651. # Tell the app that the editor is no longer active
  2652. self.editor_active = False
  2653. self.app.ui.popmenu_disable.setVisible(True)
  2654. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2655. self.app.ui.popmenu_properties.setVisible(True)
  2656. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2657. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2658. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2659. try:
  2660. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2661. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2662. for w in sel_tab_widget_list:
  2663. w.setEnabled(True)
  2664. except Exception as e:
  2665. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2666. # Show original geometry
  2667. if self.fcgeometry:
  2668. self.fcgeometry.visible = True
  2669. log.debug("Finished deactivating the Geometry Editor...")
  2670. def connect_canvas_event_handlers(self):
  2671. # Canvas events
  2672. # first connect to new, then disconnect the old handlers
  2673. # don't ask why but if there is nothing connected I've seen issues
  2674. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2675. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2676. self.canvas.vis_connect('mouse_release', self.on_geo_click_release)
  2677. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2678. # but those from FlatCAMGeoEditor
  2679. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2680. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2681. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2682. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2683. # self.app.collection.view.clicked.disconnect()
  2684. self.app.ui.popmenu_copy.triggered.disconnect()
  2685. self.app.ui.popmenu_delete.triggered.disconnect()
  2686. self.app.ui.popmenu_move.triggered.disconnect()
  2687. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  2688. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2689. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  2690. # Geometry Editor
  2691. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  2692. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  2693. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  2694. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  2695. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  2696. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  2697. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  2698. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  2699. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  2700. self.app.ui.draw_union.triggered.connect(self.union)
  2701. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  2702. self.app.ui.draw_substract.triggered.connect(self.subtract)
  2703. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  2704. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  2705. self.app.ui.draw_move.triggered.connect(self.on_move)
  2706. def disconnect_canvas_event_handlers(self):
  2707. # we restore the key and mouse control to FlatCAMApp method
  2708. # first connect to new, then disconnect the old handlers
  2709. # don't ask why but if there is nothing connected I've seen issues
  2710. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2711. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2712. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2713. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2714. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2715. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2716. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2717. self.canvas.vis_disconnect('mouse_release', self.on_geo_click_release)
  2718. try:
  2719. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  2720. except (TypeError, AttributeError):
  2721. pass
  2722. try:
  2723. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2724. except (TypeError, AttributeError):
  2725. pass
  2726. try:
  2727. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  2728. except (TypeError, AttributeError):
  2729. pass
  2730. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2731. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2732. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2733. # Geometry Editor
  2734. try:
  2735. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  2736. except (TypeError, AttributeError):
  2737. pass
  2738. try:
  2739. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  2740. except (TypeError, AttributeError):
  2741. pass
  2742. try:
  2743. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  2744. except (TypeError, AttributeError):
  2745. pass
  2746. try:
  2747. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  2748. except (TypeError, AttributeError):
  2749. pass
  2750. try:
  2751. self.app.ui.draw_circle.triggered.disconnect()
  2752. except (TypeError, AttributeError):
  2753. pass
  2754. try:
  2755. self.app.ui.draw_poly.triggered.disconnect()
  2756. except (TypeError, AttributeError):
  2757. pass
  2758. try:
  2759. self.app.ui.draw_arc.triggered.disconnect()
  2760. except (TypeError, AttributeError):
  2761. pass
  2762. try:
  2763. self.app.ui.draw_text.triggered.disconnect()
  2764. except (TypeError, AttributeError):
  2765. pass
  2766. try:
  2767. self.app.ui.draw_buffer.triggered.disconnect()
  2768. except (TypeError, AttributeError):
  2769. pass
  2770. try:
  2771. self.app.ui.draw_paint.triggered.disconnect()
  2772. except (TypeError, AttributeError):
  2773. pass
  2774. try:
  2775. self.app.ui.draw_eraser.triggered.disconnect()
  2776. except (TypeError, AttributeError):
  2777. pass
  2778. try:
  2779. self.app.ui.draw_union.triggered.disconnect(self.union)
  2780. except (TypeError, AttributeError):
  2781. pass
  2782. try:
  2783. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  2784. except (TypeError, AttributeError):
  2785. pass
  2786. try:
  2787. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  2788. except (TypeError, AttributeError):
  2789. pass
  2790. try:
  2791. self.app.ui.draw_transform.triggered.disconnect()
  2792. except (TypeError, AttributeError):
  2793. pass
  2794. def add_shape(self, shape):
  2795. """
  2796. Adds a shape to the shape storage.
  2797. :param shape: Shape to be added.
  2798. :type shape: DrawToolShape
  2799. :return: None
  2800. """
  2801. if shape is None:
  2802. return
  2803. # List of DrawToolShape?
  2804. if isinstance(shape, list):
  2805. for subshape in shape:
  2806. self.add_shape(subshape)
  2807. return
  2808. assert isinstance(shape, DrawToolShape), \
  2809. "Expected a DrawToolShape, got %s" % type(shape)
  2810. assert shape.geo is not None, \
  2811. "Shape object has empty geometry (None)"
  2812. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2813. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  2814. if isinstance(shape, DrawToolUtilityShape):
  2815. self.utility.append(shape)
  2816. else:
  2817. self.storage.insert(shape) # TODO: Check performance
  2818. def delete_utility_geometry(self):
  2819. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2820. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2821. for_deletion = [shape for shape in self.utility]
  2822. for shape in for_deletion:
  2823. self.delete_shape(shape)
  2824. self.tool_shape.clear(update=True)
  2825. self.tool_shape.redraw()
  2826. def toolbar_tool_toggle(self, key):
  2827. self.options[key] = self.sender().isChecked()
  2828. return 1 if self.options[key] == True else 0
  2829. def clear(self):
  2830. self.active_tool = None
  2831. # self.shape_buffer = []
  2832. self.selected = []
  2833. self.shapes.clear(update=True)
  2834. self.tool_shape.clear(update=True)
  2835. # self.storage = FlatCAMGeoEditor.make_storage()
  2836. self.replot()
  2837. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2838. """
  2839. Imports the geometry from the given FlatCAM Geometry object
  2840. into the editor.
  2841. :param fcgeometry: FlatCAMGeometry
  2842. :param multigeo_tool: a tool for the case of multigeo
  2843. :return: None
  2844. """
  2845. assert isinstance(fcgeometry, Geometry), \
  2846. "Expected a Geometry, got %s" % type(fcgeometry)
  2847. self.deactivate()
  2848. self.activate()
  2849. # Hide original geometry
  2850. self.fcgeometry = fcgeometry
  2851. fcgeometry.visible = False
  2852. # Set selection tolerance
  2853. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2854. self.select_tool("select")
  2855. # Link shapes into editor.
  2856. if multigeo_tool:
  2857. self.multigeo_tool = multigeo_tool
  2858. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2859. self.app.inform.emit(_("[WARNING_NOTCL] Editing MultiGeo Geometry, tool: {tool} with diameter: {dia}").
  2860. format(tool=self.multigeo_tool, dia=fcgeometry.tools[self.multigeo_tool]['tooldia']))
  2861. else:
  2862. geo_to_edit = fcgeometry.flatten()
  2863. for shape in geo_to_edit:
  2864. if shape is not None: # TODO: Make flatten never create a None
  2865. if type(shape) == Polygon:
  2866. self.add_shape(DrawToolShape(shape.exterior))
  2867. for inter in shape.interiors:
  2868. self.add_shape(DrawToolShape(inter))
  2869. else:
  2870. self.add_shape(DrawToolShape(shape))
  2871. self.replot()
  2872. # start with GRID toolbar activated
  2873. if self.app.ui.grid_snap_btn.isChecked() is False:
  2874. self.app.ui.grid_snap_btn.trigger()
  2875. def on_buffer_tool(self):
  2876. buff_tool = BufferSelectionTool(self.app, self)
  2877. buff_tool.run()
  2878. def on_paint_tool(self):
  2879. paint_tool = PaintOptionsTool(self.app, self)
  2880. paint_tool.run()
  2881. def on_tool_select(self, tool):
  2882. """
  2883. Behavior of the toolbar. Tool initialization.
  2884. :rtype : None
  2885. """
  2886. self.app.log.debug("on_tool_select('%s')" % tool)
  2887. # This is to make the group behave as radio group
  2888. if tool in self.tools:
  2889. if self.tools[tool]["button"].isChecked():
  2890. self.app.log.debug("%s is checked." % tool)
  2891. for t in self.tools:
  2892. if t != tool:
  2893. self.tools[t]["button"].setChecked(False)
  2894. self.active_tool = self.tools[tool]["constructor"](self)
  2895. else:
  2896. self.app.log.debug("%s is NOT checked." % tool)
  2897. for t in self.tools:
  2898. self.tools[t]["button"].setChecked(False)
  2899. self.select_tool('select')
  2900. self.active_tool = FCSelect(self)
  2901. def draw_tool_path(self):
  2902. self.select_tool('path')
  2903. return
  2904. def draw_tool_rectangle(self):
  2905. self.select_tool('rectangle')
  2906. return
  2907. def on_grid_toggled(self):
  2908. self.toolbar_tool_toggle("grid_snap")
  2909. # make sure that the cursor shape is enabled/disabled, too
  2910. if self.options['grid_snap'] is True:
  2911. self.app.app_cursor.enabled = True
  2912. else:
  2913. self.app.app_cursor.enabled = False
  2914. def on_canvas_click(self, event):
  2915. """
  2916. event.x and .y have canvas coordinates
  2917. event.xdaya and .ydata have plot coordinates
  2918. :param event: Event object dispatched by Matplotlib
  2919. :return: None
  2920. """
  2921. self.pos = self.canvas.translate_coords(event.pos)
  2922. if self.app.grid_status() == True:
  2923. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2924. self.app.app_cursor.enabled = True
  2925. # Update cursor
  2926. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2927. size=20)
  2928. else:
  2929. self.pos = (self.pos[0], self.pos[1])
  2930. self.app.app_cursor.enabled = False
  2931. if event.button == 1:
  2932. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2933. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2934. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2935. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2936. if modifiers == QtCore.Qt.ShiftModifier:
  2937. self.app.clipboard.setText(
  2938. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2939. return
  2940. # Selection with left mouse button
  2941. if self.active_tool is not None and event.button is 1:
  2942. # Dispatch event to active_tool
  2943. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  2944. # If it is a shape generating tool
  2945. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2946. self.on_shape_complete()
  2947. if isinstance(self.active_tool, FCText):
  2948. self.select_tool("select")
  2949. else:
  2950. self.select_tool(self.active_tool.name)
  2951. if isinstance(self.active_tool, FCSelect):
  2952. # self.app.log.debug("Replotting after click.")
  2953. self.replot()
  2954. else:
  2955. self.app.log.debug("No active tool to respond to click!")
  2956. def on_canvas_move(self, event):
  2957. """
  2958. Called on 'mouse_move' event
  2959. event.pos have canvas screen coordinates
  2960. :param event: Event object dispatched by VisPy SceneCavas
  2961. :return: None
  2962. """
  2963. pos = self.canvas.translate_coords(event.pos)
  2964. event.xdata, event.ydata = pos[0], pos[1]
  2965. self.x = event.xdata
  2966. self.y = event.ydata
  2967. self.app.ui.popMenu.mouse_is_panning = False
  2968. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2969. if event.button == 2:
  2970. if event.is_dragging:
  2971. self.app.ui.popMenu.mouse_is_panning = True
  2972. # return
  2973. else:
  2974. self.app.ui.popMenu.mouse_is_panning = False
  2975. if self.active_tool is None:
  2976. return
  2977. try:
  2978. x = float(event.xdata)
  2979. y = float(event.ydata)
  2980. except TypeError:
  2981. return
  2982. # ### Snap coordinates ###
  2983. if self.app.grid_status() == True:
  2984. x, y = self.snap(x, y)
  2985. self.app.app_cursor.enabled = True
  2986. # Update cursor
  2987. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2988. else:
  2989. self.app.app_cursor.enabled = False
  2990. self.snap_x = x
  2991. self.snap_y = y
  2992. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2993. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2994. "<b>Y</b>: %.4f" % (x, y))
  2995. if self.pos is None:
  2996. self.pos = (0, 0)
  2997. dx = x - self.pos[0]
  2998. dy = y - self.pos[1]
  2999. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3000. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3001. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3002. if event.button == 1 and event.is_dragging and isinstance(self.active_tool, FCEraser):
  3003. pass
  3004. else:
  3005. # ### Utility geometry (animated) ###
  3006. geo = self.active_tool.utility_geometry(data=(x, y))
  3007. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3008. # Remove any previous utility shape
  3009. self.tool_shape.clear(update=True)
  3010. self.draw_utility_geometry(geo=geo)
  3011. # ### Selection area on canvas section ###
  3012. dx = pos[0] - self.pos[0]
  3013. if event.is_dragging and event.button == 1:
  3014. self.app.delete_selection_shape()
  3015. if dx < 0:
  3016. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3017. color=self.app.defaults["global_alt_sel_line"],
  3018. face_color=self.app.defaults['global_alt_sel_fill'])
  3019. self.app.selection_type = False
  3020. else:
  3021. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3022. self.app.selection_type = True
  3023. else:
  3024. self.app.selection_type = None
  3025. def on_geo_click_release(self, event):
  3026. pos_canvas = self.canvas.translate_coords(event.pos)
  3027. if self.app.grid_status() == True:
  3028. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3029. else:
  3030. pos = (pos_canvas[0], pos_canvas[1])
  3031. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3032. # canvas menu
  3033. try:
  3034. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3035. # selection and then select a type of selection ("enclosing" or "touching")
  3036. if event.button == 1: # left click
  3037. if self.app.selection_type is not None:
  3038. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3039. self.app.selection_type = None
  3040. elif isinstance(self.active_tool, FCSelect):
  3041. # Dispatch event to active_tool
  3042. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3043. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3044. # self.app.inform.emit(msg)
  3045. self.replot()
  3046. elif event.button == 2: # right click
  3047. if self.app.ui.popMenu.mouse_is_panning == False:
  3048. if self.in_action is False:
  3049. try:
  3050. QtGui.QGuiApplication.restoreOverrideCursor()
  3051. except Exception as e:
  3052. pass
  3053. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3054. self.active_tool.complete = True
  3055. self.in_action = False
  3056. self.delete_utility_geometry()
  3057. self.app.inform.emit(_("[success] Done."))
  3058. self.select_tool('select')
  3059. else:
  3060. self.app.cursor = QtGui.QCursor()
  3061. self.app.populate_cmenu_grids()
  3062. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3063. else:
  3064. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3065. # right mouse click will finish the action
  3066. if isinstance(self.active_tool, FCShapeTool):
  3067. self.active_tool.click(self.snap(self.x, self.y))
  3068. self.active_tool.make()
  3069. if self.active_tool.complete:
  3070. self.on_shape_complete()
  3071. self.app.inform.emit(_("[success] Done."))
  3072. self.select_tool(self.active_tool.name)
  3073. except Exception as e:
  3074. log.warning("Error: %s" % str(e))
  3075. return
  3076. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3077. """
  3078. :param start_pos: mouse position when the selection LMB click was done
  3079. :param end_pos: mouse position when the left mouse button is released
  3080. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3081. :return:
  3082. """
  3083. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3084. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3085. if key_modifier == QtCore.Qt.ShiftModifier:
  3086. mod_key = 'Shift'
  3087. elif key_modifier == QtCore.Qt.ControlModifier:
  3088. mod_key = 'Control'
  3089. else:
  3090. mod_key = None
  3091. self.app.delete_selection_shape()
  3092. sel_objects_list = []
  3093. for obj in self.storage.get_objects():
  3094. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3095. poly_selection.intersects(obj.geo)):
  3096. sel_objects_list.append(obj)
  3097. if mod_key == self.app.defaults["global_mselect_key"]:
  3098. for obj in sel_objects_list:
  3099. if obj in self.selected:
  3100. self.selected.remove(obj)
  3101. else:
  3102. # add the object to the selected shapes
  3103. self.selected.append(obj)
  3104. else:
  3105. self.selected = []
  3106. self.selected = sel_objects_list
  3107. self.replot()
  3108. def draw_utility_geometry(self, geo):
  3109. # Add the new utility shape
  3110. try:
  3111. # this case is for the Font Parse
  3112. for el in list(geo.geo):
  3113. if type(el) == MultiPolygon:
  3114. for poly in el:
  3115. self.tool_shape.add(
  3116. shape=poly,
  3117. color=(self.app.defaults["global_draw_color"] + '80'),
  3118. update=False,
  3119. layer=0,
  3120. tolerance=None
  3121. )
  3122. elif type(el) == MultiLineString:
  3123. for linestring in el:
  3124. self.tool_shape.add(
  3125. shape=linestring,
  3126. color=(self.app.defaults["global_draw_color"] + '80'),
  3127. update=False,
  3128. layer=0,
  3129. tolerance=None
  3130. )
  3131. else:
  3132. self.tool_shape.add(
  3133. shape=el,
  3134. color=(self.app.defaults["global_draw_color"] + '80'),
  3135. update=False,
  3136. layer=0,
  3137. tolerance=None
  3138. )
  3139. except TypeError:
  3140. self.tool_shape.add(
  3141. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3142. update=False, layer=0, tolerance=None)
  3143. self.tool_shape.redraw()
  3144. def on_delete_btn(self):
  3145. self.delete_selected()
  3146. self.replot()
  3147. def delete_selected(self):
  3148. tempref = [s for s in self.selected]
  3149. for shape in tempref:
  3150. self.delete_shape(shape)
  3151. self.selected = []
  3152. def delete_shape(self, shape):
  3153. if shape in self.utility:
  3154. self.utility.remove(shape)
  3155. return
  3156. self.storage.remove(shape)
  3157. if shape in self.selected:
  3158. self.selected.remove(shape) # TODO: Check performance
  3159. def on_move(self):
  3160. # if not self.selected:
  3161. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3162. # return
  3163. self.app.ui.geo_move_btn.setChecked(True)
  3164. self.on_tool_select('move')
  3165. def on_move_click(self):
  3166. self.on_move()
  3167. self.active_tool.set_origin(self.snap(self.x, self.y))
  3168. def on_copy_click(self):
  3169. if not self.selected:
  3170. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3171. return
  3172. self.app.ui.geo_copy_btn.setChecked(True)
  3173. self.app.geo_editor.on_tool_select('copy')
  3174. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3175. self.app.geo_editor.x, self.app.geo_editor.y))
  3176. self.app.inform.emit(_("Click on target point."))
  3177. def on_corner_snap(self):
  3178. self.app.ui.corner_snap_btn.trigger()
  3179. def get_selected(self):
  3180. """
  3181. Returns list of shapes that are selected in the editor.
  3182. :return: List of shapes.
  3183. """
  3184. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3185. return self.selected
  3186. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3187. """
  3188. Plots a geometric object or list of objects without rendering. Plotted objects
  3189. are returned as a list. This allows for efficient/animated rendering.
  3190. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3191. :param color: Shape color
  3192. :param linewidth: Width of lines in # of pixels.
  3193. :return: List of plotted elements.
  3194. """
  3195. plot_elements = []
  3196. if geometry is None:
  3197. geometry = self.active_tool.geometry
  3198. try:
  3199. for geo in geometry:
  3200. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3201. # Non-iterable
  3202. except TypeError:
  3203. # DrawToolShape
  3204. if isinstance(geometry, DrawToolShape):
  3205. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3206. # Polygon: Descend into exterior and each interior.
  3207. if type(geometry) == Polygon:
  3208. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3209. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3210. if type(geometry) == LineString or type(geometry) == LinearRing:
  3211. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3212. tolerance=self.fcgeometry.drawing_tolerance))
  3213. if type(geometry) == Point:
  3214. pass
  3215. return plot_elements
  3216. def plot_all(self):
  3217. """
  3218. Plots all shapes in the editor.
  3219. :return: None
  3220. :rtype: None
  3221. """
  3222. # self.app.log.debug("plot_all()")
  3223. self.shapes.clear(update=True)
  3224. for shape in self.storage.get_objects():
  3225. if shape.geo is None: # TODO: This shouldn't have happened
  3226. continue
  3227. if shape in self.selected:
  3228. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3229. continue
  3230. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3231. for shape in self.utility:
  3232. self.plot_shape(geometry=shape.geo, linewidth=1)
  3233. continue
  3234. self.shapes.redraw()
  3235. def replot(self):
  3236. self.plot_all()
  3237. def on_shape_complete(self):
  3238. self.app.log.debug("on_shape_complete()")
  3239. # Add shape
  3240. self.add_shape(self.active_tool.geometry)
  3241. # Remove any utility shapes
  3242. self.delete_utility_geometry()
  3243. self.tool_shape.clear(update=True)
  3244. # Replot and reset tool.
  3245. self.replot()
  3246. # self.active_tool = type(self.active_tool)(self)
  3247. @staticmethod
  3248. def make_storage():
  3249. # Shape storage.
  3250. storage = FlatCAMRTreeStorage()
  3251. storage.get_points = DrawToolShape.get_pts
  3252. return storage
  3253. def select_tool(self, toolname):
  3254. """
  3255. Selects a drawing tool. Impacts the object and GUI.
  3256. :param toolname: Name of the tool.
  3257. :return: None
  3258. """
  3259. self.tools[toolname]["button"].setChecked(True)
  3260. self.on_tool_select(toolname)
  3261. def set_selected(self, shape):
  3262. # Remove and add to the end.
  3263. if shape in self.selected:
  3264. self.selected.remove(shape)
  3265. self.selected.append(shape)
  3266. def set_unselected(self, shape):
  3267. if shape in self.selected:
  3268. self.selected.remove(shape)
  3269. def snap(self, x, y):
  3270. """
  3271. Adjusts coordinates to snap settings.
  3272. :param x: Input coordinate X
  3273. :param y: Input coordinate Y
  3274. :return: Snapped (x, y)
  3275. """
  3276. snap_x, snap_y = (x, y)
  3277. snap_distance = Inf
  3278. # # ## Object (corner?) snap
  3279. # # ## No need for the objects, just the coordinates
  3280. # # ## in the index.
  3281. if self.options["corner_snap"]:
  3282. try:
  3283. nearest_pt, shape = self.storage.nearest((x, y))
  3284. nearest_pt_distance = distance((x, y), nearest_pt)
  3285. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3286. snap_distance = nearest_pt_distance
  3287. snap_x, snap_y = nearest_pt
  3288. except (StopIteration, AssertionError):
  3289. pass
  3290. # # ## Grid snap
  3291. if self.options["grid_snap"]:
  3292. if self.options["global_gridx"] != 0:
  3293. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3294. else:
  3295. snap_x_ = x
  3296. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3297. # and it will use the snap distance from GridX entry
  3298. if self.app.ui.grid_gap_link_cb.isChecked():
  3299. if self.options["global_gridx"] != 0:
  3300. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3301. else:
  3302. snap_y_ = y
  3303. else:
  3304. if self.options["global_gridy"] != 0:
  3305. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3306. else:
  3307. snap_y_ = y
  3308. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3309. if nearest_grid_distance < snap_distance:
  3310. snap_x, snap_y = (snap_x_, snap_y_)
  3311. return snap_x, snap_y
  3312. def update_fcgeometry(self, fcgeometry):
  3313. """
  3314. Transfers the geometry tool shape buffer to the selected geometry
  3315. object. The geometry already in the object are removed.
  3316. :param fcgeometry: FlatCAMGeometry
  3317. :return: None
  3318. """
  3319. if self.multigeo_tool:
  3320. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3321. # for shape in self.shape_buffer:
  3322. for shape in self.storage.get_objects():
  3323. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  3324. self.multigeo_tool = None
  3325. else:
  3326. fcgeometry.solid_geometry = []
  3327. # for shape in self.shape_buffer:
  3328. for shape in self.storage.get_objects():
  3329. fcgeometry.solid_geometry.append(shape.geo)
  3330. def update_options(self, obj):
  3331. if self.paint_tooldia:
  3332. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3333. self.paint_tooldia = None
  3334. return True
  3335. else:
  3336. return False
  3337. def union(self):
  3338. """
  3339. Makes union of selected polygons. Original polygons
  3340. are deleted.
  3341. :return: None.
  3342. """
  3343. results = unary_union([t.geo for t in self.get_selected()])
  3344. # Delete originals.
  3345. for_deletion = [s for s in self.get_selected()]
  3346. for shape in for_deletion:
  3347. self.delete_shape(shape)
  3348. # Selected geometry is now gone!
  3349. self.selected = []
  3350. self.add_shape(DrawToolShape(results))
  3351. self.replot()
  3352. def intersection_2(self):
  3353. """
  3354. Makes intersection of selected polygons. Original polygons are deleted.
  3355. :return: None
  3356. """
  3357. geo_shapes = self.get_selected()
  3358. try:
  3359. results = geo_shapes[0].geo
  3360. except Exception as e:
  3361. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3362. self.app.inform.emit(
  3363. _("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3364. self.select_tool('select')
  3365. return
  3366. for shape_el in geo_shapes[1:]:
  3367. results = results.intersection(shape_el.geo)
  3368. # Delete originals.
  3369. for_deletion = [s for s in self.get_selected()]
  3370. for shape_el in for_deletion:
  3371. self.delete_shape(shape_el)
  3372. # Selected geometry is now gone!
  3373. self.selected = []
  3374. self.add_shape(DrawToolShape(results))
  3375. self.replot()
  3376. def intersection(self):
  3377. """
  3378. Makes intersection of selected polygons. Original polygons are deleted.
  3379. :return: None
  3380. """
  3381. geo_shapes = self.get_selected()
  3382. results = []
  3383. intact = []
  3384. try:
  3385. intersector = geo_shapes[0].geo
  3386. except Exception as e:
  3387. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3388. self.app.inform.emit(
  3389. _("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3390. self.select_tool('select')
  3391. return
  3392. for shape_el in geo_shapes[1:]:
  3393. if intersector.intersects(shape_el.geo):
  3394. results.append(intersector.intersection(shape_el.geo))
  3395. else:
  3396. intact.append(shape_el)
  3397. if len(results) != 0:
  3398. # Delete originals.
  3399. for_deletion = [s for s in self.get_selected()]
  3400. for shape_el in for_deletion:
  3401. if shape_el not in intact:
  3402. self.delete_shape(shape_el)
  3403. for geo in results:
  3404. self.add_shape(DrawToolShape(geo))
  3405. # Selected geometry is now gone!
  3406. self.selected = []
  3407. self.replot()
  3408. def subtract(self):
  3409. selected = self.get_selected()
  3410. try:
  3411. tools = selected[1:]
  3412. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3413. target = selected[0].geo
  3414. target = target.buffer(0.0000001)
  3415. result = target.difference(toolgeo)
  3416. for_deletion = [s for s in self.get_selected()]
  3417. for shape in for_deletion:
  3418. self.delete_shape(shape)
  3419. self.add_shape(DrawToolShape(result))
  3420. self.replot()
  3421. except Exception as e:
  3422. log.debug(str(e))
  3423. def subtract_2(self):
  3424. selected = self.get_selected()
  3425. try:
  3426. tools = selected[1:]
  3427. toolgeo = unary_union([shp.geo for shp in tools])
  3428. result = selected[0].geo.difference(toolgeo)
  3429. self.delete_shape(selected[0])
  3430. self.add_shape(DrawToolShape(result))
  3431. self.replot()
  3432. except Exception as e:
  3433. log.debug(str(e))
  3434. def cutpath(self):
  3435. selected = self.get_selected()
  3436. tools = selected[1:]
  3437. toolgeo = unary_union([shp.geo for shp in tools])
  3438. target = selected[0]
  3439. if type(target.geo) == Polygon:
  3440. for ring in poly2rings(target.geo):
  3441. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3442. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3443. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3444. elif type(target.geo) == MultiLineString:
  3445. try:
  3446. for linestring in target.geo:
  3447. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3448. except Exception as e:
  3449. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3450. else:
  3451. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3452. return
  3453. self.delete_shape(target)
  3454. self.replot()
  3455. def buffer(self, buf_distance, join_style):
  3456. selected = self.get_selected()
  3457. if buf_distance < 0:
  3458. self.app.inform.emit(
  3459. _("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3460. "Use Buffer interior to generate an 'inside' shape"))
  3461. # deselect everything
  3462. self.selected = []
  3463. self.replot()
  3464. return 'fail'
  3465. if len(selected) == 0:
  3466. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3467. return 'fail'
  3468. if not isinstance(buf_distance, float):
  3469. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3470. # deselect everything
  3471. self.selected = []
  3472. self.replot()
  3473. return 'fail'
  3474. results = []
  3475. for t in selected:
  3476. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3477. results.append((t.geo.exterior).buffer(
  3478. buf_distance - 1e-10,
  3479. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3480. join_style=join_style)
  3481. )
  3482. else:
  3483. results.append(t.geo.buffer(
  3484. buf_distance - 1e-10,
  3485. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3486. join_style=join_style)
  3487. )
  3488. if not results:
  3489. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3490. # deselect everything
  3491. self.selected = []
  3492. self.replot()
  3493. return 'fail'
  3494. for sha in results:
  3495. self.add_shape(DrawToolShape(sha))
  3496. self.replot()
  3497. self.app.inform.emit(_("[success] Full buffer geometry created."))
  3498. def buffer_int(self, buf_distance, join_style):
  3499. selected = self.get_selected()
  3500. if buf_distance < 0:
  3501. self.app.inform.emit(
  3502. _("[ERROR_NOTCL] Negative buffer value is not accepted.")
  3503. )
  3504. # deselect everything
  3505. self.selected = []
  3506. self.replot()
  3507. return 'fail'
  3508. if len(selected) == 0:
  3509. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3510. return 'fail'
  3511. if not isinstance(buf_distance, float):
  3512. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3513. # deselect everything
  3514. self.selected = []
  3515. self.replot()
  3516. return 'fail'
  3517. results = []
  3518. for t in selected:
  3519. if isinstance(t.geo, LinearRing):
  3520. t.geo = Polygon(t.geo)
  3521. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3522. results.append((t.geo).buffer(
  3523. -buf_distance + 1e-10,
  3524. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3525. join_style=join_style)
  3526. )
  3527. if not results:
  3528. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a smaller buffer value."))
  3529. # deselect everything
  3530. self.selected = []
  3531. self.replot()
  3532. return 'fail'
  3533. for sha in results:
  3534. self.add_shape(DrawToolShape(sha))
  3535. self.replot()
  3536. self.app.inform.emit(_("[success] Interior buffer geometry created."))
  3537. def buffer_ext(self, buf_distance, join_style):
  3538. selected = self.get_selected()
  3539. if buf_distance < 0:
  3540. self.app.inform.emit(_("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3541. "Use Buffer interior to generate an 'inside' shape"))
  3542. # deselect everything
  3543. self.selected = []
  3544. self.replot()
  3545. return
  3546. if len(selected) == 0:
  3547. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3548. return
  3549. if not isinstance(buf_distance, float):
  3550. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3551. # deselect everything
  3552. self.selected = []
  3553. self.replot()
  3554. return
  3555. results = []
  3556. for t in selected:
  3557. if isinstance(t.geo, LinearRing):
  3558. t.geo = Polygon(t.geo)
  3559. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3560. results.append((t.geo).buffer(
  3561. buf_distance,
  3562. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3563. join_style=join_style)
  3564. )
  3565. if not results:
  3566. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3567. # deselect everything
  3568. self.selected = []
  3569. self.replot()
  3570. return
  3571. for sha in results:
  3572. self.add_shape(DrawToolShape(sha))
  3573. self.replot()
  3574. self.app.inform.emit(_("[success] Exterior buffer geometry created."))
  3575. # def paint(self, tooldia, overlap, margin, method):
  3576. # selected = self.get_selected()
  3577. #
  3578. # if len(selected) == 0:
  3579. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3580. # return
  3581. #
  3582. # for param in [tooldia, overlap, margin]:
  3583. # if not isinstance(param, float):
  3584. # param_name = [k for k, v in locals().items() if v is param][0]
  3585. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3586. #
  3587. # # Todo: Check for valid method.
  3588. #
  3589. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3590. #
  3591. # results = []
  3592. #
  3593. # def recurse(geo):
  3594. # try:
  3595. # for subg in geo:
  3596. # for subsubg in recurse(subg):
  3597. # yield subsubg
  3598. # except TypeError:
  3599. # if isinstance(geo, LinearRing):
  3600. # yield geo
  3601. #
  3602. # raise StopIteration
  3603. #
  3604. # for geo in selected:
  3605. # print(type(geo.geo))
  3606. #
  3607. # local_results = []
  3608. # for poly in recurse(geo.geo):
  3609. # if method == "seed":
  3610. # # Type(cp) == FlatCAMRTreeStorage | None
  3611. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3612. # tooldia, overlap=overlap)
  3613. #
  3614. # else:
  3615. # # Type(cp) == FlatCAMRTreeStorage | None
  3616. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3617. # tooldia, overlap=overlap)
  3618. #
  3619. # if cp is not None:
  3620. # local_results += list(cp.get_objects())
  3621. #
  3622. # results.append(cascaded_union(local_results))
  3623. #
  3624. # # This is a dirty patch:
  3625. # for r in results:
  3626. # self.add_shape(DrawToolShape(r))
  3627. #
  3628. # self.replot()
  3629. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3630. self.paint_tooldia = tooldia
  3631. selected = self.get_selected()
  3632. if len(selected) == 0:
  3633. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for painting."))
  3634. return
  3635. for param in [tooldia, overlap, margin]:
  3636. if not isinstance(param, float):
  3637. param_name = [k for k, v in locals().items() if v is param][0]
  3638. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3639. results = []
  3640. if overlap >= 1:
  3641. self.app.inform.emit(
  3642. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3643. return
  3644. def recurse(geometry, reset=True):
  3645. """
  3646. Creates a list of non-iterable linear geometry objects.
  3647. Results are placed in self.flat_geometry
  3648. :param geometry: Shapely type or list or list of list of such.
  3649. :param reset: Clears the contents of self.flat_geometry.
  3650. """
  3651. if geometry is None:
  3652. return
  3653. if reset:
  3654. self.flat_geo = []
  3655. # If iterable, expand recursively.
  3656. try:
  3657. for geo_el in geometry:
  3658. if geo_el is not None:
  3659. recurse(geometry=geo_el, reset=False)
  3660. # Not iterable, do the actual indexing and add.
  3661. except TypeError:
  3662. self.flat_geo.append(geometry)
  3663. return self.flat_geo
  3664. for geo in selected:
  3665. local_results = []
  3666. for geo_obj in recurse(geo.geo):
  3667. try:
  3668. if type(geo_obj) == Polygon:
  3669. poly_buf = geo_obj.buffer(-margin)
  3670. else:
  3671. poly_buf = Polygon(geo_obj).buffer(-margin)
  3672. if method == "seed":
  3673. cp = Geometry.clear_polygon2(poly_buf,
  3674. tooldia, self.app.defaults["geometry_circle_steps"],
  3675. overlap=overlap, contour=contour, connect=connect)
  3676. elif method == "lines":
  3677. cp = Geometry.clear_polygon3(poly_buf,
  3678. tooldia, self.app.defaults["geometry_circle_steps"],
  3679. overlap=overlap, contour=contour, connect=connect)
  3680. else:
  3681. cp = Geometry.clear_polygon(poly_buf,
  3682. tooldia, self.app.defaults["geometry_circle_steps"],
  3683. overlap=overlap, contour=contour, connect=connect)
  3684. if cp is not None:
  3685. local_results += list(cp.get_objects())
  3686. except Exception as e:
  3687. log.debug("Could not Paint the polygons. %s" % str(e))
  3688. self.app.inform.emit(
  3689. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3690. "Or a different method of Paint\n%s") % str(e))
  3691. return
  3692. # add the result to the results list
  3693. results.append(cascaded_union(local_results))
  3694. # This is a dirty patch:
  3695. for r in results:
  3696. self.add_shape(DrawToolShape(r))
  3697. self.app.inform.emit(
  3698. _("[success] Paint done."))
  3699. self.replot()
  3700. def distance(pt1, pt2):
  3701. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3702. def mag(vec):
  3703. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3704. def poly2rings(poly):
  3705. return [poly.exterior] + [interior for interior in poly.interiors]
  3706. def get_shapely_list_bounds(geometry_list):
  3707. xmin = Inf
  3708. ymin = Inf
  3709. xmax = -Inf
  3710. ymax = -Inf
  3711. for gs in geometry_list:
  3712. try:
  3713. gxmin, gymin, gxmax, gymax = gs.bounds
  3714. xmin = min([xmin, gxmin])
  3715. ymin = min([ymin, gymin])
  3716. xmax = max([xmax, gxmax])
  3717. ymax = max([ymax, gymax])
  3718. except Exception as e:
  3719. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3720. return [xmin, ymin, xmax, ymax]