FlatCAMEditor.py 200 KB

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