FlatCAMGeoEditor.py 182 KB

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