FlatCAMGeoEditor.py 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086
  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, FCTree
  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, linemerge
  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'))
  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] FlatCAMGeoEditor.FCSelect.click_release() -> Something went bad. %s" % str(e))
  2044. # if selection is done on canvas update the Tree in Selected Tab with the selection
  2045. try:
  2046. self.draw_app.tw.itemSelectionChanged.disconnect(self.draw_app.on_tree_selection_change)
  2047. except (AttributeError, TypeError):
  2048. pass
  2049. self.draw_app.tw.selectionModel().clearSelection()
  2050. for sel_shape in self.draw_app.selected:
  2051. iterator = QtWidgets.QTreeWidgetItemIterator(self.draw_app.tw)
  2052. while iterator.value():
  2053. item = iterator.value()
  2054. try:
  2055. if int(item.text(1)) == id(sel_shape):
  2056. item.setSelected(True)
  2057. except ValueError:
  2058. pass
  2059. iterator += 1
  2060. self.draw_app.tw.itemSelectionChanged.connect(self.draw_app.on_tree_selection_change)
  2061. return ""
  2062. def clean_up(self):
  2063. pass
  2064. class FCExplode(FCShapeTool):
  2065. def __init__(self, draw_app):
  2066. FCShapeTool.__init__(self, draw_app)
  2067. self.name = 'explode'
  2068. self.draw_app = draw_app
  2069. try:
  2070. QtGui.QGuiApplication.restoreOverrideCursor()
  2071. except Exception:
  2072. pass
  2073. self.storage = self.draw_app.storage
  2074. self.origin = (0, 0)
  2075. self.destination = None
  2076. self.draw_app.active_tool = self
  2077. if len(self.draw_app.get_selected()) == 0:
  2078. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' % ("No shape selected. Select a shape to explode"))
  2079. else:
  2080. self.make()
  2081. def make(self):
  2082. to_be_deleted_list = list()
  2083. lines = list()
  2084. for shape in self.draw_app.get_selected():
  2085. to_be_deleted_list.append(shape)
  2086. geo = shape.geo
  2087. ext_coords = list(geo.exterior.coords)
  2088. for c in range(len(ext_coords)):
  2089. if c < len(ext_coords) - 1:
  2090. lines.append(LineString([ext_coords[c], ext_coords[c + 1]]))
  2091. for int_geo in geo.interiors:
  2092. int_coords = list(int_geo.coords)
  2093. for c in range(len(int_coords)):
  2094. if c < len(int_coords):
  2095. lines.append(LineString([int_coords[c], int_coords[c + 1]]))
  2096. for shape in to_be_deleted_list:
  2097. self.draw_app.storage.remove(shape)
  2098. if shape in self.draw_app.selected:
  2099. self.draw_app.selected.remove(shape)
  2100. geo_list = list()
  2101. for line in lines:
  2102. geo_list.append(DrawToolShape(line))
  2103. self.geometry = geo_list
  2104. self.draw_app.on_shape_complete()
  2105. self.draw_app.app.inform.emit('[success] %s...' % _("Done. Polygons exploded into lines."))
  2106. def clean_up(self):
  2107. self.draw_app.selected = list()
  2108. self.draw_app.plot_all()
  2109. try:
  2110. self.draw_app.app.jump_signal.disconnect()
  2111. except (TypeError, AttributeError):
  2112. pass
  2113. class FCMove(FCShapeTool):
  2114. def __init__(self, draw_app):
  2115. FCShapeTool.__init__(self, draw_app)
  2116. self.name = 'move'
  2117. self.draw_app = draw_app
  2118. try:
  2119. QtGui.QGuiApplication.restoreOverrideCursor()
  2120. except Exception as e:
  2121. pass
  2122. self.storage = self.draw_app.storage
  2123. self.origin = None
  2124. self.destination = None
  2125. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2126. self.selection_shape = self.selection_bbox()
  2127. if len(self.draw_app.get_selected()) == 0:
  2128. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' %
  2129. _("MOVE: No shape selected. Select a shape to move"))
  2130. return
  2131. else:
  2132. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2133. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2134. def set_origin(self, origin):
  2135. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2136. self.origin = origin
  2137. def click(self, point):
  2138. if len(self.draw_app.get_selected()) == 0:
  2139. # self.complete = True
  2140. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2141. self.select_shapes(point)
  2142. self.draw_app.replot()
  2143. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2144. return
  2145. if self.origin is None:
  2146. self.set_origin(point)
  2147. self.selection_shape = self.selection_bbox()
  2148. return "Click on final location."
  2149. else:
  2150. self.destination = point
  2151. self.make()
  2152. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2153. # 'params': []}))
  2154. return "Done."
  2155. def make(self):
  2156. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2157. # Create new geometry
  2158. dx = self.destination[0] - self.origin[0]
  2159. dy = self.destination[1] - self.origin[1]
  2160. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2161. for geom in self.draw_app.get_selected()]
  2162. # Delete old
  2163. self.draw_app.delete_selected()
  2164. self.complete = True
  2165. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Move completed."))
  2166. self.draw_app.app.jump_signal.disconnect()
  2167. def selection_bbox(self):
  2168. geo_list = []
  2169. for select_shape in self.draw_app.get_selected():
  2170. geometric_data = select_shape.geo
  2171. try:
  2172. for g in geometric_data:
  2173. geo_list.append(g)
  2174. except TypeError:
  2175. geo_list.append(geometric_data)
  2176. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2177. pt1 = (xmin, ymin)
  2178. pt2 = (xmax, ymin)
  2179. pt3 = (xmax, ymax)
  2180. pt4 = (xmin, ymax)
  2181. return Polygon([pt1, pt2, pt3, pt4])
  2182. def utility_geometry(self, data=None):
  2183. """
  2184. Temporary geometry on screen while using this tool.
  2185. :param data:
  2186. :return:
  2187. """
  2188. geo_list = []
  2189. if self.origin is None:
  2190. return None
  2191. if len(self.draw_app.get_selected()) == 0:
  2192. return None
  2193. dx = data[0] - self.origin[0]
  2194. dy = data[1] - self.origin[1]
  2195. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2196. try:
  2197. for geom in self.draw_app.get_selected():
  2198. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2199. except AttributeError:
  2200. self.draw_app.select_tool('select')
  2201. self.draw_app.selected = []
  2202. return
  2203. return DrawToolUtilityShape(geo_list)
  2204. else:
  2205. try:
  2206. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2207. except ValueError:
  2208. ss_el = None
  2209. return DrawToolUtilityShape(ss_el)
  2210. def select_shapes(self, pos):
  2211. # list where we store the overlapped shapes under our mouse left click position
  2212. over_shape_list = []
  2213. try:
  2214. _, closest_shape = self.storage.nearest(pos)
  2215. except StopIteration:
  2216. return ""
  2217. over_shape_list.append(closest_shape)
  2218. try:
  2219. # if there is no shape under our click then deselect all shapes
  2220. # it will not work for 3rd method of click selection
  2221. if not over_shape_list:
  2222. self.draw_app.selected = []
  2223. self.draw_app.draw_shape_idx = -1
  2224. else:
  2225. # if there are shapes under our click then advance through the list of them, one at the time in a
  2226. # circular way
  2227. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2228. try:
  2229. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2230. except IndexError:
  2231. return
  2232. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2233. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2234. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2235. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2236. if key_modifier == Qt.ControlModifier:
  2237. if obj_to_add in self.draw_app.selected:
  2238. self.draw_app.selected.remove(obj_to_add)
  2239. else:
  2240. self.draw_app.selected.append(obj_to_add)
  2241. else:
  2242. self.draw_app.selected = []
  2243. self.draw_app.selected.append(obj_to_add)
  2244. else:
  2245. if key_modifier == Qt.ShiftModifier:
  2246. if obj_to_add in self.draw_app.selected:
  2247. self.draw_app.selected.remove(obj_to_add)
  2248. else:
  2249. self.draw_app.selected.append(obj_to_add)
  2250. else:
  2251. self.draw_app.selected = []
  2252. self.draw_app.selected.append(obj_to_add)
  2253. except Exception as e:
  2254. log.error("[ERROR] Something went bad. %s" % str(e))
  2255. raise
  2256. def clean_up(self):
  2257. self.draw_app.selected = list()
  2258. self.draw_app.plot_all()
  2259. try:
  2260. self.draw_app.app.jump_signal.disconnect()
  2261. except (TypeError, AttributeError):
  2262. pass
  2263. class FCCopy(FCMove):
  2264. def __init__(self, draw_app):
  2265. FCMove.__init__(self, draw_app)
  2266. self.name = 'copy'
  2267. def make(self):
  2268. # Create new geometry
  2269. dx = self.destination[0] - self.origin[0]
  2270. dy = self.destination[1] - self.origin[1]
  2271. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2272. for geom in self.draw_app.get_selected()]
  2273. self.complete = True
  2274. self.draw_app.app.inform.emit('[success] %s' % _("Done. Geometry(s) Copy completed."))
  2275. self.draw_app.app.jump_signal.disconnect()
  2276. def clean_up(self):
  2277. self.draw_app.selected = list()
  2278. self.draw_app.plot_all()
  2279. try:
  2280. self.draw_app.app.jump_signal.disconnect()
  2281. except (TypeError, AttributeError):
  2282. pass
  2283. class FCText(FCShapeTool):
  2284. def __init__(self, draw_app):
  2285. FCShapeTool.__init__(self, draw_app)
  2286. self.name = 'text'
  2287. self.draw_app = draw_app
  2288. try:
  2289. QtGui.QGuiApplication.restoreOverrideCursor()
  2290. except Exception:
  2291. pass
  2292. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_text.png'))
  2293. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2294. self.app = draw_app.app
  2295. self.draw_app.app.inform.emit(_("Click on 1st point ..."))
  2296. self.origin = (0, 0)
  2297. self.text_gui = TextInputTool(self.app)
  2298. self.text_gui.run()
  2299. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2300. def click(self, point):
  2301. # Create new geometry
  2302. dx = point[0]
  2303. dy = point[1]
  2304. if self.text_gui.text_path:
  2305. try:
  2306. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2307. except Exception as e:
  2308. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2309. self.draw_app.app.inform.emit('[ERROR] %s: %s' %
  2310. (_("Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2311. "supported. Error"), str(e)))
  2312. self.text_gui.text_path = []
  2313. self.text_gui.hide_tool()
  2314. self.draw_app.select_tool('select')
  2315. self.draw_app.app.jump_signal.disconnect()
  2316. return
  2317. else:
  2318. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' % _("No text to add."))
  2319. self.draw_app.app.jump_signal.disconnect()
  2320. return
  2321. self.text_gui.text_path = []
  2322. self.text_gui.hide_tool()
  2323. self.complete = True
  2324. self.draw_app.app.inform.emit('[success]%s' % _(" Done. Adding Text completed."))
  2325. def utility_geometry(self, data=None):
  2326. """
  2327. Temporary geometry on screen while using this tool.
  2328. :param data: mouse position coords
  2329. :return:
  2330. """
  2331. dx = data[0] - self.origin[0]
  2332. dy = data[1] - self.origin[1]
  2333. try:
  2334. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2335. except Exception:
  2336. return
  2337. def clean_up(self):
  2338. self.draw_app.selected = list()
  2339. self.draw_app.plot_all()
  2340. try:
  2341. self.draw_app.app.jump_signal.disconnect()
  2342. except (TypeError, AttributeError):
  2343. pass
  2344. class FCBuffer(FCShapeTool):
  2345. def __init__(self, draw_app):
  2346. FCShapeTool.__init__(self, draw_app)
  2347. self.name = 'buffer'
  2348. # self.shape_buffer = self.draw_app.shape_buffer
  2349. self.draw_app = draw_app
  2350. self.app = draw_app.app
  2351. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2352. self.origin = (0, 0)
  2353. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2354. self.buff_tool.run()
  2355. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2356. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2357. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2358. self.activate()
  2359. def on_buffer(self):
  2360. if not self.draw_app.selected:
  2361. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Buffer cancelled. No shape selected."))
  2362. return
  2363. try:
  2364. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2365. except ValueError:
  2366. # try to convert comma to decimal point. if it's still not working error message and return
  2367. try:
  2368. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2369. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2370. except ValueError:
  2371. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2372. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2373. return
  2374. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2375. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2376. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2377. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2378. self.app.ui.notebook.setTabText(2, _("Tools"))
  2379. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2380. self.disactivate()
  2381. if ret_val == 'fail':
  2382. return
  2383. self.draw_app.app.inform.emit('[success] %s' %
  2384. _("Done. Buffer Tool completed."))
  2385. def on_buffer_int(self):
  2386. if not self.draw_app.selected:
  2387. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2388. _("Buffer cancelled. No shape selected."))
  2389. return
  2390. try:
  2391. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2392. except ValueError:
  2393. # try to convert comma to decimal point. if it's still not working error message and return
  2394. try:
  2395. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2396. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2397. except ValueError:
  2398. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2399. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2400. return
  2401. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2402. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2403. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2404. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2405. self.app.ui.notebook.setTabText(2, _("Tools"))
  2406. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2407. self.disactivate()
  2408. if ret_val == 'fail':
  2409. return
  2410. self.draw_app.app.inform.emit('[success] %s' %
  2411. _("Done. Buffer Int Tool completed."))
  2412. def on_buffer_ext(self):
  2413. if not self.draw_app.selected:
  2414. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2415. _("Buffer cancelled. No shape selected."))
  2416. return
  2417. try:
  2418. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2419. except ValueError:
  2420. # try to convert comma to decimal point. if it's still not working error message and return
  2421. try:
  2422. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2423. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2424. except ValueError:
  2425. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2426. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2427. return
  2428. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2429. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2430. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2431. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2432. self.app.ui.notebook.setTabText(2, _("Tools"))
  2433. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2434. self.disactivate()
  2435. if ret_val == 'fail':
  2436. return
  2437. self.draw_app.app.inform.emit('[success] %s' %
  2438. _("Done. Buffer Ext Tool completed."))
  2439. def activate(self):
  2440. self.buff_tool.buffer_button.clicked.disconnect()
  2441. self.buff_tool.buffer_int_button.clicked.disconnect()
  2442. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2443. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2444. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2445. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2446. def disactivate(self):
  2447. self.buff_tool.buffer_button.clicked.disconnect()
  2448. self.buff_tool.buffer_int_button.clicked.disconnect()
  2449. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2450. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2451. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2452. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2453. self.complete = True
  2454. self.draw_app.select_tool("select")
  2455. self.buff_tool.hide_tool()
  2456. def clean_up(self):
  2457. self.draw_app.selected = list()
  2458. self.draw_app.plot_all()
  2459. try:
  2460. self.draw_app.app.jump_signal.disconnect()
  2461. except (TypeError, AttributeError):
  2462. pass
  2463. class FCEraser(FCShapeTool):
  2464. def __init__(self, draw_app):
  2465. DrawTool.__init__(self, draw_app)
  2466. self.name = 'eraser'
  2467. self.draw_app = draw_app
  2468. self.origin = None
  2469. self.destination = None
  2470. if len(self.draw_app.get_selected()) == 0:
  2471. if self.draw_app.launched_from_shortcuts is True:
  2472. self.draw_app.launched_from_shortcuts = False
  2473. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2474. else:
  2475. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2476. self.geometry = []
  2477. self.storage = self.draw_app.storage
  2478. # Switch notebook to Selected page
  2479. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2480. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  2481. def set_origin(self, origin):
  2482. self.origin = origin
  2483. def click(self, point):
  2484. if len(self.draw_app.get_selected()) == 0:
  2485. for obj_shape in self.storage.get_objects():
  2486. try:
  2487. __, closest_shape = self.storage.nearest(point)
  2488. self.draw_app.selected.append(closest_shape)
  2489. except StopIteration:
  2490. if len(self.draw_app.selected) > 0:
  2491. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2492. return ""
  2493. if len(self.draw_app.get_selected()) == 0:
  2494. return "Nothing to ersase."
  2495. else:
  2496. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2497. if self.origin is None:
  2498. self.set_origin(point)
  2499. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2500. return
  2501. else:
  2502. self.destination = point
  2503. self.make()
  2504. # self.draw_app.select_tool("select")
  2505. return
  2506. def make(self):
  2507. eraser_sel_shapes = []
  2508. # create the eraser shape from selection
  2509. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2510. temp_shape = eraser_shape.buffer(0.0000001)
  2511. temp_shape = Polygon(temp_shape.exterior)
  2512. eraser_sel_shapes.append(temp_shape)
  2513. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2514. for obj_shape in self.storage.get_objects():
  2515. try:
  2516. geometric_data = obj_shape.geo
  2517. if eraser_sel_shapes.intersects(geometric_data):
  2518. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2519. except KeyError:
  2520. pass
  2521. self.draw_app.delete_utility_geometry()
  2522. self.draw_app.plot_all()
  2523. self.draw_app.app.inform.emit('[success] %s' % _("Done. Eraser tool action completed."))
  2524. self.draw_app.app.jump_signal.disconnect()
  2525. def utility_geometry(self, data=None):
  2526. """
  2527. Temporary geometry on screen while using this tool.
  2528. :param data:
  2529. :return:
  2530. """
  2531. geo_list = []
  2532. if self.origin is None:
  2533. return None
  2534. if len(self.draw_app.get_selected()) == 0:
  2535. return None
  2536. dx = data[0] - self.origin[0]
  2537. dy = data[1] - self.origin[1]
  2538. try:
  2539. for geom in self.draw_app.get_selected():
  2540. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2541. except AttributeError:
  2542. self.draw_app.select_tool('select')
  2543. self.draw_app.selected = []
  2544. return
  2545. return DrawToolUtilityShape(geo_list)
  2546. def clean_up(self):
  2547. self.draw_app.selected = list()
  2548. self.draw_app.plot_all()
  2549. try:
  2550. self.draw_app.app.jump_signal.disconnect()
  2551. except (TypeError, AttributeError):
  2552. pass
  2553. class FCPaint(FCShapeTool):
  2554. def __init__(self, draw_app):
  2555. FCShapeTool.__init__(self, draw_app)
  2556. self.name = 'paint'
  2557. self.draw_app = draw_app
  2558. self.app = draw_app.app
  2559. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2560. self.origin = (0, 0)
  2561. self.draw_app.paint_tool.run()
  2562. class FCTransform(FCShapeTool):
  2563. def __init__(self, draw_app):
  2564. FCShapeTool.__init__(self, draw_app)
  2565. self.name = 'transformation'
  2566. self.draw_app = draw_app
  2567. self.app = draw_app.app
  2568. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2569. self.origin = (0, 0)
  2570. self.draw_app.transform_tool.run()
  2571. # ###############################################
  2572. # ################ Main Application #############
  2573. # ###############################################
  2574. class FlatCAMGeoEditor(QtCore.QObject):
  2575. # will emit the name of the object that was just selected
  2576. item_selected = QtCore.pyqtSignal(str)
  2577. transform_complete = QtCore.pyqtSignal()
  2578. draw_shape_idx = -1
  2579. def __init__(self, app, disabled=False):
  2580. assert isinstance(app, FlatCAMApp.App), \
  2581. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2582. super(FlatCAMGeoEditor, self).__init__()
  2583. self.app = app
  2584. self.canvas = app.plotcanvas
  2585. self.decimals = app.decimals
  2586. self.geo_edit_widget = QtWidgets.QWidget()
  2587. # ## Box for custom widgets
  2588. # This gets populated in offspring implementations.
  2589. layout = QtWidgets.QVBoxLayout()
  2590. self.geo_edit_widget.setLayout(layout)
  2591. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  2592. # this way I can hide/show the frame
  2593. self.geo_frame = QtWidgets.QFrame()
  2594. self.geo_frame.setContentsMargins(0, 0, 0, 0)
  2595. layout.addWidget(self.geo_frame)
  2596. self.tools_box = QtWidgets.QVBoxLayout()
  2597. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2598. self.geo_frame.setLayout(self.tools_box)
  2599. # ## Page Title box (spacing between children)
  2600. self.title_box = QtWidgets.QHBoxLayout()
  2601. self.tools_box.addLayout(self.title_box)
  2602. # ## Page Title icon
  2603. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  2604. self.icon = QtWidgets.QLabel()
  2605. self.icon.setPixmap(pixmap)
  2606. self.title_box.addWidget(self.icon, stretch=0)
  2607. # ## Title label
  2608. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Geometry Editor'))
  2609. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  2610. self.title_box.addWidget(self.title_label, stretch=1)
  2611. self.title_box.addWidget(QtWidgets.QLabel(''))
  2612. self.tw = FCTree(extended_sel=True)
  2613. self.tools_box.addWidget(self.tw)
  2614. self.geo_font = QtGui.QFont()
  2615. self.geo_font.setBold(True)
  2616. parent = self.tw.invisibleRootItem()
  2617. self.geo_parent = self.tw.addParent(
  2618. parent, _('Geometry Elements'), expanded=True, color=QtGui.QColor("#000000"), font=self.geo_font)
  2619. # ## Toolbar events and properties
  2620. self.tools = {
  2621. "select": {"button": self.app.ui.geo_select_btn,
  2622. "constructor": FCSelect},
  2623. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2624. "constructor": FCArc},
  2625. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2626. "constructor": FCCircle},
  2627. "path": {"button": self.app.ui.geo_add_path_btn,
  2628. "constructor": FCPath},
  2629. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2630. "constructor": FCRectangle},
  2631. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2632. "constructor": FCPolygon},
  2633. "text": {"button": self.app.ui.geo_add_text_btn,
  2634. "constructor": FCText},
  2635. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2636. "constructor": FCBuffer},
  2637. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2638. "constructor": FCPaint},
  2639. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2640. "constructor": FCEraser},
  2641. "move": {"button": self.app.ui.geo_move_btn,
  2642. "constructor": FCMove},
  2643. "transform": {"button": self.app.ui.geo_transform_btn,
  2644. "constructor": FCTransform},
  2645. "copy": {"button": self.app.ui.geo_copy_btn,
  2646. "constructor": FCCopy},
  2647. "explode": {"button": self.app.ui.geo_explode_btn,
  2648. "constructor": FCExplode}
  2649. }
  2650. # # ## Data
  2651. self.active_tool = None
  2652. self.storage = FlatCAMGeoEditor.make_storage()
  2653. self.utility = []
  2654. # VisPy visuals
  2655. self.fcgeometry = None
  2656. if self.app.is_legacy is False:
  2657. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2658. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2659. else:
  2660. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2661. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='shapes_geo_editor')
  2662. self.tool_shape = ShapeCollectionLegacy(obj=self, app=self.app, name='tool_shapes_geo_editor')
  2663. self.app.pool_recreated.connect(self.pool_recreated)
  2664. # Remove from scene
  2665. self.shapes.enabled = False
  2666. self.tool_shape.enabled = False
  2667. # List of selected shapes.
  2668. self.selected = []
  2669. self.flat_geo = []
  2670. self.move_timer = QtCore.QTimer()
  2671. self.move_timer.setSingleShot(True)
  2672. # this var will store the state of the toolbar before starting the editor
  2673. self.toolbar_old_state = False
  2674. self.key = None # Currently pressed key
  2675. self.geo_key_modifiers = None
  2676. self.x = None # Current mouse cursor pos
  2677. self.y = None
  2678. # if we edit a multigeo geometry store here the tool number
  2679. self.multigeo_tool = None
  2680. # Current snapped mouse pos
  2681. self.snap_x = None
  2682. self.snap_y = None
  2683. self.pos = None
  2684. # signal that there is an action active like polygon or path
  2685. self.in_action = False
  2686. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2687. self.launched_from_shortcuts = False
  2688. def make_callback(thetool):
  2689. def f():
  2690. self.on_tool_select(thetool)
  2691. return f
  2692. for tool in self.tools:
  2693. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2694. self.tools[tool]["button"].setCheckable(True) # Checkable
  2695. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2696. self.app.ui.corner_snap_btn.setCheckable(True)
  2697. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2698. self.options = {
  2699. "global_gridx": 0.1,
  2700. "global_gridy": 0.1,
  2701. "global_snap_max": 0.05,
  2702. "grid_snap": True,
  2703. "corner_snap": False,
  2704. "grid_gap_link": True
  2705. }
  2706. self.options.update(self.app.options)
  2707. for option in self.options:
  2708. if option in self.app.options:
  2709. self.options[option] = self.app.options[option]
  2710. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2711. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2712. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2713. self.app.ui.grid_gap_link_cb.setChecked(True)
  2714. self.rtree_index = rtindex.Index()
  2715. def entry2option(option, entry):
  2716. try:
  2717. self.options[option] = float(entry.text())
  2718. except Exception as e:
  2719. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2720. return
  2721. def gridx_changed(goption, gentry):
  2722. entry2option(option=goption, entry=gentry)
  2723. # if the grid link is checked copy the value in the GridX field to GridY
  2724. try:
  2725. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2726. except ValueError:
  2727. return
  2728. units = self.app.defaults['units'].upper()
  2729. if self.app.ui.grid_gap_link_cb.isChecked():
  2730. self.app.ui.grid_gap_y_entry.set_value(val, decimals=self.decimals)
  2731. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2732. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2733. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2734. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2735. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2736. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2737. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2738. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2739. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2740. # if using Paint store here the tool diameter used
  2741. self.paint_tooldia = None
  2742. self.paint_tool = PaintOptionsTool(self.app, self)
  2743. self.transform_tool = TransformEditorTool(self.app, self)
  2744. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2745. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2746. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2747. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2748. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2749. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2750. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2751. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2752. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2753. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2754. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2755. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2756. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2757. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2758. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2759. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2760. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2761. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2762. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2763. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2764. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2765. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2766. self.transform_complete.connect(self.on_transform_complete)
  2767. # Event signals disconnect id holders
  2768. self.mp = None
  2769. self.mm = None
  2770. self.mr = None
  2771. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2772. self.editor_active = False
  2773. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2774. def pool_recreated(self, pool):
  2775. self.shapes.pool = pool
  2776. self.tool_shape.pool = pool
  2777. def on_transform_complete(self):
  2778. self.delete_selected()
  2779. self.replot()
  2780. def set_ui(self):
  2781. # updated units
  2782. self.units = self.app.defaults['units'].upper()
  2783. self.decimals = self.app.decimals
  2784. # Remove anything else in the GUI Selected Tab
  2785. self.app.ui.selected_scroll_area.takeWidget()
  2786. # Put ourselves in the GUI Selected Tab
  2787. self.app.ui.selected_scroll_area.setWidget(self.geo_edit_widget)
  2788. # Switch notebook to Selected page
  2789. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2790. def build_ui(self, first_run=None):
  2791. # try:
  2792. # # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2793. # self.apertures_table.itemChanged.disconnect()
  2794. # except (TypeError, AttributeError):
  2795. # pass
  2796. iterator = QtWidgets.QTreeWidgetItemIterator(self.geo_parent)
  2797. to_delete = list()
  2798. while iterator.value():
  2799. item = iterator.value()
  2800. to_delete.append(item)
  2801. iterator += 1
  2802. for it in to_delete:
  2803. self.geo_parent.removeChild(it)
  2804. for elem in self.storage.get_objects():
  2805. geo_type = type(elem.geo)
  2806. title = None
  2807. if geo_type is LinearRing:
  2808. title = _('ID Ring')
  2809. elif geo_type is LineString:
  2810. title = _('ID Line')
  2811. elif geo_type is Polygon:
  2812. title = _('ID Polygon')
  2813. elif geo_type is MultiLineString:
  2814. title = _('ID Multi-Line')
  2815. elif geo_type is MultiPolygon:
  2816. title = _('ID Multi-Polygon')
  2817. self.tw.addChild(
  2818. self.geo_parent,
  2819. [
  2820. '%s:' % title,
  2821. str(id(elem))
  2822. ],
  2823. True,
  2824. font=self.geo_font,
  2825. font_items=1
  2826. )
  2827. def on_geo_elem_selected(self):
  2828. pass
  2829. def on_tree_selection_change(self):
  2830. self.selected = list()
  2831. selected_tree_items = self.tw.selectedItems()
  2832. for sel in selected_tree_items:
  2833. for obj_shape in self.storage.get_objects():
  2834. try:
  2835. if id(obj_shape) == int(sel.text(1)):
  2836. self.selected.append(obj_shape)
  2837. except ValueError:
  2838. pass
  2839. self.replot()
  2840. def activate(self):
  2841. # adjust the status of the menu entries related to the editor
  2842. self.app.ui.menueditedit.setDisabled(True)
  2843. self.app.ui.menueditok.setDisabled(False)
  2844. # adjust the visibility of some of the canvas context menu
  2845. self.app.ui.popmenu_edit.setVisible(False)
  2846. self.app.ui.popmenu_save.setVisible(True)
  2847. self.connect_canvas_event_handlers()
  2848. # initialize working objects
  2849. self.storage = FlatCAMGeoEditor.make_storage()
  2850. self.utility = []
  2851. self.selected = []
  2852. self.shapes.enabled = True
  2853. self.tool_shape.enabled = True
  2854. self.app.app_cursor.enabled = True
  2855. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2856. self.app.ui.corner_snap_btn.setEnabled(True)
  2857. self.app.ui.snap_magnet.setVisible(True)
  2858. self.app.ui.corner_snap_btn.setVisible(True)
  2859. self.app.ui.geo_editor_menu.setDisabled(False)
  2860. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2861. self.app.ui.update_obj_btn.setEnabled(True)
  2862. self.app.ui.g_editor_cmenu.setEnabled(True)
  2863. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2864. self.app.ui.geo_edit_toolbar.setVisible(True)
  2865. self.app.ui.snap_toolbar.setDisabled(False)
  2866. self.app.ui.popmenu_disable.setVisible(False)
  2867. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2868. self.app.ui.popmenu_properties.setVisible(False)
  2869. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2870. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2871. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2872. # for w in sel_tab_widget_list:
  2873. # w.setEnabled(False)
  2874. # Tell the App that the editor is active
  2875. self.editor_active = True
  2876. self.item_selected.connect(self.on_geo_elem_selected)
  2877. # ## GUI Events
  2878. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  2879. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2880. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2881. self.geo_frame.show()
  2882. log.debug("Finished activating the Geometry Editor...")
  2883. def deactivate(self):
  2884. try:
  2885. QtGui.QGuiApplication.restoreOverrideCursor()
  2886. except Exception:
  2887. pass
  2888. # adjust the status of the menu entries related to the editor
  2889. self.app.ui.menueditedit.setDisabled(False)
  2890. self.app.ui.menueditok.setDisabled(True)
  2891. # adjust the visibility of some of the canvas context menu
  2892. self.app.ui.popmenu_edit.setVisible(True)
  2893. self.app.ui.popmenu_save.setVisible(False)
  2894. self.disconnect_canvas_event_handlers()
  2895. self.clear()
  2896. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2897. settings = QSettings("Open Source", "FlatCAM")
  2898. if settings.contains("layout"):
  2899. layout = settings.value('layout', type=str)
  2900. if layout == 'standard':
  2901. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2902. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2903. self.app.ui.corner_snap_btn.setEnabled(False)
  2904. self.app.ui.snap_magnet.setVisible(False)
  2905. self.app.ui.corner_snap_btn.setVisible(False)
  2906. elif layout == 'compact':
  2907. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2908. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2909. self.app.ui.corner_snap_btn.setEnabled(False)
  2910. else:
  2911. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2912. self.app.ui.snap_magnet.setVisible(False)
  2913. self.app.ui.corner_snap_btn.setVisible(False)
  2914. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2915. self.app.ui.corner_snap_btn.setEnabled(False)
  2916. # set the Editor Toolbar visibility to what was before entering in the Editor
  2917. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2918. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2919. # Disable visuals
  2920. self.shapes.enabled = False
  2921. self.tool_shape.enabled = False
  2922. self.app.ui.geo_editor_menu.setDisabled(True)
  2923. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2924. self.app.ui.update_obj_btn.setEnabled(False)
  2925. self.app.ui.g_editor_cmenu.setEnabled(False)
  2926. self.app.ui.e_editor_cmenu.setEnabled(False)
  2927. # Tell the app that the editor is no longer active
  2928. self.editor_active = False
  2929. self.app.ui.popmenu_disable.setVisible(True)
  2930. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2931. self.app.ui.popmenu_properties.setVisible(True)
  2932. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2933. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2934. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2935. try:
  2936. self.item_selected.disconnect()
  2937. except (AttributeError, TypeError):
  2938. pass
  2939. try:
  2940. # ## GUI Events
  2941. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  2942. # self.tw.keyPressed.connect(self.app.ui.keyPressEvent)
  2943. # self.tw.customContextMenuRequested.connect(self.on_menu_request)
  2944. except (AttributeError, TypeError):
  2945. pass
  2946. # try:
  2947. # # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2948. # sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2949. # for w in sel_tab_widget_list:
  2950. # w.setEnabled(True)
  2951. # except Exception as e:
  2952. # log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2953. # Show original geometry
  2954. if self.fcgeometry:
  2955. self.fcgeometry.visible = True
  2956. # hide the UI
  2957. self.geo_frame.hide()
  2958. log.debug("Finished deactivating the Geometry Editor...")
  2959. def connect_canvas_event_handlers(self):
  2960. # Canvas events
  2961. # first connect to new, then disconnect the old handlers
  2962. # don't ask why but if there is nothing connected I've seen issues
  2963. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  2964. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  2965. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_geo_click_release)
  2966. if self.app.is_legacy is False:
  2967. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2968. # but those from FlatCAMGeoEditor
  2969. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2970. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2971. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2972. self.app.plotcanvas.graph_event_disconnect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  2973. else:
  2974. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  2975. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  2976. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  2977. self.app.plotcanvas.graph_event_disconnect(self.app.mdc)
  2978. # self.app.collection.view.clicked.disconnect()
  2979. self.app.ui.popmenu_copy.triggered.disconnect()
  2980. self.app.ui.popmenu_delete.triggered.disconnect()
  2981. self.app.ui.popmenu_move.triggered.disconnect()
  2982. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  2983. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2984. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  2985. # Geometry Editor
  2986. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  2987. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  2988. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  2989. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  2990. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  2991. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  2992. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  2993. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  2994. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  2995. self.app.ui.draw_union.triggered.connect(self.union)
  2996. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  2997. self.app.ui.draw_substract.triggered.connect(self.subtract)
  2998. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  2999. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  3000. self.app.ui.draw_move.triggered.connect(self.on_move)
  3001. def disconnect_canvas_event_handlers(self):
  3002. # we restore the key and mouse control to FlatCAMApp method
  3003. # first connect to new, then disconnect the old handlers
  3004. # don't ask why but if there is nothing connected I've seen issues
  3005. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  3006. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  3007. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  3008. self.app.on_mouse_click_release_over_plot)
  3009. self.app.mdc = self.app.plotcanvas.graph_event_connect('mouse_double_click',
  3010. self.app.on_mouse_double_click_over_plot)
  3011. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  3012. if self.app.is_legacy is False:
  3013. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  3014. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  3015. self.canvas.graph_event_disconnect('mouse_release', self.on_geo_click_release)
  3016. else:
  3017. self.canvas.graph_event_disconnect(self.mp)
  3018. self.canvas.graph_event_disconnect(self.mm)
  3019. self.canvas.graph_event_disconnect(self.mr)
  3020. try:
  3021. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  3022. except (TypeError, AttributeError):
  3023. pass
  3024. try:
  3025. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  3026. except (TypeError, AttributeError):
  3027. pass
  3028. try:
  3029. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  3030. except (TypeError, AttributeError):
  3031. pass
  3032. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_command)
  3033. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  3034. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  3035. # Geometry Editor
  3036. try:
  3037. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  3038. except (TypeError, AttributeError):
  3039. pass
  3040. try:
  3041. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  3042. except (TypeError, AttributeError):
  3043. pass
  3044. try:
  3045. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  3046. except (TypeError, AttributeError):
  3047. pass
  3048. try:
  3049. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  3050. except (TypeError, AttributeError):
  3051. pass
  3052. try:
  3053. self.app.ui.draw_circle.triggered.disconnect()
  3054. except (TypeError, AttributeError):
  3055. pass
  3056. try:
  3057. self.app.ui.draw_poly.triggered.disconnect()
  3058. except (TypeError, AttributeError):
  3059. pass
  3060. try:
  3061. self.app.ui.draw_arc.triggered.disconnect()
  3062. except (TypeError, AttributeError):
  3063. pass
  3064. try:
  3065. self.app.ui.draw_text.triggered.disconnect()
  3066. except (TypeError, AttributeError):
  3067. pass
  3068. try:
  3069. self.app.ui.draw_buffer.triggered.disconnect()
  3070. except (TypeError, AttributeError):
  3071. pass
  3072. try:
  3073. self.app.ui.draw_paint.triggered.disconnect()
  3074. except (TypeError, AttributeError):
  3075. pass
  3076. try:
  3077. self.app.ui.draw_eraser.triggered.disconnect()
  3078. except (TypeError, AttributeError):
  3079. pass
  3080. try:
  3081. self.app.ui.draw_union.triggered.disconnect(self.union)
  3082. except (TypeError, AttributeError):
  3083. pass
  3084. try:
  3085. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  3086. except (TypeError, AttributeError):
  3087. pass
  3088. try:
  3089. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  3090. except (TypeError, AttributeError):
  3091. pass
  3092. try:
  3093. self.app.ui.draw_transform.triggered.disconnect()
  3094. except (TypeError, AttributeError):
  3095. pass
  3096. try:
  3097. self.app.jump_signal.disconnect()
  3098. except (TypeError, AttributeError):
  3099. pass
  3100. def add_shape(self, shape):
  3101. """
  3102. Adds a shape to the shape storage.
  3103. :param shape: Shape to be added.
  3104. :type shape: DrawToolShape
  3105. :return: None
  3106. """
  3107. if shape is None:
  3108. return
  3109. # List of DrawToolShape?
  3110. if isinstance(shape, list):
  3111. for subshape in shape:
  3112. self.add_shape(subshape)
  3113. return
  3114. assert isinstance(shape, DrawToolShape), "Expected a DrawToolShape, got %s" % type(shape)
  3115. assert shape.geo is not None, "Shape object has empty geometry (None)"
  3116. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  3117. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  3118. if isinstance(shape, DrawToolUtilityShape):
  3119. self.utility.append(shape)
  3120. else:
  3121. self.storage.insert(shape) # TODO: Check performance
  3122. self.build_ui()
  3123. def delete_utility_geometry(self):
  3124. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3125. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3126. for_deletion = [shape for shape in self.utility]
  3127. for shape in for_deletion:
  3128. self.delete_shape(shape)
  3129. self.tool_shape.clear(update=True)
  3130. self.tool_shape.redraw()
  3131. def toolbar_tool_toggle(self, key):
  3132. self.options[key] = self.sender().isChecked()
  3133. return 1 if self.options[key] == True else 0
  3134. def clear(self):
  3135. self.active_tool = None
  3136. # self.shape_buffer = []
  3137. self.selected = []
  3138. self.shapes.clear(update=True)
  3139. self.tool_shape.clear(update=True)
  3140. # self.storage = FlatCAMGeoEditor.make_storage()
  3141. self.replot()
  3142. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  3143. """
  3144. Imports the geometry from the given FlatCAM Geometry object
  3145. into the editor.
  3146. :param fcgeometry: FlatCAMGeometry
  3147. :param multigeo_tool: a tool for the case of multigeo
  3148. :return: None
  3149. """
  3150. assert isinstance(fcgeometry, Geometry), \
  3151. "Expected a Geometry, got %s" % type(fcgeometry)
  3152. self.deactivate()
  3153. self.activate()
  3154. self.set_ui()
  3155. # Hide original geometry
  3156. self.fcgeometry = fcgeometry
  3157. fcgeometry.visible = False
  3158. # Set selection tolerance
  3159. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3160. self.select_tool("select")
  3161. if self.app.defaults['geometry_spindledir'] == 'CW':
  3162. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3163. milling_type = 1 # CCW motion = climb milling (spindle is rotating CW)
  3164. else:
  3165. milling_type = -1 # CW motion = conventional milling (spindle is rotating CW)
  3166. else:
  3167. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3168. milling_type = -1 # CCW motion = climb milling (spindle is rotating CCW)
  3169. else:
  3170. milling_type = 1 # CW motion = conventional milling (spindle is rotating CCW)
  3171. # Link shapes into editor.
  3172. if multigeo_tool:
  3173. self.multigeo_tool = multigeo_tool
  3174. geo_to_edit = self.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'],
  3175. orient_val=milling_type)
  3176. self.app.inform.emit(
  3177. '[WARNING_NOTCL] %s: %s %s: %s' % (
  3178. _("Editing MultiGeo Geometry, tool"),
  3179. str(self.multigeo_tool),
  3180. _("with diameter"),
  3181. str(fcgeometry.tools[self.multigeo_tool]['tooldia'])
  3182. )
  3183. )
  3184. else:
  3185. geo_to_edit = self.flatten(geometry=fcgeometry.solid_geometry, orient_val=milling_type)
  3186. for shape in geo_to_edit:
  3187. if shape is not None: # TODO: Make flatten never create a None
  3188. if type(shape) == Polygon:
  3189. self.add_shape(DrawToolShape(shape.exterior))
  3190. for inter in shape.interiors:
  3191. self.add_shape(DrawToolShape(inter))
  3192. else:
  3193. self.add_shape(DrawToolShape(shape))
  3194. self.replot()
  3195. # updated units
  3196. self.units = self.app.defaults['units'].upper()
  3197. self.decimals = self.app.decimals
  3198. # start with GRID toolbar activated
  3199. if self.app.ui.grid_snap_btn.isChecked() is False:
  3200. self.app.ui.grid_snap_btn.trigger()
  3201. self.app.on_grid_snap_triggered(state=True)
  3202. def on_buffer_tool(self):
  3203. buff_tool = BufferSelectionTool(self.app, self)
  3204. buff_tool.run()
  3205. def on_paint_tool(self):
  3206. paint_tool = PaintOptionsTool(self.app, self)
  3207. paint_tool.run()
  3208. def on_tool_select(self, tool):
  3209. """
  3210. Behavior of the toolbar. Tool initialization.
  3211. :rtype : None
  3212. """
  3213. self.app.log.debug("on_tool_select('%s')" % tool)
  3214. # This is to make the group behave as radio group
  3215. if tool in self.tools:
  3216. if self.tools[tool]["button"].isChecked():
  3217. self.app.log.debug("%s is checked." % tool)
  3218. for t in self.tools:
  3219. if t != tool:
  3220. self.tools[t]["button"].setChecked(False)
  3221. self.active_tool = self.tools[tool]["constructor"](self)
  3222. else:
  3223. self.app.log.debug("%s is NOT checked." % tool)
  3224. for t in self.tools:
  3225. self.tools[t]["button"].setChecked(False)
  3226. self.select_tool('select')
  3227. self.active_tool = FCSelect(self)
  3228. def draw_tool_path(self):
  3229. self.select_tool('path')
  3230. return
  3231. def draw_tool_rectangle(self):
  3232. self.select_tool('rectangle')
  3233. return
  3234. def on_grid_toggled(self):
  3235. self.toolbar_tool_toggle("grid_snap")
  3236. # make sure that the cursor shape is enabled/disabled, too
  3237. if self.options['grid_snap'] is True:
  3238. self.app.app_cursor.enabled = True
  3239. else:
  3240. self.app.app_cursor.enabled = False
  3241. def on_canvas_click(self, event):
  3242. """
  3243. event.x and .y have canvas coordinates
  3244. event.xdaya and .ydata have plot coordinates
  3245. :param event: Event object dispatched by Matplotlib
  3246. :return: None
  3247. """
  3248. if self.app.is_legacy is False:
  3249. event_pos = event.pos
  3250. else:
  3251. event_pos = (event.xdata, event.ydata)
  3252. self.pos = self.canvas.translate_coords(event_pos)
  3253. if self.app.grid_status():
  3254. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  3255. else:
  3256. self.pos = (self.pos[0], self.pos[1])
  3257. if event.button == 1:
  3258. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3259. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3260. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3261. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3262. if modifiers == QtCore.Qt.ShiftModifier:
  3263. self.app.clipboard.setText(
  3264. self.app.defaults["global_point_clipboard_format"] %
  3265. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  3266. )
  3267. return
  3268. # Selection with left mouse button
  3269. if self.active_tool is not None and event.button == 1:
  3270. # Dispatch event to active_tool
  3271. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3272. # If it is a shape generating tool
  3273. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3274. self.on_shape_complete()
  3275. if isinstance(self.active_tool, FCText):
  3276. self.select_tool("select")
  3277. else:
  3278. self.select_tool(self.active_tool.name)
  3279. if isinstance(self.active_tool, FCSelect):
  3280. # self.app.log.debug("Replotting after click.")
  3281. self.replot()
  3282. else:
  3283. self.app.log.debug("No active tool to respond to click!")
  3284. def on_canvas_move(self, event):
  3285. """
  3286. Called on 'mouse_move' event
  3287. event.pos have canvas screen coordinates
  3288. :param event: Event object dispatched by VisPy SceneCavas
  3289. :return: None
  3290. """
  3291. if self.app.is_legacy is False:
  3292. event_pos = event.pos
  3293. event_is_dragging = event.is_dragging
  3294. right_button = 2
  3295. else:
  3296. event_pos = (event.xdata, event.ydata)
  3297. event_is_dragging = self.app.plotcanvas.is_dragging
  3298. right_button = 3
  3299. pos = self.canvas.translate_coords(event_pos)
  3300. event.xdata, event.ydata = pos[0], pos[1]
  3301. self.x = event.xdata
  3302. self.y = event.ydata
  3303. self.app.ui.popMenu.mouse_is_panning = False
  3304. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3305. if event.button == right_button:
  3306. if event_is_dragging:
  3307. self.app.ui.popMenu.mouse_is_panning = True
  3308. # return
  3309. else:
  3310. self.app.ui.popMenu.mouse_is_panning = False
  3311. if self.active_tool is None:
  3312. return
  3313. try:
  3314. x = float(event.xdata)
  3315. y = float(event.ydata)
  3316. except TypeError:
  3317. return
  3318. # ### Snap coordinates ###
  3319. if self.app.grid_status():
  3320. x, y = self.snap(x, y)
  3321. # Update cursor
  3322. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3323. edge_width=self.app.defaults["global_cursor_width"],
  3324. size=self.app.defaults["global_cursor_size"])
  3325. self.snap_x = x
  3326. self.snap_y = y
  3327. self.app.mouse = [x, y]
  3328. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3329. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3330. "<b>Y</b>: %.4f" % (x, y))
  3331. if self.pos is None:
  3332. self.pos = (0, 0)
  3333. dx = x - self.pos[0]
  3334. dy = y - self.pos[1]
  3335. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3336. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3337. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3338. if event.button == 1 and event_is_dragging and isinstance(self.active_tool, FCEraser):
  3339. pass
  3340. else:
  3341. self.update_utility_geometry(data=(x, y))
  3342. # ### Selection area on canvas section ###
  3343. dx = pos[0] - self.pos[0]
  3344. if event_is_dragging and event.button == 1:
  3345. self.app.delete_selection_shape()
  3346. if dx < 0:
  3347. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3348. color=self.app.defaults["global_alt_sel_line"],
  3349. face_color=self.app.defaults['global_alt_sel_fill'])
  3350. self.app.selection_type = False
  3351. else:
  3352. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3353. self.app.selection_type = True
  3354. else:
  3355. self.app.selection_type = None
  3356. def update_utility_geometry(self, data):
  3357. # ### Utility geometry (animated) ###
  3358. geo = self.active_tool.utility_geometry(data=data)
  3359. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3360. # Remove any previous utility shape
  3361. self.tool_shape.clear(update=True)
  3362. self.draw_utility_geometry(geo=geo)
  3363. def on_geo_click_release(self, event):
  3364. if self.app.is_legacy is False:
  3365. event_pos = event.pos
  3366. event_is_dragging = event.is_dragging
  3367. right_button = 2
  3368. else:
  3369. event_pos = (event.xdata, event.ydata)
  3370. event_is_dragging = self.app.plotcanvas.is_dragging
  3371. right_button = 3
  3372. pos_canvas = self.canvas.translate_coords(event_pos)
  3373. if self.app.grid_status() == True:
  3374. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3375. else:
  3376. pos = (pos_canvas[0], pos_canvas[1])
  3377. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3378. # canvas menu
  3379. try:
  3380. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3381. # selection and then select a type of selection ("enclosing" or "touching")
  3382. if event.button == 1: # left click
  3383. if self.app.selection_type is not None:
  3384. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3385. self.app.selection_type = None
  3386. elif isinstance(self.active_tool, FCSelect):
  3387. # Dispatch event to active_tool
  3388. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3389. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3390. # self.app.inform.emit(msg)
  3391. self.replot()
  3392. elif event.button == right_button: # right click
  3393. if self.app.ui.popMenu.mouse_is_panning is False:
  3394. if self.in_action is False:
  3395. try:
  3396. QtGui.QGuiApplication.restoreOverrideCursor()
  3397. except Exception:
  3398. pass
  3399. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3400. self.active_tool.complete = True
  3401. self.in_action = False
  3402. self.delete_utility_geometry()
  3403. self.app.inform.emit('[success] %s' % _("Done."))
  3404. self.select_tool('select')
  3405. else:
  3406. self.app.cursor = QtGui.QCursor()
  3407. self.app.populate_cmenu_grids()
  3408. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3409. else:
  3410. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3411. # right mouse click will finish the action
  3412. if isinstance(self.active_tool, FCShapeTool):
  3413. self.active_tool.click(self.snap(self.x, self.y))
  3414. self.active_tool.make()
  3415. if self.active_tool.complete:
  3416. self.on_shape_complete()
  3417. self.app.inform.emit('[success] %s' % _("Done."))
  3418. self.select_tool(self.active_tool.name)
  3419. except Exception as e:
  3420. log.warning("FLatCAMGeoEditor.on_geo_click_release() --> Error: %s" % str(e))
  3421. return
  3422. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3423. """
  3424. :param start_pos: mouse position when the selection LMB click was done
  3425. :param end_pos: mouse position when the left mouse button is released
  3426. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3427. :return:
  3428. """
  3429. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3430. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3431. if key_modifier == QtCore.Qt.ShiftModifier:
  3432. mod_key = 'Shift'
  3433. elif key_modifier == QtCore.Qt.ControlModifier:
  3434. mod_key = 'Control'
  3435. else:
  3436. mod_key = None
  3437. self.app.delete_selection_shape()
  3438. sel_objects_list = []
  3439. for obj in self.storage.get_objects():
  3440. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3441. poly_selection.intersects(obj.geo)):
  3442. sel_objects_list.append(obj)
  3443. if mod_key == self.app.defaults["global_mselect_key"]:
  3444. for obj in sel_objects_list:
  3445. if obj in self.selected:
  3446. self.selected.remove(obj)
  3447. else:
  3448. # add the object to the selected shapes
  3449. self.selected.append(obj)
  3450. else:
  3451. self.selected = []
  3452. self.selected = sel_objects_list
  3453. # if selection is done on canvas update the Tree in Selected Tab with the selection
  3454. try:
  3455. self.tw.itemSelectionChanged.disconnect(self.on_tree_selection_change)
  3456. except (AttributeError, TypeError):
  3457. pass
  3458. self.tw.selectionModel().clearSelection()
  3459. for sel_shape in self.selected:
  3460. iterator = QtWidgets.QTreeWidgetItemIterator(self.tw)
  3461. while iterator.value():
  3462. item = iterator.value()
  3463. try:
  3464. if int(item.text(1)) == id(sel_shape):
  3465. item.setSelected(True)
  3466. except ValueError:
  3467. pass
  3468. iterator += 1
  3469. self.tw.itemSelectionChanged.connect(self.on_tree_selection_change)
  3470. self.replot()
  3471. def draw_utility_geometry(self, geo):
  3472. # Add the new utility shape
  3473. try:
  3474. # this case is for the Font Parse
  3475. for el in list(geo.geo):
  3476. if type(el) == MultiPolygon:
  3477. for poly in el:
  3478. self.tool_shape.add(
  3479. shape=poly,
  3480. color=(self.app.defaults["global_draw_color"] + '80'),
  3481. update=False,
  3482. layer=0,
  3483. tolerance=None
  3484. )
  3485. elif type(el) == MultiLineString:
  3486. for linestring in el:
  3487. self.tool_shape.add(
  3488. shape=linestring,
  3489. color=(self.app.defaults["global_draw_color"] + '80'),
  3490. update=False,
  3491. layer=0,
  3492. tolerance=None
  3493. )
  3494. else:
  3495. self.tool_shape.add(
  3496. shape=el,
  3497. color=(self.app.defaults["global_draw_color"] + '80'),
  3498. update=False,
  3499. layer=0,
  3500. tolerance=None
  3501. )
  3502. except TypeError:
  3503. self.tool_shape.add(
  3504. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3505. update=False, layer=0, tolerance=None)
  3506. self.tool_shape.redraw()
  3507. def on_delete_btn(self):
  3508. self.delete_selected()
  3509. self.replot()
  3510. def delete_selected(self):
  3511. tempref = [s for s in self.selected]
  3512. for shape in tempref:
  3513. self.delete_shape(shape)
  3514. self.selected = []
  3515. self.build_ui()
  3516. def delete_shape(self, shape):
  3517. if shape in self.utility:
  3518. self.utility.remove(shape)
  3519. return
  3520. self.storage.remove(shape)
  3521. if shape in self.selected:
  3522. self.selected.remove(shape) # TODO: Check performance
  3523. def on_move(self):
  3524. # if not self.selected:
  3525. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3526. # return
  3527. self.app.ui.geo_move_btn.setChecked(True)
  3528. self.on_tool_select('move')
  3529. def on_move_click(self):
  3530. self.on_move()
  3531. self.active_tool.set_origin(self.snap(self.x, self.y))
  3532. def on_copy_click(self):
  3533. if not self.selected:
  3534. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3535. _("Copy cancelled. No shape selected."))
  3536. return
  3537. self.app.ui.geo_copy_btn.setChecked(True)
  3538. self.app.geo_editor.on_tool_select('copy')
  3539. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3540. self.app.geo_editor.x, self.app.geo_editor.y))
  3541. self.app.inform.emit(_("Click on target point."))
  3542. def on_corner_snap(self):
  3543. self.app.ui.corner_snap_btn.trigger()
  3544. def get_selected(self):
  3545. """
  3546. Returns list of shapes that are selected in the editor.
  3547. :return: List of shapes.
  3548. """
  3549. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3550. return self.selected
  3551. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3552. """
  3553. Plots a geometric object or list of objects without rendering. Plotted objects
  3554. are returned as a list. This allows for efficient/animated rendering.
  3555. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3556. :param color: Shape color
  3557. :param linewidth: Width of lines in # of pixels.
  3558. :return: List of plotted elements.
  3559. """
  3560. plot_elements = []
  3561. if geometry is None:
  3562. geometry = self.active_tool.geometry
  3563. try:
  3564. for geo in geometry:
  3565. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3566. # Non-iterable
  3567. except TypeError:
  3568. # DrawToolShape
  3569. if isinstance(geometry, DrawToolShape):
  3570. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3571. # Polygon: Descend into exterior and each interior.
  3572. if type(geometry) == Polygon:
  3573. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3574. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3575. if type(geometry) == LineString or type(geometry) == LinearRing:
  3576. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3577. tolerance=self.fcgeometry.drawing_tolerance,
  3578. linewidth=linewidth))
  3579. if type(geometry) == Point:
  3580. pass
  3581. return plot_elements
  3582. def plot_all(self):
  3583. """
  3584. Plots all shapes in the editor.
  3585. :return: None
  3586. :rtype: None
  3587. """
  3588. # self.app.log.debug("plot_all()")
  3589. self.shapes.clear(update=True)
  3590. for shape in self.storage.get_objects():
  3591. if shape.geo is None: # TODO: This shouldn't have happened
  3592. continue
  3593. if shape in self.selected:
  3594. self.plot_shape(geometry=shape.geo,
  3595. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3596. linewidth=2)
  3597. continue
  3598. self.plot_shape(geometry=shape.geo,
  3599. color=self.app.defaults['global_draw_color'] + "FF")
  3600. for shape in self.utility:
  3601. self.plot_shape(geometry=shape.geo,
  3602. linewidth=1)
  3603. continue
  3604. self.shapes.redraw()
  3605. def replot(self):
  3606. self.plot_all()
  3607. def on_shape_complete(self):
  3608. self.app.log.debug("on_shape_complete()")
  3609. geom = []
  3610. try:
  3611. for shape in self.active_tool.geometry:
  3612. geom.append(shape.geo)
  3613. except TypeError:
  3614. geom = self.active_tool.geometry.geo
  3615. if self.app.defaults['geometry_editor_milling_type'] == 'cl':
  3616. # reverse the geometry coordinates direction to allow creation of Gcode for climb milling
  3617. try:
  3618. pl = []
  3619. for p in geom:
  3620. if p is not None:
  3621. if isinstance(p, Polygon):
  3622. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3623. elif isinstance(p, LinearRing):
  3624. pl.append(Polygon(p.coords[::-1]))
  3625. elif isinstance(p, LineString):
  3626. pl.append(LineString(p.coords[::-1]))
  3627. try:
  3628. geom = MultiPolygon(pl)
  3629. except TypeError:
  3630. # this may happen if the geom elements are made out of LineStrings because you can't create a
  3631. # MultiPolygon out of LineStrings
  3632. pass
  3633. except TypeError:
  3634. if isinstance(geom, Polygon) and geom is not None:
  3635. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3636. elif isinstance(geom, LinearRing) and geom is not None:
  3637. geom = Polygon(geom.coords[::-1])
  3638. elif isinstance(geom, LineString) and geom is not None:
  3639. geom = LineString(geom.coords[::-1])
  3640. else:
  3641. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> Unexpected Geometry %s" %
  3642. type(geom))
  3643. except Exception as e:
  3644. log.debug("FlatCAMGeoEditor.on_shape_complete() Error --> %s" % str(e))
  3645. return 'fail'
  3646. shape_list = list()
  3647. try:
  3648. for geo in geom:
  3649. shape_list.append(DrawToolShape(geo))
  3650. except TypeError:
  3651. shape_list.append(DrawToolShape(geom))
  3652. # Add shape
  3653. self.add_shape(shape_list)
  3654. # Remove any utility shapes
  3655. self.delete_utility_geometry()
  3656. self.tool_shape.clear(update=True)
  3657. # Replot and reset tool.
  3658. self.replot()
  3659. # self.active_tool = type(self.active_tool)(self)
  3660. @staticmethod
  3661. def make_storage():
  3662. # Shape storage.
  3663. storage = FlatCAMRTreeStorage()
  3664. storage.get_points = DrawToolShape.get_pts
  3665. return storage
  3666. def select_tool(self, toolname):
  3667. """
  3668. Selects a drawing tool. Impacts the object and GUI.
  3669. :param toolname: Name of the tool.
  3670. :return: None
  3671. """
  3672. self.tools[toolname]["button"].setChecked(True)
  3673. self.on_tool_select(toolname)
  3674. def set_selected(self, shape):
  3675. # Remove and add to the end.
  3676. if shape in self.selected:
  3677. self.selected.remove(shape)
  3678. self.selected.append(shape)
  3679. def set_unselected(self, shape):
  3680. if shape in self.selected:
  3681. self.selected.remove(shape)
  3682. def snap(self, x, y):
  3683. """
  3684. Adjusts coordinates to snap settings.
  3685. :param x: Input coordinate X
  3686. :param y: Input coordinate Y
  3687. :return: Snapped (x, y)
  3688. """
  3689. snap_x, snap_y = (x, y)
  3690. snap_distance = np.Inf
  3691. # # ## Object (corner?) snap
  3692. # # ## No need for the objects, just the coordinates
  3693. # # ## in the index.
  3694. if self.options["corner_snap"]:
  3695. try:
  3696. nearest_pt, shape = self.storage.nearest((x, y))
  3697. nearest_pt_distance = distance((x, y), nearest_pt)
  3698. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3699. snap_distance = nearest_pt_distance
  3700. snap_x, snap_y = nearest_pt
  3701. except (StopIteration, AssertionError):
  3702. pass
  3703. # # ## Grid snap
  3704. if self.options["grid_snap"]:
  3705. if self.options["global_gridx"] != 0:
  3706. try:
  3707. snap_x_ = round(x / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3708. except TypeError:
  3709. snap_x_ = x
  3710. else:
  3711. snap_x_ = x
  3712. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3713. # and it will use the snap distance from GridX entry
  3714. if self.app.ui.grid_gap_link_cb.isChecked():
  3715. if self.options["global_gridx"] != 0:
  3716. try:
  3717. snap_y_ = round(y / float(self.options["global_gridx"])) * float(self.options['global_gridx'])
  3718. except TypeError:
  3719. snap_y_ = y
  3720. else:
  3721. snap_y_ = y
  3722. else:
  3723. if self.options["global_gridy"] != 0:
  3724. try:
  3725. snap_y_ = round(y / float(self.options["global_gridy"])) * float(self.options['global_gridy'])
  3726. except TypeError:
  3727. snap_y_ = y
  3728. else:
  3729. snap_y_ = y
  3730. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3731. if nearest_grid_distance < snap_distance:
  3732. snap_x, snap_y = (snap_x_, snap_y_)
  3733. return snap_x, snap_y
  3734. def update_fcgeometry(self, fcgeometry):
  3735. """
  3736. Transfers the geometry tool shape buffer to the selected geometry
  3737. object. The geometry already in the object are removed.
  3738. :param fcgeometry: FlatCAMGeometry
  3739. :return: None
  3740. """
  3741. if self.multigeo_tool:
  3742. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3743. # for shape in self.shape_buffer:
  3744. for shape in self.storage.get_objects():
  3745. new_geo = shape.geo
  3746. # simplify the MultiLineString
  3747. if isinstance(new_geo, MultiLineString):
  3748. new_geo = linemerge(new_geo)
  3749. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(new_geo)
  3750. self.multigeo_tool = None
  3751. fcgeometry.solid_geometry = []
  3752. # for shape in self.shape_buffer:
  3753. for shape in self.storage.get_objects():
  3754. new_geo = shape.geo
  3755. # simplify the MultiLineString
  3756. if isinstance(new_geo, MultiLineString):
  3757. new_geo = linemerge(new_geo)
  3758. fcgeometry.solid_geometry.append(new_geo)
  3759. def update_options(self, obj):
  3760. if self.paint_tooldia:
  3761. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3762. self.paint_tooldia = None
  3763. return True
  3764. else:
  3765. return False
  3766. def union(self):
  3767. """
  3768. Makes union of selected polygons. Original polygons
  3769. are deleted.
  3770. :return: None.
  3771. """
  3772. results = unary_union([t.geo for t in self.get_selected()])
  3773. # Delete originals.
  3774. for_deletion = [s for s in self.get_selected()]
  3775. for shape in for_deletion:
  3776. self.delete_shape(shape)
  3777. # Selected geometry is now gone!
  3778. self.selected = []
  3779. self.add_shape(DrawToolShape(results))
  3780. self.replot()
  3781. def intersection_2(self):
  3782. """
  3783. Makes intersection of selected polygons. Original polygons are deleted.
  3784. :return: None
  3785. """
  3786. geo_shapes = self.get_selected()
  3787. try:
  3788. results = geo_shapes[0].geo
  3789. except Exception as e:
  3790. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3791. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3792. _("A selection of at least 2 geo items is required to do Intersection."))
  3793. self.select_tool('select')
  3794. return
  3795. for shape_el in geo_shapes[1:]:
  3796. results = results.intersection(shape_el.geo)
  3797. # Delete originals.
  3798. for_deletion = [s for s in self.get_selected()]
  3799. for shape_el in for_deletion:
  3800. self.delete_shape(shape_el)
  3801. # Selected geometry is now gone!
  3802. self.selected = []
  3803. self.add_shape(DrawToolShape(results))
  3804. self.replot()
  3805. def intersection(self):
  3806. """
  3807. Makes intersection of selected polygons. Original polygons are deleted.
  3808. :return: None
  3809. """
  3810. geo_shapes = self.get_selected()
  3811. results = []
  3812. intact = []
  3813. try:
  3814. intersector = geo_shapes[0].geo
  3815. except Exception as e:
  3816. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3817. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3818. _("A selection of at least 2 geo items is required to do Intersection."))
  3819. self.select_tool('select')
  3820. return
  3821. for shape_el in geo_shapes[1:]:
  3822. if intersector.intersects(shape_el.geo):
  3823. results.append(intersector.intersection(shape_el.geo))
  3824. else:
  3825. intact.append(shape_el)
  3826. if len(results) != 0:
  3827. # Delete originals.
  3828. for_deletion = [s for s in self.get_selected()]
  3829. for shape_el in for_deletion:
  3830. if shape_el not in intact:
  3831. self.delete_shape(shape_el)
  3832. for geo in results:
  3833. self.add_shape(DrawToolShape(geo))
  3834. # Selected geometry is now gone!
  3835. self.selected = []
  3836. self.replot()
  3837. def subtract(self):
  3838. selected = self.get_selected()
  3839. try:
  3840. tools = selected[1:]
  3841. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3842. target = selected[0].geo
  3843. target = target.buffer(0.0000001)
  3844. result = target.difference(toolgeo)
  3845. for_deletion = [s for s in self.get_selected()]
  3846. for shape in for_deletion:
  3847. self.delete_shape(shape)
  3848. self.add_shape(DrawToolShape(result))
  3849. self.replot()
  3850. except Exception as e:
  3851. log.debug(str(e))
  3852. def subtract_2(self):
  3853. selected = self.get_selected()
  3854. try:
  3855. tools = selected[1:]
  3856. toolgeo = unary_union([shp.geo for shp in tools])
  3857. result = selected[0].geo.difference(toolgeo)
  3858. self.delete_shape(selected[0])
  3859. self.add_shape(DrawToolShape(result))
  3860. self.replot()
  3861. except Exception as e:
  3862. log.debug(str(e))
  3863. def cutpath(self):
  3864. selected = self.get_selected()
  3865. tools = selected[1:]
  3866. toolgeo = unary_union([shp.geo for shp in tools])
  3867. target = selected[0]
  3868. if type(target.geo) == Polygon:
  3869. for ring in poly2rings(target.geo):
  3870. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3871. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3872. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3873. elif type(target.geo) == MultiLineString:
  3874. try:
  3875. for linestring in target.geo:
  3876. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3877. except Exception as e:
  3878. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3879. else:
  3880. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3881. return
  3882. self.delete_shape(target)
  3883. self.replot()
  3884. def buffer(self, buf_distance, join_style):
  3885. selected = self.get_selected()
  3886. if buf_distance < 0:
  3887. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3888. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3889. "'inside' shape"))
  3890. # deselect everything
  3891. self.selected = []
  3892. self.replot()
  3893. return 'fail'
  3894. if len(selected) == 0:
  3895. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3896. _("Nothing selected for buffering."))
  3897. return 'fail'
  3898. if not isinstance(buf_distance, float):
  3899. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3900. _("Invalid distance for buffering."))
  3901. # deselect everything
  3902. self.selected = []
  3903. self.replot()
  3904. return 'fail'
  3905. results = []
  3906. for t in selected:
  3907. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3908. results.append(t.geo.exterior.buffer(
  3909. buf_distance - 1e-10,
  3910. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3911. join_style=join_style)
  3912. )
  3913. else:
  3914. results.append(t.geo.buffer(
  3915. buf_distance - 1e-10,
  3916. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3917. join_style=join_style)
  3918. )
  3919. if not results:
  3920. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3921. _("Failed, the result is empty. Choose a different buffer value."))
  3922. # deselect everything
  3923. self.selected = []
  3924. self.replot()
  3925. return 'fail'
  3926. for sha in results:
  3927. self.add_shape(DrawToolShape(sha))
  3928. self.replot()
  3929. self.app.inform.emit('[success] %s' %
  3930. _("Full buffer geometry created."))
  3931. def buffer_int(self, buf_distance, join_style):
  3932. selected = self.get_selected()
  3933. if buf_distance < 0:
  3934. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Negative buffer value is not accepted."))
  3935. # deselect everything
  3936. self.selected = []
  3937. self.replot()
  3938. return 'fail'
  3939. if len(selected) == 0:
  3940. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for buffering."))
  3941. return 'fail'
  3942. if not isinstance(buf_distance, float):
  3943. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Invalid distance for buffering."))
  3944. # deselect everything
  3945. self.selected = []
  3946. self.replot()
  3947. return 'fail'
  3948. results = []
  3949. for t in selected:
  3950. if isinstance(t.geo, LinearRing):
  3951. t.geo = Polygon(t.geo)
  3952. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3953. results.append(t.geo.buffer(
  3954. -buf_distance + 1e-10,
  3955. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3956. join_style=join_style)
  3957. )
  3958. if not results:
  3959. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3960. _("Failed, the result is empty. Choose a smaller buffer value."))
  3961. # deselect everything
  3962. self.selected = []
  3963. self.replot()
  3964. return 'fail'
  3965. for sha in results:
  3966. self.add_shape(DrawToolShape(sha))
  3967. self.replot()
  3968. self.app.inform.emit('[success] %s' % _("Interior buffer geometry created."))
  3969. def buffer_ext(self, buf_distance, join_style):
  3970. selected = self.get_selected()
  3971. if buf_distance < 0:
  3972. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3973. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3974. "'inside' shape"))
  3975. # deselect everything
  3976. self.selected = []
  3977. self.replot()
  3978. return
  3979. if len(selected) == 0:
  3980. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3981. _("Nothing selected for buffering."))
  3982. return
  3983. if not isinstance(buf_distance, float):
  3984. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3985. _("Invalid distance for buffering."))
  3986. # deselect everything
  3987. self.selected = []
  3988. self.replot()
  3989. return
  3990. results = []
  3991. for t in selected:
  3992. if isinstance(t.geo, LinearRing):
  3993. t.geo = Polygon(t.geo)
  3994. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3995. results.append(t.geo.buffer(
  3996. buf_distance,
  3997. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3998. join_style=join_style)
  3999. )
  4000. if not results:
  4001. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4002. _("Failed, the result is empty. Choose a different buffer value."))
  4003. # deselect everything
  4004. self.selected = []
  4005. self.replot()
  4006. return
  4007. for sha in results:
  4008. self.add_shape(DrawToolShape(sha))
  4009. self.replot()
  4010. self.app.inform.emit('[success] %s' % _("Exterior buffer geometry created."))
  4011. def paint(self, tooldia, overlap, margin, connect, contour, method):
  4012. if overlap >= 100:
  4013. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4014. _("Could not do Paint. Overlap value has to be less than 100%%."))
  4015. return
  4016. self.paint_tooldia = tooldia
  4017. selected = self.get_selected()
  4018. if len(selected) == 0:
  4019. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Nothing selected for painting."))
  4020. return
  4021. for param in [tooldia, overlap, margin]:
  4022. if not isinstance(param, float):
  4023. param_name = [k for k, v in locals().items() if v is param][0]
  4024. self.app.inform.emit('[WARNING] %s: %s' % (_("Invalid value for"), str(param)))
  4025. results = []
  4026. def recurse(geometry, reset=True):
  4027. """
  4028. Creates a list of non-iterable linear geometry objects.
  4029. Results are placed in self.flat_geometry
  4030. :param geometry: Shapely type or list or list of list of such.
  4031. :param reset: Clears the contents of self.flat_geometry.
  4032. """
  4033. if geometry is None:
  4034. return
  4035. if reset:
  4036. self.flat_geo = []
  4037. # If iterable, expand recursively.
  4038. try:
  4039. for geo_el in geometry:
  4040. if geo_el is not None:
  4041. recurse(geometry=geo_el, reset=False)
  4042. # Not iterable, do the actual indexing and add.
  4043. except TypeError:
  4044. self.flat_geo.append(geometry)
  4045. return self.flat_geo
  4046. for geo in selected:
  4047. local_results = []
  4048. for geo_obj in recurse(geo.geo):
  4049. try:
  4050. if type(geo_obj) == Polygon:
  4051. poly_buf = geo_obj.buffer(-margin)
  4052. else:
  4053. poly_buf = Polygon(geo_obj).buffer(-margin)
  4054. if method == "seed":
  4055. cp = Geometry.clear_polygon2(self, polygon_to_clear=poly_buf, tooldia=tooldia,
  4056. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4057. overlap=overlap, contour=contour, connect=connect)
  4058. elif method == "lines":
  4059. cp = Geometry.clear_polygon3(self, polygon=poly_buf, tooldia=tooldia,
  4060. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4061. overlap=overlap, contour=contour, connect=connect)
  4062. else:
  4063. cp = Geometry.clear_polygon(self, polygon=poly_buf, tooldia=tooldia,
  4064. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  4065. overlap=overlap, contour=contour, connect=connect)
  4066. if cp is not None:
  4067. local_results += list(cp.get_objects())
  4068. except Exception as e:
  4069. log.debug("Could not Paint the polygons. %s" % str(e))
  4070. self.app.inform.emit('[ERROR] %s\n%s' %
  4071. (_("Could not do Paint. Try a different combination of"
  4072. " parameters. Or a different method of Paint"),
  4073. str(e)
  4074. )
  4075. )
  4076. return
  4077. # add the result to the results list
  4078. results.append(cascaded_union(local_results))
  4079. # This is a dirty patch:
  4080. for r in results:
  4081. self.add_shape(DrawToolShape(r))
  4082. self.app.inform.emit(
  4083. '[success] %s' % _("Paint done."))
  4084. self.replot()
  4085. def flatten(self, geometry, orient_val=1, reset=True, pathonly=False):
  4086. """
  4087. Creates a list of non-iterable linear geometry objects.
  4088. Polygons are expanded into its exterior and interiors if specified.
  4089. Results are placed in self.flat_geometry
  4090. :param geometry: Shapely type or list or list of list of such.
  4091. :param orient_val: will orient the exterior coordinates CW if 1 and CCW for else (whatever else means ...)
  4092. https://shapely.readthedocs.io/en/stable/manual.html#polygons
  4093. :param reset: Clears the contents of self.flat_geometry.
  4094. :param pathonly: Expands polygons into linear elements.
  4095. """
  4096. if reset:
  4097. self.flat_geo = []
  4098. # ## If iterable, expand recursively.
  4099. try:
  4100. for geo in geometry:
  4101. if geo is not None:
  4102. self.flatten(geometry=geo,
  4103. orient_val=orient_val,
  4104. reset=False,
  4105. pathonly=pathonly)
  4106. # ## Not iterable, do the actual indexing and add.
  4107. except TypeError:
  4108. if type(geometry) == Polygon:
  4109. geometry = orient(geometry, orient_val)
  4110. if pathonly and type(geometry) == Polygon:
  4111. self.flat_geo.append(geometry.exterior)
  4112. self.flatten(geometry=geometry.interiors,
  4113. reset=False,
  4114. pathonly=True)
  4115. else:
  4116. self.flat_geo.append(geometry)
  4117. return self.flat_geo
  4118. def distance(pt1, pt2):
  4119. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4120. def mag(vec):
  4121. return np.sqrt(vec[0] ** 2 + vec[1] ** 2)
  4122. def poly2rings(poly):
  4123. return [poly.exterior] + [interior for interior in poly.interiors]
  4124. def get_shapely_list_bounds(geometry_list):
  4125. xmin = np.Inf
  4126. ymin = np.Inf
  4127. xmax = -np.Inf
  4128. ymax = -np.Inf
  4129. for gs in geometry_list:
  4130. try:
  4131. gxmin, gymin, gxmax, gymax = gs.bounds
  4132. xmin = min([xmin, gxmin])
  4133. ymin = min([ymin, gymin])
  4134. xmax = max([xmax, gxmax])
  4135. ymax = max([ymax, gymax])
  4136. except Exception as e:
  4137. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  4138. return [xmin, ymin, xmax, ymax]