FlatCAMGeoEditor.py 148 KB

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