FlatCAMGeoEditor.py 194 KB

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