FlatCAMGeoEditor.py 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997
  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.snap_toolbar.setDisabled(False)
  2308. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2309. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2310. for w in sel_tab_widget_list:
  2311. w.setEnabled(False)
  2312. # Tell the App that the editor is active
  2313. self.editor_active = True
  2314. def deactivate(self):
  2315. self.disconnect_canvas_event_handlers()
  2316. self.clear()
  2317. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2318. settings = QSettings("Open Source", "FlatCAM")
  2319. if settings.contains("layout"):
  2320. layout = settings.value('layout', type=str)
  2321. if layout == 'Standard':
  2322. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2323. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2324. self.app.ui.corner_snap_btn.setEnabled(False)
  2325. self.app.ui.snap_magnet.setVisible(False)
  2326. self.app.ui.corner_snap_btn.setVisible(False)
  2327. elif layout == 'Compact':
  2328. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2329. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2330. self.app.ui.corner_snap_btn.setEnabled(False)
  2331. else:
  2332. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2333. self.app.ui.snap_magnet.setVisible(False)
  2334. self.app.ui.corner_snap_btn.setVisible(False)
  2335. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2336. self.app.ui.corner_snap_btn.setEnabled(False)
  2337. # set the Editor Toolbar visibility to what was before entering in the Editor
  2338. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2339. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2340. # Disable visuals
  2341. self.shapes.enabled = False
  2342. self.tool_shape.enabled = False
  2343. self.app.app_cursor.enabled = False
  2344. self.app.ui.geo_editor_menu.setDisabled(True)
  2345. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2346. self.app.ui.update_obj_btn.setEnabled(False)
  2347. self.app.ui.g_editor_cmenu.setEnabled(False)
  2348. self.app.ui.e_editor_cmenu.setEnabled(False)
  2349. # Tell the app that the editor is no longer active
  2350. self.editor_active = False
  2351. # Show original geometry
  2352. if self.fcgeometry:
  2353. self.fcgeometry.visible = True
  2354. def connect_canvas_event_handlers(self):
  2355. ## Canvas events
  2356. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2357. # but those from FlatCAMGeoEditor
  2358. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2359. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2360. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2361. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2362. self.app.collection.view.clicked.disconnect()
  2363. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2364. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2365. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  2366. def disconnect_canvas_event_handlers(self):
  2367. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2368. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2369. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  2370. # we restore the key and mouse control to FlatCAMApp method
  2371. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2372. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2373. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2374. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2375. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2376. def add_shape(self, shape):
  2377. """
  2378. Adds a shape to the shape storage.
  2379. :param shape: Shape to be added.
  2380. :type shape: DrawToolShape
  2381. :return: None
  2382. """
  2383. # List of DrawToolShape?
  2384. if isinstance(shape, list):
  2385. for subshape in shape:
  2386. self.add_shape(subshape)
  2387. return
  2388. assert isinstance(shape, DrawToolShape), \
  2389. "Expected a DrawToolShape, got %s" % type(shape)
  2390. assert shape.geo is not None, \
  2391. "Shape object has empty geometry (None)"
  2392. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2393. not isinstance(shape.geo, list), \
  2394. "Shape objects has empty geometry ([])"
  2395. if isinstance(shape, DrawToolUtilityShape):
  2396. self.utility.append(shape)
  2397. else:
  2398. self.storage.insert(shape) # TODO: Check performance
  2399. def delete_utility_geometry(self):
  2400. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2401. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2402. for_deletion = [shape for shape in self.utility]
  2403. for shape in for_deletion:
  2404. self.delete_shape(shape)
  2405. self.tool_shape.clear(update=True)
  2406. self.tool_shape.redraw()
  2407. def cutpath(self):
  2408. selected = self.get_selected()
  2409. tools = selected[1:]
  2410. toolgeo = cascaded_union([shp.geo for shp in tools])
  2411. target = selected[0]
  2412. if type(target.geo) == Polygon:
  2413. for ring in poly2rings(target.geo):
  2414. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2415. self.delete_shape(target)
  2416. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2417. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2418. self.delete_shape(target)
  2419. elif type(target.geo) == MultiLineString:
  2420. try:
  2421. for linestring in target.geo:
  2422. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2423. except:
  2424. self.app.log.warning("Current LinearString does not intersect the target")
  2425. self.delete_shape(target)
  2426. else:
  2427. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2428. self.replot()
  2429. def toolbar_tool_toggle(self, key):
  2430. self.options[key] = self.sender().isChecked()
  2431. if self.options[key] == True:
  2432. return 1
  2433. else:
  2434. return 0
  2435. def clear(self):
  2436. self.active_tool = None
  2437. # self.shape_buffer = []
  2438. self.selected = []
  2439. self.shapes.clear(update=True)
  2440. self.tool_shape.clear(update=True)
  2441. self.storage = FlatCAMGeoEditor.make_storage()
  2442. self.replot()
  2443. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2444. """
  2445. Imports the geometry from the given FlatCAM Geometry object
  2446. into the editor.
  2447. :param fcgeometry: FlatCAMGeometry
  2448. :return: None
  2449. """
  2450. assert isinstance(fcgeometry, Geometry), \
  2451. "Expected a Geometry, got %s" % type(fcgeometry)
  2452. self.deactivate()
  2453. self.activate()
  2454. # Hide original geometry
  2455. self.fcgeometry = fcgeometry
  2456. fcgeometry.visible = False
  2457. # Set selection tolerance
  2458. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2459. self.select_tool("select")
  2460. # Link shapes into editor.
  2461. if multigeo_tool:
  2462. self.multigeo_tool = multigeo_tool
  2463. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2464. self.app.inform.emit(_("[WARNING] Editing MultiGeo Geometry, tool: {tool} with diameter: {dia}").
  2465. format(tool=self.multigeo_tool, dia=fcgeometry.tools[self.multigeo_tool]['tooldia']))
  2466. else:
  2467. geo_to_edit = fcgeometry.flatten()
  2468. for shape in geo_to_edit:
  2469. if shape is not None: # TODO: Make flatten never create a None
  2470. if type(shape) == Polygon:
  2471. self.add_shape(DrawToolShape(shape.exterior))
  2472. for inter in shape.interiors:
  2473. self.add_shape(DrawToolShape(inter))
  2474. else:
  2475. self.add_shape(DrawToolShape(shape))
  2476. self.replot()
  2477. # start with GRID toolbar activated
  2478. if self.app.ui.grid_snap_btn.isChecked() == False:
  2479. self.app.ui.grid_snap_btn.trigger()
  2480. def on_buffer_tool(self):
  2481. buff_tool = BufferSelectionTool(self.app, self)
  2482. buff_tool.run()
  2483. def on_paint_tool(self):
  2484. paint_tool = PaintOptionsTool(self.app, self)
  2485. paint_tool.run()
  2486. def on_transform_tool(self):
  2487. transform_tool = TransformEditorTool(self.app, self)
  2488. transform_tool.run()
  2489. def on_tool_select(self, tool):
  2490. """
  2491. Behavior of the toolbar. Tool initialization.
  2492. :rtype : None
  2493. """
  2494. self.app.log.debug("on_tool_select('%s')" % tool)
  2495. # This is to make the group behave as radio group
  2496. if tool in self.tools:
  2497. if self.tools[tool]["button"].isChecked():
  2498. self.app.log.debug("%s is checked." % tool)
  2499. for t in self.tools:
  2500. if t != tool:
  2501. self.tools[t]["button"].setChecked(False)
  2502. self.active_tool = self.tools[tool]["constructor"](self)
  2503. if not isinstance(self.active_tool, FCSelect):
  2504. self.app.inform.emit(self.active_tool.start_msg)
  2505. else:
  2506. self.app.log.debug("%s is NOT checked." % tool)
  2507. for t in self.tools:
  2508. self.tools[t]["button"].setChecked(False)
  2509. self.active_tool = None
  2510. def draw_tool_path(self):
  2511. self.select_tool('path')
  2512. return
  2513. def draw_tool_rectangle(self):
  2514. self.select_tool('rectangle')
  2515. return
  2516. def on_grid_toggled(self):
  2517. self.toolbar_tool_toggle("grid_snap")
  2518. # make sure that the cursor shape is enabled/disabled, too
  2519. if self.options['grid_snap'] is True:
  2520. self.app.app_cursor.enabled = True
  2521. else:
  2522. self.app.app_cursor.enabled = False
  2523. def on_canvas_click(self, event):
  2524. """
  2525. event.x and .y have canvas coordinates
  2526. event.xdaya and .ydata have plot coordinates
  2527. :param event: Event object dispatched by Matplotlib
  2528. :return: None
  2529. """
  2530. if event.button is 1:
  2531. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2532. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2533. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2534. ### Snap coordinates
  2535. x, y = self.snap(self.pos[0], self.pos[1])
  2536. self.pos = (x, y)
  2537. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2538. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2539. if modifiers == QtCore.Qt.ShiftModifier:
  2540. self.app.clipboard.setText(
  2541. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2542. return
  2543. # Selection with left mouse button
  2544. if self.active_tool is not None and event.button is 1:
  2545. # Dispatch event to active_tool
  2546. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2547. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  2548. # If it is a shape generating tool
  2549. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2550. self.on_shape_complete()
  2551. # MS: always return to the Select Tool if modifier key is not pressed
  2552. # else return to the current tool
  2553. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2554. if self.app.defaults["global_mselect_key"] == 'Control':
  2555. modifier_to_use = Qt.ControlModifier
  2556. else:
  2557. modifier_to_use = Qt.ShiftModifier
  2558. # if modifier key is pressed then we add to the selected list the current shape but if
  2559. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  2560. if key_modifier == modifier_to_use:
  2561. self.select_tool(self.active_tool.name)
  2562. else:
  2563. self.select_tool("select")
  2564. return
  2565. if isinstance(self.active_tool, FCSelect):
  2566. # self.app.log.debug("Replotting after click.")
  2567. self.replot()
  2568. else:
  2569. self.app.log.debug("No active tool to respond to click!")
  2570. def on_canvas_move(self, event):
  2571. """
  2572. Called on 'mouse_move' event
  2573. event.pos have canvas screen coordinates
  2574. :param event: Event object dispatched by VisPy SceneCavas
  2575. :return: None
  2576. """
  2577. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2578. event.xdata, event.ydata = pos[0], pos[1]
  2579. self.x = event.xdata
  2580. self.y = event.ydata
  2581. # Prevent updates on pan
  2582. # if len(event.buttons) > 0:
  2583. # return
  2584. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2585. if event.button == 2:
  2586. self.app.panning_action = True
  2587. return
  2588. else:
  2589. self.app.panning_action = False
  2590. try:
  2591. x = float(event.xdata)
  2592. y = float(event.ydata)
  2593. except TypeError:
  2594. return
  2595. if self.active_tool is None:
  2596. return
  2597. ### Snap coordinates
  2598. x, y = self.snap(x, y)
  2599. self.snap_x = x
  2600. self.snap_y = y
  2601. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2602. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2603. "<b>Y</b>: %.4f" % (x, y))
  2604. if self.pos is None:
  2605. self.pos = (0, 0)
  2606. dx = x - self.pos[0]
  2607. dy = y - self.pos[1]
  2608. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2609. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2610. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2611. ### Utility geometry (animated)
  2612. geo = self.active_tool.utility_geometry(data=(x, y))
  2613. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2614. # Remove any previous utility shape
  2615. self.tool_shape.clear(update=True)
  2616. self.draw_utility_geometry(geo=geo)
  2617. ### Selection area on canvas section ###
  2618. dx = pos[0] - self.pos[0]
  2619. if event.is_dragging == 1 and event.button == 1:
  2620. self.app.delete_selection_shape()
  2621. if dx < 0:
  2622. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2623. color=self.app.defaults["global_alt_sel_line"],
  2624. face_color=self.app.defaults['global_alt_sel_fill'])
  2625. self.app.selection_type = False
  2626. else:
  2627. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2628. self.app.selection_type = True
  2629. else:
  2630. self.app.selection_type = None
  2631. # Update cursor
  2632. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2633. def on_canvas_click_release(self, event):
  2634. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2635. if self.app.grid_status():
  2636. pos = self.snap(pos_canvas[0], pos_canvas[1])
  2637. else:
  2638. pos = (pos_canvas[0], pos_canvas[1])
  2639. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2640. # canvas menu
  2641. try:
  2642. if event.button == 2: # right click
  2643. if self.app.panning_action is True:
  2644. self.app.panning_action = False
  2645. else:
  2646. if self.in_action is False:
  2647. self.app.cursor = QtGui.QCursor()
  2648. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2649. else:
  2650. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2651. # right mouse click will finish the action
  2652. if isinstance(self.active_tool, FCShapeTool):
  2653. self.active_tool.click(self.snap(self.x, self.y))
  2654. self.active_tool.make()
  2655. if self.active_tool.complete:
  2656. self.on_shape_complete()
  2657. self.app.inform.emit(_("[success] Done."))
  2658. # MS: always return to the Select Tool if modifier key is not pressed
  2659. # else return to the current tool
  2660. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2661. if self.app.defaults["global_mselect_key"] == 'Control':
  2662. modifier_to_use = Qt.ControlModifier
  2663. else:
  2664. modifier_to_use = Qt.ShiftModifier
  2665. if key_modifier == modifier_to_use:
  2666. self.select_tool(self.active_tool.name)
  2667. else:
  2668. self.select_tool("select")
  2669. except Exception as e:
  2670. log.warning("Error: %s" % str(e))
  2671. return
  2672. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2673. # selection and then select a type of selection ("enclosing" or "touching")
  2674. try:
  2675. if event.button == 1: # left click
  2676. if self.app.selection_type is not None:
  2677. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2678. self.app.selection_type = None
  2679. elif isinstance(self.active_tool, FCSelect):
  2680. # Dispatch event to active_tool
  2681. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2682. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2683. # self.app.inform.emit(msg)
  2684. self.replot()
  2685. except Exception as e:
  2686. log.warning("Error: %s" % str(e))
  2687. return
  2688. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2689. """
  2690. :param start_pos: mouse position when the selection LMB click was done
  2691. :param end_pos: mouse position when the left mouse button is released
  2692. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2693. :type Bool
  2694. :return:
  2695. """
  2696. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2697. self.app.delete_selection_shape()
  2698. for obj in self.storage.get_objects():
  2699. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2700. (sel_type is False and poly_selection.intersects(obj.geo)):
  2701. if self.key == self.app.defaults["global_mselect_key"]:
  2702. if obj in self.selected:
  2703. self.selected.remove(obj)
  2704. else:
  2705. # add the object to the selected shapes
  2706. self.selected.append(obj)
  2707. else:
  2708. if obj not in self.selected:
  2709. self.selected.append(obj)
  2710. self.replot()
  2711. def draw_utility_geometry(self, geo):
  2712. # Add the new utility shape
  2713. try:
  2714. # this case is for the Font Parse
  2715. for el in list(geo.geo):
  2716. if type(el) == MultiPolygon:
  2717. for poly in el:
  2718. self.tool_shape.add(
  2719. shape=poly,
  2720. color=(self.app.defaults["global_draw_color"] + '80'),
  2721. update=False,
  2722. layer=0,
  2723. tolerance=None
  2724. )
  2725. elif type(el) == MultiLineString:
  2726. for linestring in el:
  2727. self.tool_shape.add(
  2728. shape=linestring,
  2729. color=(self.app.defaults["global_draw_color"] + '80'),
  2730. update=False,
  2731. layer=0,
  2732. tolerance=None
  2733. )
  2734. else:
  2735. self.tool_shape.add(
  2736. shape=el,
  2737. color=(self.app.defaults["global_draw_color"] + '80'),
  2738. update=False,
  2739. layer=0,
  2740. tolerance=None
  2741. )
  2742. except TypeError:
  2743. self.tool_shape.add(
  2744. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2745. update=False, layer=0, tolerance=None)
  2746. self.tool_shape.redraw()
  2747. def on_delete_btn(self):
  2748. self.delete_selected()
  2749. self.replot()
  2750. def delete_selected(self):
  2751. tempref = [s for s in self.selected]
  2752. for shape in tempref:
  2753. self.delete_shape(shape)
  2754. self.selected = []
  2755. def delete_shape(self, shape):
  2756. if shape in self.utility:
  2757. self.utility.remove(shape)
  2758. return
  2759. self.storage.remove(shape)
  2760. if shape in self.selected:
  2761. self.selected.remove(shape) # TODO: Check performance
  2762. def on_move(self):
  2763. self.app.ui.geo_move_btn.setChecked(True)
  2764. self.on_tool_select('move')
  2765. def on_move_click(self):
  2766. if not self.selected:
  2767. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2768. return
  2769. self.on_move()
  2770. self.active_tool.set_origin(self.snap(self.x, self.y))
  2771. def on_copy_click(self):
  2772. if not self.selected:
  2773. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  2774. return
  2775. self.app.ui.geo_copy_btn.setChecked(True)
  2776. self.app.geo_editor.on_tool_select('copy')
  2777. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  2778. self.app.geo_editor.x, self.app.geo_editor.y))
  2779. self.app.inform.emit(_("Click on target point."))
  2780. def on_corner_snap(self):
  2781. self.app.ui.corner_snap_btn.trigger()
  2782. def get_selected(self):
  2783. """
  2784. Returns list of shapes that are selected in the editor.
  2785. :return: List of shapes.
  2786. """
  2787. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2788. return self.selected
  2789. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2790. """
  2791. Plots a geometric object or list of objects without rendering. Plotted objects
  2792. are returned as a list. This allows for efficient/animated rendering.
  2793. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2794. :param color: Shape color
  2795. :param linewidth: Width of lines in # of pixels.
  2796. :return: List of plotted elements.
  2797. """
  2798. plot_elements = []
  2799. if geometry is None:
  2800. geometry = self.active_tool.geometry
  2801. try:
  2802. for geo in geometry:
  2803. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2804. ## Non-iterable
  2805. except TypeError:
  2806. ## DrawToolShape
  2807. if isinstance(geometry, DrawToolShape):
  2808. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2809. ## Polygon: Descend into exterior and each interior.
  2810. if type(geometry) == Polygon:
  2811. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2812. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2813. if type(geometry) == LineString or type(geometry) == LinearRing:
  2814. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  2815. tolerance=self.fcgeometry.drawing_tolerance))
  2816. if type(geometry) == Point:
  2817. pass
  2818. return plot_elements
  2819. def plot_all(self):
  2820. """
  2821. Plots all shapes in the editor.
  2822. :return: None
  2823. :rtype: None
  2824. """
  2825. # self.app.log.debug("plot_all()")
  2826. self.shapes.clear(update=True)
  2827. for shape in self.storage.get_objects():
  2828. if shape.geo is None: # TODO: This shouldn't have happened
  2829. continue
  2830. if shape in self.selected:
  2831. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2832. continue
  2833. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2834. for shape in self.utility:
  2835. self.plot_shape(geometry=shape.geo, linewidth=1)
  2836. continue
  2837. self.shapes.redraw()
  2838. def replot(self):
  2839. self.plot_all()
  2840. def on_shape_complete(self):
  2841. self.app.log.debug("on_shape_complete()")
  2842. # Add shape
  2843. self.add_shape(self.active_tool.geometry)
  2844. # Remove any utility shapes
  2845. self.delete_utility_geometry()
  2846. self.tool_shape.clear(update=True)
  2847. # Replot and reset tool.
  2848. self.replot()
  2849. # self.active_tool = type(self.active_tool)(self)
  2850. @staticmethod
  2851. def make_storage():
  2852. ## Shape storage.
  2853. storage = FlatCAMRTreeStorage()
  2854. storage.get_points = DrawToolShape.get_pts
  2855. return storage
  2856. def select_tool(self, toolname):
  2857. """
  2858. Selects a drawing tool. Impacts the object and GUI.
  2859. :param toolname: Name of the tool.
  2860. :return: None
  2861. """
  2862. self.tools[toolname]["button"].setChecked(True)
  2863. self.on_tool_select(toolname)
  2864. def set_selected(self, shape):
  2865. # Remove and add to the end.
  2866. if shape in self.selected:
  2867. self.selected.remove(shape)
  2868. self.selected.append(shape)
  2869. def set_unselected(self, shape):
  2870. if shape in self.selected:
  2871. self.selected.remove(shape)
  2872. def snap(self, x, y):
  2873. """
  2874. Adjusts coordinates to snap settings.
  2875. :param x: Input coordinate X
  2876. :param y: Input coordinate Y
  2877. :return: Snapped (x, y)
  2878. """
  2879. snap_x, snap_y = (x, y)
  2880. snap_distance = Inf
  2881. ### Object (corner?) snap
  2882. ### No need for the objects, just the coordinates
  2883. ### in the index.
  2884. if self.options["corner_snap"]:
  2885. try:
  2886. nearest_pt, shape = self.storage.nearest((x, y))
  2887. nearest_pt_distance = distance((x, y), nearest_pt)
  2888. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  2889. snap_distance = nearest_pt_distance
  2890. snap_x, snap_y = nearest_pt
  2891. except (StopIteration, AssertionError):
  2892. pass
  2893. ### Grid snap
  2894. if self.options["grid_snap"]:
  2895. if self.options["global_gridx"] != 0:
  2896. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  2897. else:
  2898. snap_x_ = x
  2899. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  2900. # and it will use the snap distance from GridX entry
  2901. if self.app.ui.grid_gap_link_cb.isChecked():
  2902. if self.options["global_gridx"] != 0:
  2903. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  2904. else:
  2905. snap_y_ = y
  2906. else:
  2907. if self.options["global_gridy"] != 0:
  2908. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  2909. else:
  2910. snap_y_ = y
  2911. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  2912. if nearest_grid_distance < snap_distance:
  2913. snap_x, snap_y = (snap_x_, snap_y_)
  2914. return snap_x, snap_y
  2915. def update_fcgeometry(self, fcgeometry):
  2916. """
  2917. Transfers the geometry tool shape buffer to the selected geometry
  2918. object. The geometry already in the object are removed.
  2919. :param fcgeometry: FlatCAMGeometry
  2920. :return: None
  2921. """
  2922. if self.multigeo_tool:
  2923. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  2924. # for shape in self.shape_buffer:
  2925. for shape in self.storage.get_objects():
  2926. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  2927. self.multigeo_tool = None
  2928. else:
  2929. fcgeometry.solid_geometry = []
  2930. # for shape in self.shape_buffer:
  2931. for shape in self.storage.get_objects():
  2932. fcgeometry.solid_geometry.append(shape.geo)
  2933. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2934. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2935. for w in sel_tab_widget_list:
  2936. w.setEnabled(True)
  2937. def update_options(self, obj):
  2938. if self.paint_tooldia:
  2939. obj.options['cnctooldia'] = self.paint_tooldia
  2940. self.paint_tooldia = None
  2941. return True
  2942. else:
  2943. return False
  2944. def union(self):
  2945. """
  2946. Makes union of selected polygons. Original polygons
  2947. are deleted.
  2948. :return: None.
  2949. """
  2950. results = cascaded_union([t.geo for t in self.get_selected()])
  2951. # Delete originals.
  2952. for_deletion = [s for s in self.get_selected()]
  2953. for shape in for_deletion:
  2954. self.delete_shape(shape)
  2955. # Selected geometry is now gone!
  2956. self.selected = []
  2957. self.add_shape(DrawToolShape(results))
  2958. self.replot()
  2959. def intersection(self):
  2960. """
  2961. Makes intersectino of selected polygons. Original polygons are deleted.
  2962. :return: None
  2963. """
  2964. shapes = self.get_selected()
  2965. try:
  2966. results = shapes[0].geo
  2967. except Exception as e:
  2968. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  2969. self.app.inform.emit(_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  2970. self.select_tool('select')
  2971. return
  2972. for shape in shapes[1:]:
  2973. results = results.intersection(shape.geo)
  2974. # Delete originals.
  2975. for_deletion = [s for s in self.get_selected()]
  2976. for shape in for_deletion:
  2977. self.delete_shape(shape)
  2978. # Selected geometry is now gone!
  2979. self.selected = []
  2980. self.add_shape(DrawToolShape(results))
  2981. self.replot()
  2982. def subtract(self):
  2983. selected = self.get_selected()
  2984. try:
  2985. tools = selected[1:]
  2986. toolgeo = cascaded_union([shp.geo for shp in tools])
  2987. result = selected[0].geo.difference(toolgeo)
  2988. self.delete_shape(selected[0])
  2989. self.add_shape(DrawToolShape(result))
  2990. self.replot()
  2991. except Exception as e:
  2992. log.debug(str(e))
  2993. def buffer(self, buf_distance, join_style):
  2994. selected = self.get_selected()
  2995. if buf_distance < 0:
  2996. self.app.inform.emit(
  2997. _( "[ERROR_NOTCL] Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  2998. # deselect everything
  2999. self.selected = []
  3000. self.replot()
  3001. return
  3002. if len(selected) == 0:
  3003. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3004. return
  3005. if not isinstance(buf_distance, float):
  3006. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3007. # deselect everything
  3008. self.selected = []
  3009. self.replot()
  3010. return
  3011. pre_buffer = cascaded_union([t.geo for t in selected])
  3012. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3013. if results.is_empty:
  3014. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3015. # deselect everything
  3016. self.selected = []
  3017. self.replot()
  3018. return
  3019. self.add_shape(DrawToolShape(results))
  3020. self.replot()
  3021. self.app.inform.emit(_("[success] Full buffer geometry created."))
  3022. def buffer_int(self, buf_distance, join_style):
  3023. selected = self.get_selected()
  3024. if buf_distance < 0:
  3025. self.app.inform.emit(
  3026. _("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3027. "Use Buffer interior to generate an 'inside' shape")
  3028. )
  3029. # deselect everything
  3030. self.selected = []
  3031. self.replot()
  3032. return
  3033. if len(selected) == 0:
  3034. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3035. return
  3036. if not isinstance(buf_distance, float):
  3037. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3038. # deselect everything
  3039. self.selected = []
  3040. self.replot()
  3041. return
  3042. pre_buffer = cascaded_union([t.geo for t in selected])
  3043. results = pre_buffer.buffer(-buf_distance + 1e-10, resolution=32, join_style=join_style)
  3044. if results.is_empty:
  3045. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a smaller buffer value."))
  3046. # deselect everything
  3047. self.selected = []
  3048. self.replot()
  3049. return
  3050. if type(results) == MultiPolygon:
  3051. for poly in results:
  3052. self.add_shape(DrawToolShape(poly.exterior))
  3053. else:
  3054. self.add_shape(DrawToolShape(results.exterior))
  3055. self.replot()
  3056. self.app.inform.emit(_("[success] Interior buffer geometry created."))
  3057. # selected = self.get_selected()
  3058. #
  3059. # if len(selected) == 0:
  3060. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3061. # return
  3062. #
  3063. # if not isinstance(buf_distance, float):
  3064. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3065. # return
  3066. #
  3067. # pre_buffer = cascaded_union([t.geo for t in selected])
  3068. # results = pre_buffer.buffer(buf_distance)
  3069. # if results.is_empty:
  3070. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3071. # return
  3072. #
  3073. # int_geo = []
  3074. # if type(results) == MultiPolygon:
  3075. # for poly in results:
  3076. # for g in poly.interiors:
  3077. # int_geo.append(g)
  3078. # res = cascaded_union(int_geo)
  3079. # self.add_shape(DrawToolShape(res))
  3080. # else:
  3081. # print(results.interiors)
  3082. # for g in results.interiors:
  3083. # int_geo.append(g)
  3084. # res = cascaded_union(int_geo)
  3085. # self.add_shape(DrawToolShape(res))
  3086. #
  3087. # self.replot()
  3088. # self.app.inform.emit("Interior buffer geometry created.")
  3089. def buffer_ext(self, buf_distance, join_style):
  3090. selected = self.get_selected()
  3091. if buf_distance < 0:
  3092. self.app.inform.emit(_("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3093. "Use Buffer interior to generate an 'inside' shape"))
  3094. # deselect everything
  3095. self.selected = []
  3096. self.replot()
  3097. return
  3098. if len(selected) == 0:
  3099. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3100. return
  3101. if not isinstance(buf_distance, float):
  3102. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3103. # deselect everything
  3104. self.selected = []
  3105. self.replot()
  3106. return
  3107. pre_buffer = cascaded_union([t.geo for t in selected])
  3108. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3109. if results.is_empty:
  3110. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3111. # deselect everything
  3112. self.selected = []
  3113. self.replot()
  3114. return
  3115. if type(results) == MultiPolygon:
  3116. for poly in results:
  3117. self.add_shape(DrawToolShape(poly.exterior))
  3118. else:
  3119. self.add_shape(DrawToolShape(results.exterior))
  3120. self.replot()
  3121. self.app.inform.emit(_("[success] Exterior buffer geometry created."))
  3122. # def paint(self, tooldia, overlap, margin, method):
  3123. # selected = self.get_selected()
  3124. #
  3125. # if len(selected) == 0:
  3126. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3127. # return
  3128. #
  3129. # for param in [tooldia, overlap, margin]:
  3130. # if not isinstance(param, float):
  3131. # param_name = [k for k, v in locals().items() if v is param][0]
  3132. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3133. #
  3134. # # Todo: Check for valid method.
  3135. #
  3136. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3137. #
  3138. # results = []
  3139. #
  3140. # def recurse(geo):
  3141. # try:
  3142. # for subg in geo:
  3143. # for subsubg in recurse(subg):
  3144. # yield subsubg
  3145. # except TypeError:
  3146. # if isinstance(geo, LinearRing):
  3147. # yield geo
  3148. #
  3149. # raise StopIteration
  3150. #
  3151. # for geo in selected:
  3152. # print(type(geo.geo))
  3153. #
  3154. # local_results = []
  3155. # for poly in recurse(geo.geo):
  3156. # if method == "seed":
  3157. # # Type(cp) == FlatCAMRTreeStorage | None
  3158. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3159. # tooldia, overlap=overlap)
  3160. #
  3161. # else:
  3162. # # Type(cp) == FlatCAMRTreeStorage | None
  3163. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3164. # tooldia, overlap=overlap)
  3165. #
  3166. # if cp is not None:
  3167. # local_results += list(cp.get_objects())
  3168. #
  3169. # results.append(cascaded_union(local_results))
  3170. #
  3171. # # This is a dirty patch:
  3172. # for r in results:
  3173. # self.add_shape(DrawToolShape(r))
  3174. #
  3175. # self.replot()
  3176. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3177. self.paint_tooldia = tooldia
  3178. selected = self.get_selected()
  3179. if len(selected) == 0:
  3180. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for painting."))
  3181. return
  3182. for param in [tooldia, overlap, margin]:
  3183. if not isinstance(param, float):
  3184. param_name = [k for k, v in locals().items() if v is param][0]
  3185. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3186. results = []
  3187. if overlap >= 1:
  3188. self.app.inform.emit(
  3189. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3190. return
  3191. def recurse(geometry, reset=True):
  3192. """
  3193. Creates a list of non-iterable linear geometry objects.
  3194. Results are placed in self.flat_geometry
  3195. :param geometry: Shapely type or list or list of list of such.
  3196. :param reset: Clears the contents of self.flat_geometry.
  3197. """
  3198. if geometry is None:
  3199. return
  3200. if reset:
  3201. self.flat_geo = []
  3202. ## If iterable, expand recursively.
  3203. try:
  3204. for geo in geometry:
  3205. if geo is not None:
  3206. recurse(geometry=geo, reset=False)
  3207. ## Not iterable, do the actual indexing and add.
  3208. except TypeError:
  3209. self.flat_geo.append(geometry)
  3210. return self.flat_geo
  3211. for geo in selected:
  3212. local_results = []
  3213. for geo_obj in recurse(geo.geo):
  3214. try:
  3215. if type(geo_obj) == Polygon:
  3216. poly_buf = geo_obj.buffer(-margin)
  3217. else:
  3218. poly_buf = Polygon(geo_obj).buffer(-margin)
  3219. if method == "seed":
  3220. cp = Geometry.clear_polygon2(poly_buf,
  3221. tooldia, self.app.defaults["geometry_circle_steps"],
  3222. overlap=overlap, contour=contour, connect=connect)
  3223. elif method == "lines":
  3224. cp = Geometry.clear_polygon3(poly_buf,
  3225. tooldia, self.app.defaults["geometry_circle_steps"],
  3226. overlap=overlap, contour=contour, connect=connect)
  3227. else:
  3228. cp = Geometry.clear_polygon(poly_buf,
  3229. tooldia, self.app.defaults["geometry_circle_steps"],
  3230. overlap=overlap, contour=contour, connect=connect)
  3231. if cp is not None:
  3232. local_results += list(cp.get_objects())
  3233. except Exception as e:
  3234. log.debug("Could not Paint the polygons. %s" % str(e))
  3235. self.app.inform.emit(
  3236. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3237. "Or a different method of Paint\n%s") % str(e))
  3238. return
  3239. # add the result to the results list
  3240. results.append(cascaded_union(local_results))
  3241. # This is a dirty patch:
  3242. for r in results:
  3243. self.add_shape(DrawToolShape(r))
  3244. self.app.inform.emit(
  3245. _("[success] Paint done."))
  3246. self.replot()
  3247. def distance(pt1, pt2):
  3248. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3249. def mag(vec):
  3250. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3251. def poly2rings(poly):
  3252. return [poly.exterior] + [interior for interior in poly.interiors]