FlatCAMGeoEditor.py 159 KB

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