FlatCAMGeoEditor.py 191 KB

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