FlatCAMGeoEditor.py 166 KB

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