FlatCAMEditor.py 191 KB

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