FlatCAMEditor.py 247 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. ############################################################ #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. ############################################################
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. import FlatCAMApp
  15. from camlib import *
  16. from FlatCAMTool import FlatCAMTool
  17. from ObjectUI import LengthEntry, RadioSet
  18. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  19. from shapely.geometry import MultiPoint, MultiPolygon
  20. from shapely.geometry import box as shply_box
  21. from shapely.ops import cascaded_union, unary_union
  22. import shapely.affinity as affinity
  23. from shapely.wkt import loads as sloads
  24. from shapely.wkt import dumps as sdumps
  25. from shapely.geometry.base import BaseGeometry
  26. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot
  27. from numpy.linalg import solve
  28. from rtree import index as rtindex
  29. from GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCEntry2, FCComboBox, FCTextAreaRich, \
  30. VerticalScrollArea, FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  31. from ParseFont import *
  32. from vispy.scene.visuals import Markers
  33. from copy import copy
  34. import freetype as ft
  35. import gettext
  36. import FlatCAMTranslation as fcTranslate
  37. fcTranslate.apply_language('FlatCAMEditor')
  38. class BufferSelectionTool(FlatCAMTool):
  39. """
  40. Simple input for buffer distance.
  41. """
  42. toolName = "Buffer Selection"
  43. def __init__(self, app, draw_app):
  44. FlatCAMTool.__init__(self, app)
  45. self.draw_app = draw_app
  46. # Title
  47. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  48. title_label.setStyleSheet("""
  49. QLabel
  50. {
  51. font-size: 16px;
  52. font-weight: bold;
  53. }
  54. """)
  55. self.layout.addWidget(title_label)
  56. # this way I can hide/show the frame
  57. self.buffer_tool_frame = QtWidgets.QFrame()
  58. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  59. self.layout.addWidget(self.buffer_tool_frame)
  60. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  61. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  62. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  63. # Form Layout
  64. form_layout = QtWidgets.QFormLayout()
  65. self.buffer_tools_box.addLayout(form_layout)
  66. # Buffer distance
  67. self.buffer_distance_entry = FCEntry()
  68. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  69. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  70. self.buffer_corner_lbl.setToolTip(
  71. _("There are 3 types of corners:\n"
  72. " - 'Round': the corner is rounded for exterior buffer.\n"
  73. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  74. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  75. )
  76. self.buffer_corner_cb = FCComboBox()
  77. self.buffer_corner_cb.addItem(_("Round"))
  78. self.buffer_corner_cb.addItem(_("Square"))
  79. self.buffer_corner_cb.addItem(_("Beveled"))
  80. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  81. # Buttons
  82. hlay = QtWidgets.QHBoxLayout()
  83. self.buffer_tools_box.addLayout(hlay)
  84. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  85. hlay.addWidget(self.buffer_int_button)
  86. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  87. hlay.addWidget(self.buffer_ext_button)
  88. hlay1 = QtWidgets.QHBoxLayout()
  89. self.buffer_tools_box.addLayout(hlay1)
  90. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  91. hlay1.addWidget(self.buffer_button)
  92. self.layout.addStretch()
  93. # Signals
  94. self.buffer_button.clicked.connect(self.on_buffer)
  95. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  96. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  97. # Init GUI
  98. self.buffer_distance_entry.set_value(0.01)
  99. def run(self):
  100. self.app.report_usage("Geo Editor ToolBuffer()")
  101. FlatCAMTool.run(self)
  102. # if the splitter us hidden, display it
  103. if self.app.ui.splitter.sizes()[0] == 0:
  104. self.app.ui.splitter.setSizes([1, 1])
  105. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  106. def on_buffer(self):
  107. try:
  108. buffer_distance = float(self.buffer_distance_entry.get_value())
  109. except ValueError:
  110. # try to convert comma to decimal point. if it's still not working error message and return
  111. try:
  112. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  113. self.buffer_distance_entry.set_value(buffer_distance)
  114. except ValueError:
  115. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  116. "Add it and retry."))
  117. return
  118. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  119. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  120. join_style = self.buffer_corner_cb.currentIndex() + 1
  121. self.draw_app.buffer(buffer_distance, join_style)
  122. def on_buffer_int(self):
  123. try:
  124. buffer_distance = float(self.buffer_distance_entry.get_value())
  125. except ValueError:
  126. # try to convert comma to decimal point. if it's still not working error message and return
  127. try:
  128. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  129. self.buffer_distance_entry.set_value(buffer_distance)
  130. except ValueError:
  131. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  132. "Add it and retry."))
  133. return
  134. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  135. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  136. join_style = self.buffer_corner_cb.currentIndex() + 1
  137. self.draw_app.buffer_int(buffer_distance, join_style)
  138. def on_buffer_ext(self):
  139. try:
  140. buffer_distance = float(self.buffer_distance_entry.get_value())
  141. except ValueError:
  142. # try to convert comma to decimal point. if it's still not working error message and return
  143. try:
  144. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  145. self.buffer_distance_entry.set_value(buffer_distance)
  146. except ValueError:
  147. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  148. "Add it and retry."))
  149. return
  150. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  151. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  152. join_style = self.buffer_corner_cb.currentIndex() + 1
  153. self.draw_app.buffer_ext(buffer_distance, join_style)
  154. def hide_tool(self):
  155. self.buffer_tool_frame.hide()
  156. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  157. class TextInputTool(FlatCAMTool):
  158. """
  159. Simple input for buffer distance.
  160. """
  161. toolName = "Text Input Tool"
  162. def __init__(self, app):
  163. FlatCAMTool.__init__(self, app)
  164. self.app = app
  165. self.text_path = []
  166. self.f_parse = ParseFont(self)
  167. self.f_parse.get_fonts_by_types()
  168. # this way I can hide/show the frame
  169. self.text_tool_frame = QtWidgets.QFrame()
  170. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  171. self.layout.addWidget(self.text_tool_frame)
  172. self.text_tools_box = QtWidgets.QVBoxLayout()
  173. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  174. self.text_tool_frame.setLayout(self.text_tools_box)
  175. # Title
  176. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  177. title_label.setStyleSheet("""
  178. QLabel
  179. {
  180. font-size: 16px;
  181. font-weight: bold;
  182. }
  183. """)
  184. self.text_tools_box.addWidget(title_label)
  185. # Form Layout
  186. self.form_layout = QtWidgets.QFormLayout()
  187. self.text_tools_box.addLayout(self.form_layout)
  188. # Font type
  189. if sys.platform == "win32":
  190. f_current = QtGui.QFont("Arial")
  191. elif sys.platform == "linux":
  192. f_current = QtGui.QFont("FreeMono")
  193. else:
  194. f_current = QtGui.QFont("Helvetica Neue")
  195. self.font_name = f_current.family()
  196. self.font_type_cb = QtWidgets.QFontComboBox(self)
  197. self.font_type_cb.setCurrentFont(f_current)
  198. self.form_layout.addRow("Font:", self.font_type_cb)
  199. # Flag variables to show if font is bold, italic, both or none (regular)
  200. self.font_bold = False
  201. self.font_italic = False
  202. # # Create dictionaries with the filenames of the fonts
  203. # # Key: Fontname
  204. # # Value: Font File Name.ttf
  205. #
  206. # # regular fonts
  207. # self.ff_names_regular ={}
  208. # # bold fonts
  209. # self.ff_names_bold = {}
  210. # # italic fonts
  211. # self.ff_names_italic = {}
  212. # # bold and italic fonts
  213. # self.ff_names_bi = {}
  214. #
  215. # if sys.platform == 'win32':
  216. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  217. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  218. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  219. # try:
  220. # i = 0
  221. # while 1:
  222. # name_font, value, type = EnumValue(font_key, i)
  223. # k = name_font.replace(" (TrueType)", '')
  224. # if 'Bold' in k and 'Italic' in k:
  225. # k = k.replace(" Bold Italic", '')
  226. # self.ff_names_bi.update({k: value})
  227. # elif 'Bold' in k:
  228. # k = k.replace(" Bold", '')
  229. # self.ff_names_bold.update({k: value})
  230. # elif 'Italic' in k:
  231. # k = k.replace(" Italic", '')
  232. # self.ff_names_italic.update({k: value})
  233. # else:
  234. # self.ff_names_regular.update({k: value})
  235. # i += 1
  236. # except WindowsError:
  237. # pass
  238. # Font size
  239. self.font_size_cb = FCComboBox()
  240. self.font_size_cb.setEditable(True)
  241. self.font_size_cb.setMinimumContentsLength(3)
  242. self.font_size_cb.setMaximumWidth(70)
  243. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  244. '15', '16', '18', '20', '22', '24', '26', '28',
  245. '32', '36', '40', '44', '48', '54', '60', '66',
  246. '72', '80', '88', '96']
  247. for i in font_sizes:
  248. self.font_size_cb.addItem(i)
  249. self.font_size_cb.setCurrentIndex(4)
  250. hlay = QtWidgets.QHBoxLayout()
  251. hlay.addWidget(self.font_size_cb)
  252. hlay.addStretch()
  253. self.font_bold_tb = QtWidgets.QToolButton()
  254. self.font_bold_tb.setCheckable(True)
  255. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  256. hlay.addWidget(self.font_bold_tb)
  257. self.font_italic_tb = QtWidgets.QToolButton()
  258. self.font_italic_tb.setCheckable(True)
  259. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  260. hlay.addWidget(self.font_italic_tb)
  261. self.form_layout.addRow("Size:", hlay)
  262. # Text input
  263. self.text_input_entry = FCTextAreaRich()
  264. self.text_input_entry.setTabStopWidth(12)
  265. self.text_input_entry.setMinimumHeight(200)
  266. # self.text_input_entry.setMaximumHeight(150)
  267. self.text_input_entry.setCurrentFont(f_current)
  268. self.text_input_entry.setFontPointSize(10)
  269. self.form_layout.addRow("Text:", self.text_input_entry)
  270. # Buttons
  271. hlay1 = QtWidgets.QHBoxLayout()
  272. self.form_layout.addRow("", hlay1)
  273. hlay1.addStretch()
  274. self.apply_button = QtWidgets.QPushButton("Apply")
  275. hlay1.addWidget(self.apply_button)
  276. # self.layout.addStretch()
  277. # Signals
  278. self.apply_button.clicked.connect(self.on_apply_button)
  279. self.font_type_cb.currentFontChanged.connect(self.font_family)
  280. self.font_size_cb.activated.connect(self.font_size)
  281. self.font_bold_tb.clicked.connect(self.on_bold_button)
  282. self.font_italic_tb.clicked.connect(self.on_italic_button)
  283. def on_apply_button(self):
  284. font_to_geo_type = ""
  285. if self.font_bold is True:
  286. font_to_geo_type = 'bold'
  287. elif self.font_italic is True:
  288. font_to_geo_type = 'italic'
  289. elif self.font_bold is True and self.font_italic is True:
  290. font_to_geo_type = 'bi'
  291. elif self.font_bold is False and self.font_italic is False:
  292. font_to_geo_type = 'regular'
  293. string_to_geo = self.text_input_entry.get_value()
  294. font_to_geo_size = self.font_size_cb.get_value()
  295. self.text_path = self.f_parse.font_to_geometry(
  296. char_string=string_to_geo,
  297. font_name=self.font_name,
  298. font_size=font_to_geo_size,
  299. font_type=font_to_geo_type,
  300. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  301. def font_family(self, font):
  302. self.text_input_entry.selectAll()
  303. font.setPointSize(float(self.font_size_cb.get_value()))
  304. self.text_input_entry.setCurrentFont(font)
  305. self.font_name = self.font_type_cb.currentFont().family()
  306. def font_size(self):
  307. self.text_input_entry.selectAll()
  308. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  309. def on_bold_button(self):
  310. if self.font_bold_tb.isChecked():
  311. self.text_input_entry.selectAll()
  312. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  313. self.font_bold = True
  314. else:
  315. self.text_input_entry.selectAll()
  316. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  317. self.font_bold = False
  318. def on_italic_button(self):
  319. if self.font_italic_tb.isChecked():
  320. self.text_input_entry.selectAll()
  321. self.text_input_entry.setFontItalic(True)
  322. self.font_italic = True
  323. else:
  324. self.text_input_entry.selectAll()
  325. self.text_input_entry.setFontItalic(False)
  326. self.font_italic = False
  327. def hide_tool(self):
  328. self.text_tool_frame.hide()
  329. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  330. class PaintOptionsTool(FlatCAMTool):
  331. """
  332. Inputs to specify how to paint the selected polygons.
  333. """
  334. toolName = "Paint Tool"
  335. def __init__(self, app, fcdraw):
  336. FlatCAMTool.__init__(self, app)
  337. self.app = app
  338. self.fcdraw = fcdraw
  339. ## Title
  340. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  341. title_label.setStyleSheet("""
  342. QLabel
  343. {
  344. font-size: 16px;
  345. font-weight: bold;
  346. }
  347. """)
  348. self.layout.addWidget(title_label)
  349. grid = QtWidgets.QGridLayout()
  350. self.layout.addLayout(grid)
  351. # Tool dia
  352. ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
  353. ptdlabel.setToolTip(
  354. _( "Diameter of the tool to\n"
  355. "be used in the operation.")
  356. )
  357. grid.addWidget(ptdlabel, 0, 0)
  358. self.painttooldia_entry = FCEntry()
  359. grid.addWidget(self.painttooldia_entry, 0, 1)
  360. # Overlap
  361. ovlabel = QtWidgets.QLabel(_('Overlap:'))
  362. ovlabel.setToolTip(
  363. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  364. "Example:\n"
  365. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  366. "Adjust the value starting with lower values\n"
  367. "and increasing it if areas that should be painted are still \n"
  368. "not painted.\n"
  369. "Lower values = faster processing, faster execution on PCB.\n"
  370. "Higher values = slow processing and slow execution on CNC\n"
  371. "due of too many paths.")
  372. )
  373. grid.addWidget(ovlabel, 1, 0)
  374. self.paintoverlap_entry = FCEntry()
  375. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  376. grid.addWidget(self.paintoverlap_entry, 1, 1)
  377. # Margin
  378. marginlabel = QtWidgets.QLabel(_('Margin:'))
  379. marginlabel.setToolTip(
  380. _( "Distance by which to avoid\n"
  381. "the edges of the polygon to\n"
  382. "be painted.")
  383. )
  384. grid.addWidget(marginlabel, 2, 0)
  385. self.paintmargin_entry = FCEntry()
  386. grid.addWidget(self.paintmargin_entry, 2, 1)
  387. # Method
  388. methodlabel = QtWidgets.QLabel(_('Method:'))
  389. methodlabel.setToolTip(
  390. _("Algorithm to paint the polygon:<BR>"
  391. "<B>Standard</B>: Fixed step inwards.<BR>"
  392. "<B>Seed-based</B>: Outwards from seed.")
  393. )
  394. grid.addWidget(methodlabel, 3, 0)
  395. self.paintmethod_combo = RadioSet([
  396. {"label": _("Standard"), "value": "standard"},
  397. {"label": _("Seed-based"), "value": "seed"},
  398. {"label": _("Straight lines"), "value": "lines"}
  399. ], orientation='vertical', stretch=False)
  400. grid.addWidget(self.paintmethod_combo, 3, 1)
  401. # Connect lines
  402. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  403. pathconnectlabel.setToolTip(
  404. _( "Draw lines between resulting\n"
  405. "segments to minimize tool lifts.")
  406. )
  407. grid.addWidget(pathconnectlabel, 4, 0)
  408. self.pathconnect_cb = FCCheckBox()
  409. grid.addWidget(self.pathconnect_cb, 4, 1)
  410. contourlabel = QtWidgets.QLabel(_("Contour:"))
  411. contourlabel.setToolTip(
  412. _("Cut around the perimeter of the polygon\n"
  413. "to trim rough edges.")
  414. )
  415. grid.addWidget(contourlabel, 5, 0)
  416. self.paintcontour_cb = FCCheckBox()
  417. grid.addWidget(self.paintcontour_cb, 5, 1)
  418. ## Buttons
  419. hlay = QtWidgets.QHBoxLayout()
  420. self.layout.addLayout(hlay)
  421. hlay.addStretch()
  422. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  423. hlay.addWidget(self.paint_button)
  424. self.layout.addStretch()
  425. ## Signals
  426. self.paint_button.clicked.connect(self.on_paint)
  427. self.set_tool_ui()
  428. def run(self):
  429. self.app.report_usage("Geo Editor ToolPaint()")
  430. FlatCAMTool.run(self)
  431. # if the splitter us hidden, display it
  432. if self.app.ui.splitter.sizes()[0] == 0:
  433. self.app.ui.splitter.setSizes([1, 1])
  434. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  435. def set_tool_ui(self):
  436. ## Init GUI
  437. if self.app.defaults["tools_painttooldia"]:
  438. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  439. else:
  440. self.painttooldia_entry.set_value(0.0)
  441. if self.app.defaults["tools_paintoverlap"]:
  442. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  443. else:
  444. self.paintoverlap_entry.set_value(0.0)
  445. if self.app.defaults["tools_paintmargin"]:
  446. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  447. else:
  448. self.paintmargin_entry.set_value(0.0)
  449. if self.app.defaults["tools_paintmethod"]:
  450. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  451. else:
  452. self.paintmethod_combo.set_value("seed")
  453. if self.app.defaults["tools_pathconnect"]:
  454. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  455. else:
  456. self.pathconnect_cb.set_value(False)
  457. if self.app.defaults["tools_paintcontour"]:
  458. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  459. else:
  460. self.paintcontour_cb.set_value(False)
  461. def on_paint(self):
  462. if not self.fcdraw.selected:
  463. self.app.inform.emit(_("[WARNING_NOTCL] Paint cancelled. No shape selected."))
  464. return
  465. try:
  466. tooldia = float(self.painttooldia_entry.get_value())
  467. except ValueError:
  468. # try to convert comma to decimal point. if it's still not working error message and return
  469. try:
  470. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  471. self.painttooldia_entry.set_value(tooldia)
  472. except ValueError:
  473. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  474. "Add it and retry."))
  475. return
  476. try:
  477. overlap = float(self.paintoverlap_entry.get_value())
  478. except ValueError:
  479. # try to convert comma to decimal point. if it's still not working error message and return
  480. try:
  481. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  482. self.paintoverlap_entry.set_value(overlap)
  483. except ValueError:
  484. self.app.inform.emit(_("[WARNING_NOTCL] Overlap value is missing or wrong format. "
  485. "Add it and retry."))
  486. return
  487. try:
  488. margin = float(self.paintmargin_entry.get_value())
  489. except ValueError:
  490. # try to convert comma to decimal point. if it's still not working error message and return
  491. try:
  492. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  493. self.paintmargin_entry.set_value(margin)
  494. except ValueError:
  495. self.app.inform.emit(_("[WARNING_NOTCL] Margin distance value is missing or wrong format. "
  496. "Add it and retry."))
  497. return
  498. method = self.paintmethod_combo.get_value()
  499. contour = self.paintcontour_cb.get_value()
  500. connect = self.pathconnect_cb.get_value()
  501. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  502. self.fcdraw.select_tool("select")
  503. self.app.ui.notebook.setTabText(2, _("Tools"))
  504. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  505. self.app.ui.splitter.setSizes([0, 1])
  506. class TransformEditorTool(FlatCAMTool):
  507. """
  508. Inputs to specify how to paint the selected polygons.
  509. """
  510. toolName = _("Transform Tool")
  511. rotateName = _("Rotate")
  512. skewName = _("Skew/Shear")
  513. scaleName = _("Scale")
  514. flipName = _("Mirror (Flip)")
  515. offsetName = _("Offset")
  516. def __init__(self, app, draw_app):
  517. FlatCAMTool.__init__(self, app)
  518. self.app = app
  519. self.draw_app = draw_app
  520. self.transform_lay = QtWidgets.QVBoxLayout()
  521. self.layout.addLayout(self.transform_lay)
  522. ## Title
  523. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  524. title_label.setStyleSheet("""
  525. QLabel
  526. {
  527. font-size: 16px;
  528. font-weight: bold;
  529. }
  530. """)
  531. self.transform_lay.addWidget(title_label)
  532. self.empty_label = QtWidgets.QLabel("")
  533. self.empty_label.setFixedWidth(50)
  534. self.empty_label1 = QtWidgets.QLabel("")
  535. self.empty_label1.setFixedWidth(70)
  536. self.empty_label2 = QtWidgets.QLabel("")
  537. self.empty_label2.setFixedWidth(70)
  538. self.empty_label3 = QtWidgets.QLabel("")
  539. self.empty_label3.setFixedWidth(70)
  540. self.empty_label4 = QtWidgets.QLabel("")
  541. self.empty_label4.setFixedWidth(70)
  542. self.transform_lay.addWidget(self.empty_label)
  543. ## Rotate Title
  544. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  545. self.transform_lay.addWidget(rotate_title_label)
  546. ## Layout
  547. form_layout = QtWidgets.QFormLayout()
  548. self.transform_lay.addLayout(form_layout)
  549. form_child = QtWidgets.QHBoxLayout()
  550. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  551. self.rotate_label.setToolTip(
  552. _( "Angle for Rotation action, in degrees.\n"
  553. "Float number between -360 and 359.\n"
  554. "Positive numbers for CW motion.\n"
  555. "Negative numbers for CCW motion.")
  556. )
  557. self.rotate_label.setFixedWidth(50)
  558. self.rotate_entry = FCEntry()
  559. # self.rotate_entry.setFixedWidth(60)
  560. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  561. self.rotate_button = FCButton()
  562. self.rotate_button.set_value(_("Rotate"))
  563. self.rotate_button.setToolTip(
  564. _("Rotate the selected shape(s).\n"
  565. "The point of reference is the middle of\n"
  566. "the bounding box for all selected shapes.")
  567. )
  568. self.rotate_button.setFixedWidth(60)
  569. form_child.addWidget(self.rotate_entry)
  570. form_child.addWidget(self.rotate_button)
  571. form_layout.addRow(self.rotate_label, form_child)
  572. self.transform_lay.addWidget(self.empty_label1)
  573. ## Skew Title
  574. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  575. self.transform_lay.addWidget(skew_title_label)
  576. ## Form Layout
  577. form1_layout = QtWidgets.QFormLayout()
  578. self.transform_lay.addLayout(form1_layout)
  579. form1_child_1 = QtWidgets.QHBoxLayout()
  580. form1_child_2 = QtWidgets.QHBoxLayout()
  581. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  582. self.skewx_label.setToolTip(
  583. _( "Angle for Skew action, in degrees.\n"
  584. "Float number between -360 and 359.")
  585. )
  586. self.skewx_label.setFixedWidth(50)
  587. self.skewx_entry = FCEntry()
  588. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  589. # self.skewx_entry.setFixedWidth(60)
  590. self.skewx_button = FCButton()
  591. self.skewx_button.set_value(_("Skew X"))
  592. self.skewx_button.setToolTip(
  593. _( "Skew/shear the selected shape(s).\n"
  594. "The point of reference is the middle of\n"
  595. "the bounding box for all selected shapes."))
  596. self.skewx_button.setFixedWidth(60)
  597. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  598. self.skewy_label.setToolTip(
  599. _( "Angle for Skew action, in degrees.\n"
  600. "Float number between -360 and 359.")
  601. )
  602. self.skewy_label.setFixedWidth(50)
  603. self.skewy_entry = FCEntry()
  604. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  605. # self.skewy_entry.setFixedWidth(60)
  606. self.skewy_button = FCButton()
  607. self.skewy_button.set_value(_("Skew Y"))
  608. self.skewy_button.setToolTip(
  609. _("Skew/shear the selected shape(s).\n"
  610. "The point of reference is the middle of\n"
  611. "the bounding box for all selected shapes."))
  612. self.skewy_button.setFixedWidth(60)
  613. form1_child_1.addWidget(self.skewx_entry)
  614. form1_child_1.addWidget(self.skewx_button)
  615. form1_child_2.addWidget(self.skewy_entry)
  616. form1_child_2.addWidget(self.skewy_button)
  617. form1_layout.addRow(self.skewx_label, form1_child_1)
  618. form1_layout.addRow(self.skewy_label, form1_child_2)
  619. self.transform_lay.addWidget(self.empty_label2)
  620. ## Scale Title
  621. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  622. self.transform_lay.addWidget(scale_title_label)
  623. ## Form Layout
  624. form2_layout = QtWidgets.QFormLayout()
  625. self.transform_lay.addLayout(form2_layout)
  626. form2_child_1 = QtWidgets.QHBoxLayout()
  627. form2_child_2 = QtWidgets.QHBoxLayout()
  628. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  629. self.scalex_label.setToolTip(
  630. _("Factor for Scale action over X axis.")
  631. )
  632. self.scalex_label.setFixedWidth(50)
  633. self.scalex_entry = FCEntry()
  634. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  635. # self.scalex_entry.setFixedWidth(60)
  636. self.scalex_button = FCButton()
  637. self.scalex_button.set_value(_("Scale X"))
  638. self.scalex_button.setToolTip(
  639. _( "Scale the selected shape(s).\n"
  640. "The point of reference depends on \n"
  641. "the Scale reference checkbox state."))
  642. self.scalex_button.setFixedWidth(60)
  643. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  644. self.scaley_label.setToolTip(
  645. _("Factor for Scale action over Y axis.")
  646. )
  647. self.scaley_label.setFixedWidth(50)
  648. self.scaley_entry = FCEntry()
  649. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  650. # self.scaley_entry.setFixedWidth(60)
  651. self.scaley_button = FCButton()
  652. self.scaley_button.set_value(_("Scale Y"))
  653. self.scaley_button.setToolTip(
  654. _( "Scale the selected shape(s).\n"
  655. "The point of reference depends on \n"
  656. "the Scale reference checkbox state."))
  657. self.scaley_button.setFixedWidth(60)
  658. self.scale_link_cb = FCCheckBox()
  659. self.scale_link_cb.set_value(True)
  660. self.scale_link_cb.setText(_("Link"))
  661. self.scale_link_cb.setToolTip(
  662. _("Scale the selected shape(s)\n"
  663. "using the Scale Factor X for both axis."))
  664. self.scale_link_cb.setFixedWidth(50)
  665. self.scale_zero_ref_cb = FCCheckBox()
  666. self.scale_zero_ref_cb.set_value(True)
  667. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  668. self.scale_zero_ref_cb.setToolTip(
  669. _("Scale the selected shape(s)\n"
  670. "using the origin reference when checked,\n"
  671. "and the center of the biggest bounding box\n"
  672. "of the selected shapes when unchecked."))
  673. form2_child_1.addWidget(self.scalex_entry)
  674. form2_child_1.addWidget(self.scalex_button)
  675. form2_child_2.addWidget(self.scaley_entry)
  676. form2_child_2.addWidget(self.scaley_button)
  677. form2_layout.addRow(self.scalex_label, form2_child_1)
  678. form2_layout.addRow(self.scaley_label, form2_child_2)
  679. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  680. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  681. self.transform_lay.addWidget(self.empty_label3)
  682. ## Offset Title
  683. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  684. self.transform_lay.addWidget(offset_title_label)
  685. ## Form Layout
  686. form3_layout = QtWidgets.QFormLayout()
  687. self.transform_lay.addLayout(form3_layout)
  688. form3_child_1 = QtWidgets.QHBoxLayout()
  689. form3_child_2 = QtWidgets.QHBoxLayout()
  690. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  691. self.offx_label.setToolTip(
  692. _("Value for Offset action on X axis.")
  693. )
  694. self.offx_label.setFixedWidth(50)
  695. self.offx_entry = FCEntry()
  696. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  697. # self.offx_entry.setFixedWidth(60)
  698. self.offx_button = FCButton()
  699. self.offx_button.set_value(_("Offset X"))
  700. self.offx_button.setToolTip(
  701. _( "Offset the selected shape(s).\n"
  702. "The point of reference is the middle of\n"
  703. "the bounding box for all selected shapes.\n")
  704. )
  705. self.offx_button.setFixedWidth(60)
  706. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  707. self.offy_label.setToolTip(
  708. _("Value for Offset action on Y axis.")
  709. )
  710. self.offy_label.setFixedWidth(50)
  711. self.offy_entry = FCEntry()
  712. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  713. # self.offy_entry.setFixedWidth(60)
  714. self.offy_button = FCButton()
  715. self.offy_button.set_value(_("Offset Y"))
  716. self.offy_button.setToolTip(
  717. _("Offset the selected shape(s).\n"
  718. "The point of reference is the middle of\n"
  719. "the bounding box for all selected shapes.\n")
  720. )
  721. self.offy_button.setFixedWidth(60)
  722. form3_child_1.addWidget(self.offx_entry)
  723. form3_child_1.addWidget(self.offx_button)
  724. form3_child_2.addWidget(self.offy_entry)
  725. form3_child_2.addWidget(self.offy_button)
  726. form3_layout.addRow(self.offx_label, form3_child_1)
  727. form3_layout.addRow(self.offy_label, form3_child_2)
  728. self.transform_lay.addWidget(self.empty_label4)
  729. ## Flip Title
  730. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  731. self.transform_lay.addWidget(flip_title_label)
  732. ## Form Layout
  733. form4_layout = QtWidgets.QFormLayout()
  734. form4_child_hlay = QtWidgets.QHBoxLayout()
  735. self.transform_lay.addLayout(form4_child_hlay)
  736. self.transform_lay.addLayout(form4_layout)
  737. form4_child_1 = QtWidgets.QHBoxLayout()
  738. self.flipx_button = FCButton()
  739. self.flipx_button.set_value(_("Flip on X"))
  740. self.flipx_button.setToolTip(
  741. _("Flip the selected shape(s) over the X axis.\n"
  742. "Does not create a new shape.")
  743. )
  744. self.flipx_button.setFixedWidth(60)
  745. self.flipy_button = FCButton()
  746. self.flipy_button.set_value(_("Flip on Y"))
  747. self.flipy_button.setToolTip(
  748. _("Flip the selected shape(s) over the X axis.\n"
  749. "Does not create a new shape.")
  750. )
  751. self.flipy_button.setFixedWidth(60)
  752. self.flip_ref_cb = FCCheckBox()
  753. self.flip_ref_cb.set_value(True)
  754. self.flip_ref_cb.setText(_("Ref Pt"))
  755. self.flip_ref_cb.setToolTip(
  756. _("Flip the selected shape(s)\n"
  757. "around the point in Point Entry Field.\n"
  758. "\n"
  759. "The point coordinates can be captured by\n"
  760. "left click on canvas together with pressing\n"
  761. "SHIFT key. \n"
  762. "Then click Add button to insert coordinates.\n"
  763. "Or enter the coords in format (x, y) in the\n"
  764. "Point Entry field and click Flip on X(Y)")
  765. )
  766. self.flip_ref_cb.setFixedWidth(50)
  767. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  768. self.flip_ref_label.setToolTip(
  769. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  770. "The 'x' in (x, y) will be used when using Flip on X and\n"
  771. "the 'y' in (x, y) will be used when using Flip on Y.")
  772. )
  773. self.flip_ref_label.setFixedWidth(50)
  774. self.flip_ref_entry = EvalEntry2("(0, 0)")
  775. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  776. # self.flip_ref_entry.setFixedWidth(60)
  777. self.flip_ref_button = FCButton()
  778. self.flip_ref_button.set_value(_("Add"))
  779. self.flip_ref_button.setToolTip(
  780. _( "The point coordinates can be captured by\n"
  781. "left click on canvas together with pressing\n"
  782. "SHIFT key. Then click Add button to insert.")
  783. )
  784. self.flip_ref_button.setFixedWidth(60)
  785. form4_child_hlay.addStretch()
  786. form4_child_hlay.addWidget(self.flipx_button)
  787. form4_child_hlay.addWidget(self.flipy_button)
  788. form4_child_1.addWidget(self.flip_ref_entry)
  789. form4_child_1.addWidget(self.flip_ref_button)
  790. form4_layout.addRow(self.flip_ref_cb)
  791. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  792. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  793. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  794. self.transform_lay.addStretch()
  795. ## Signals
  796. self.rotate_button.clicked.connect(self.on_rotate)
  797. self.skewx_button.clicked.connect(self.on_skewx)
  798. self.skewy_button.clicked.connect(self.on_skewy)
  799. self.scalex_button.clicked.connect(self.on_scalex)
  800. self.scaley_button.clicked.connect(self.on_scaley)
  801. self.offx_button.clicked.connect(self.on_offx)
  802. self.offy_button.clicked.connect(self.on_offy)
  803. self.flipx_button.clicked.connect(self.on_flipx)
  804. self.flipy_button.clicked.connect(self.on_flipy)
  805. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  806. self.rotate_entry.returnPressed.connect(self.on_rotate)
  807. self.skewx_entry.returnPressed.connect(self.on_skewx)
  808. self.skewy_entry.returnPressed.connect(self.on_skewy)
  809. self.scalex_entry.returnPressed.connect(self.on_scalex)
  810. self.scaley_entry.returnPressed.connect(self.on_scaley)
  811. self.offx_entry.returnPressed.connect(self.on_offx)
  812. self.offy_entry.returnPressed.connect(self.on_offy)
  813. self.set_tool_ui()
  814. def run(self):
  815. self.app.report_usage("Geo Editor Transform Tool()")
  816. FlatCAMTool.run(self)
  817. self.set_tool_ui()
  818. # if the splitter us hidden, display it
  819. if self.app.ui.splitter.sizes()[0] == 0:
  820. self.app.ui.splitter.setSizes([1, 1])
  821. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  822. def install(self, icon=None, separator=None, **kwargs):
  823. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  824. def set_tool_ui(self):
  825. ## Initialize form
  826. if self.app.defaults["tools_transform_rotate"]:
  827. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  828. else:
  829. self.rotate_entry.set_value(0.0)
  830. if self.app.defaults["tools_transform_skew_x"]:
  831. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  832. else:
  833. self.skewx_entry.set_value(0.0)
  834. if self.app.defaults["tools_transform_skew_y"]:
  835. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  836. else:
  837. self.skewy_entry.set_value(0.0)
  838. if self.app.defaults["tools_transform_scale_x"]:
  839. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  840. else:
  841. self.scalex_entry.set_value(1.0)
  842. if self.app.defaults["tools_transform_scale_y"]:
  843. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  844. else:
  845. self.scaley_entry.set_value(1.0)
  846. if self.app.defaults["tools_transform_scale_link"]:
  847. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  848. else:
  849. self.scale_link_cb.set_value(True)
  850. if self.app.defaults["tools_transform_scale_reference"]:
  851. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  852. else:
  853. self.scale_zero_ref_cb.set_value(True)
  854. if self.app.defaults["tools_transform_offset_x"]:
  855. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  856. else:
  857. self.offx_entry.set_value(0.0)
  858. if self.app.defaults["tools_transform_offset_y"]:
  859. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  860. else:
  861. self.offy_entry.set_value(0.0)
  862. if self.app.defaults["tools_transform_mirror_reference"]:
  863. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  864. else:
  865. self.flip_ref_cb.set_value(False)
  866. if self.app.defaults["tools_transform_mirror_point"]:
  867. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  868. else:
  869. self.flip_ref_entry.set_value((0, 0))
  870. def template(self):
  871. if not self.fcdraw.selected:
  872. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  873. return
  874. self.draw_app.select_tool("select")
  875. self.app.ui.notebook.setTabText(2, "Tools")
  876. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  877. self.app.ui.splitter.setSizes([0, 1])
  878. def on_rotate(self, sig=None, val=None):
  879. if val:
  880. value = val
  881. else:
  882. try:
  883. value = float(self.rotate_entry.get_value())
  884. except ValueError:
  885. # try to convert comma to decimal point. if it's still not working error message and return
  886. try:
  887. value = float(self.rotate_entry.get_value().replace(',', '.'))
  888. except ValueError:
  889. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Rotate, "
  890. "use a number."))
  891. return
  892. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  893. 'params': [value]})
  894. # self.on_rotate_action(value)
  895. return
  896. def on_flipx(self):
  897. # self.on_flip("Y")
  898. axis = 'Y'
  899. self.app.worker_task.emit({'fcn': self.on_flip,
  900. 'params': [axis]})
  901. return
  902. def on_flipy(self):
  903. # self.on_flip("X")
  904. axis = 'X'
  905. self.app.worker_task.emit({'fcn': self.on_flip,
  906. 'params': [axis]})
  907. return
  908. def on_flip_add_coords(self):
  909. val = self.app.clipboard.text()
  910. self.flip_ref_entry.set_value(val)
  911. def on_skewx(self, sig=None, val=None):
  912. if val:
  913. value = val
  914. else:
  915. try:
  916. value = float(self.skewx_entry.get_value())
  917. except ValueError:
  918. # try to convert comma to decimal point. if it's still not working error message and return
  919. try:
  920. value = float(self.skewx_entry.get_value().replace(',', '.'))
  921. except ValueError:
  922. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew X, "
  923. "use a number."))
  924. return
  925. # self.on_skew("X", value)
  926. axis = 'X'
  927. self.app.worker_task.emit({'fcn': self.on_skew,
  928. 'params': [axis, value]})
  929. return
  930. def on_skewy(self, sig=None, val=None):
  931. if val:
  932. value = val
  933. else:
  934. try:
  935. value = float(self.skewy_entry.get_value())
  936. except ValueError:
  937. # try to convert comma to decimal point. if it's still not working error message and return
  938. try:
  939. value = float(self.skewy_entry.get_value().replace(',', '.'))
  940. except ValueError:
  941. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew Y, "
  942. "use a number."))
  943. return
  944. # self.on_skew("Y", value)
  945. axis = 'Y'
  946. self.app.worker_task.emit({'fcn': self.on_skew,
  947. 'params': [axis, value]})
  948. return
  949. def on_scalex(self, sig=None, val=None):
  950. if val:
  951. xvalue = val
  952. else:
  953. try:
  954. xvalue = float(self.scalex_entry.get_value())
  955. except ValueError:
  956. # try to convert comma to decimal point. if it's still not working error message and return
  957. try:
  958. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  959. except ValueError:
  960. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale X, "
  961. "use a number."))
  962. return
  963. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  964. if xvalue == 0:
  965. xvalue = 1
  966. if self.scale_link_cb.get_value():
  967. yvalue = xvalue
  968. else:
  969. yvalue = 1
  970. axis = 'X'
  971. point = (0, 0)
  972. if self.scale_zero_ref_cb.get_value():
  973. self.app.worker_task.emit({'fcn': self.on_scale,
  974. 'params': [axis, xvalue, yvalue, point]})
  975. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  976. else:
  977. # self.on_scale("X", xvalue, yvalue)
  978. self.app.worker_task.emit({'fcn': self.on_scale,
  979. 'params': [axis, xvalue, yvalue]})
  980. return
  981. def on_scaley(self, sig=None, val=None):
  982. xvalue = 1
  983. if val:
  984. yvalue = val
  985. else:
  986. try:
  987. yvalue = float(self.scaley_entry.get_value())
  988. except ValueError:
  989. # try to convert comma to decimal point. if it's still not working error message and return
  990. try:
  991. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  992. except ValueError:
  993. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale Y, "
  994. "use a number."))
  995. return
  996. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  997. if yvalue == 0:
  998. yvalue = 1
  999. axis = 'Y'
  1000. point = (0, 0)
  1001. if self.scale_zero_ref_cb.get_value():
  1002. self.app.worker_task.emit({'fcn': self.on_scale,
  1003. 'params': [axis, xvalue, yvalue, point]})
  1004. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1005. else:
  1006. # self.on_scale("Y", xvalue, yvalue)
  1007. self.app.worker_task.emit({'fcn': self.on_scale,
  1008. 'params': [axis, xvalue, yvalue]})
  1009. return
  1010. def on_offx(self, sig=None, val=None):
  1011. if val:
  1012. value = val
  1013. else:
  1014. try:
  1015. value = float(self.offx_entry.get_value())
  1016. except ValueError:
  1017. # try to convert comma to decimal point. if it's still not working error message and return
  1018. try:
  1019. value = float(self.offx_entry.get_value().replace(',', '.'))
  1020. except ValueError:
  1021. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset X, "
  1022. "use a number."))
  1023. return
  1024. # self.on_offset("X", value)
  1025. axis = 'X'
  1026. self.app.worker_task.emit({'fcn': self.on_offset,
  1027. 'params': [axis, value]})
  1028. return
  1029. def on_offy(self, sig=None, val=None):
  1030. if val:
  1031. value = val
  1032. else:
  1033. try:
  1034. value = float(self.offy_entry.get_value())
  1035. except ValueError:
  1036. # try to convert comma to decimal point. if it's still not working error message and return
  1037. try:
  1038. value = float(self.offy_entry.get_value().replace(',', '.'))
  1039. except ValueError:
  1040. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset Y, "
  1041. "use a number."))
  1042. return
  1043. # self.on_offset("Y", value)
  1044. axis = 'Y'
  1045. self.app.worker_task.emit({'fcn': self.on_offset,
  1046. 'params': [axis, value]})
  1047. return
  1048. def on_rotate_action(self, num):
  1049. shape_list = self.draw_app.selected
  1050. xminlist = []
  1051. yminlist = []
  1052. xmaxlist = []
  1053. ymaxlist = []
  1054. if not shape_list:
  1055. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  1056. return
  1057. else:
  1058. with self.app.proc_container.new(_("Appying Rotate")):
  1059. try:
  1060. # first get a bounding box to fit all
  1061. for sha in shape_list:
  1062. xmin, ymin, xmax, ymax = sha.bounds()
  1063. xminlist.append(xmin)
  1064. yminlist.append(ymin)
  1065. xmaxlist.append(xmax)
  1066. ymaxlist.append(ymax)
  1067. # get the minimum x,y and maximum x,y for all objects selected
  1068. xminimal = min(xminlist)
  1069. yminimal = min(yminlist)
  1070. xmaximal = max(xmaxlist)
  1071. ymaximal = max(ymaxlist)
  1072. self.app.progress.emit(20)
  1073. for sel_sha in shape_list:
  1074. px = 0.5 * (xminimal + xmaximal)
  1075. py = 0.5 * (yminimal + ymaximal)
  1076. sel_sha.rotate(-num, point=(px, py))
  1077. self.draw_app.replot()
  1078. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1079. # self.draw_app.transform_complete.emit()
  1080. self.app.inform.emit(_("[success] Done. Rotate completed."))
  1081. self.app.progress.emit(100)
  1082. except Exception as e:
  1083. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  1084. return
  1085. def on_flip(self, axis):
  1086. shape_list = self.draw_app.selected
  1087. xminlist = []
  1088. yminlist = []
  1089. xmaxlist = []
  1090. ymaxlist = []
  1091. if not shape_list:
  1092. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  1093. return
  1094. else:
  1095. with self.app.proc_container.new(_("Applying Flip")):
  1096. try:
  1097. # get mirroring coords from the point entry
  1098. if self.flip_ref_cb.isChecked():
  1099. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1100. # get mirroing coords from the center of an all-enclosing bounding box
  1101. else:
  1102. # first get a bounding box to fit all
  1103. for sha in shape_list:
  1104. xmin, ymin, xmax, ymax = sha.bounds()
  1105. xminlist.append(xmin)
  1106. yminlist.append(ymin)
  1107. xmaxlist.append(xmax)
  1108. ymaxlist.append(ymax)
  1109. # get the minimum x,y and maximum x,y for all objects selected
  1110. xminimal = min(xminlist)
  1111. yminimal = min(yminlist)
  1112. xmaximal = max(xmaxlist)
  1113. ymaximal = max(ymaxlist)
  1114. px = 0.5 * (xminimal + xmaximal)
  1115. py = 0.5 * (yminimal + ymaximal)
  1116. self.app.progress.emit(20)
  1117. # execute mirroring
  1118. for sha in shape_list:
  1119. if axis is 'X':
  1120. sha.mirror('X', (px, py))
  1121. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  1122. elif axis is 'Y':
  1123. sha.mirror('Y', (px, py))
  1124. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  1125. self.draw_app.replot()
  1126. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1127. #
  1128. # self.draw_app.transform_complete.emit()
  1129. self.app.progress.emit(100)
  1130. except Exception as e:
  1131. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  1132. return
  1133. def on_skew(self, axis, num):
  1134. shape_list = self.draw_app.selected
  1135. xminlist = []
  1136. yminlist = []
  1137. if not shape_list:
  1138. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  1139. return
  1140. else:
  1141. with self.app.proc_container.new(_("Applying Skew")):
  1142. try:
  1143. # first get a bounding box to fit all
  1144. for sha in shape_list:
  1145. xmin, ymin, xmax, ymax = sha.bounds()
  1146. xminlist.append(xmin)
  1147. yminlist.append(ymin)
  1148. # get the minimum x,y and maximum x,y for all objects selected
  1149. xminimal = min(xminlist)
  1150. yminimal = min(yminlist)
  1151. self.app.progress.emit(20)
  1152. for sha in shape_list:
  1153. if axis is 'X':
  1154. sha.skew(num, 0, point=(xminimal, yminimal))
  1155. elif axis is 'Y':
  1156. sha.skew(0, num, point=(xminimal, yminimal))
  1157. self.draw_app.replot()
  1158. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1159. #
  1160. # self.draw_app.transform_complete.emit()
  1161. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  1162. self.app.progress.emit(100)
  1163. except Exception as e:
  1164. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  1165. return
  1166. def on_scale(self, axis, xfactor, yfactor, point=None):
  1167. shape_list = self.draw_app.selected
  1168. xminlist = []
  1169. yminlist = []
  1170. xmaxlist = []
  1171. ymaxlist = []
  1172. if not shape_list:
  1173. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  1174. return
  1175. else:
  1176. with self.app.proc_container.new(_("Applying Scale")):
  1177. try:
  1178. # first get a bounding box to fit all
  1179. for sha in shape_list:
  1180. xmin, ymin, xmax, ymax = sha.bounds()
  1181. xminlist.append(xmin)
  1182. yminlist.append(ymin)
  1183. xmaxlist.append(xmax)
  1184. ymaxlist.append(ymax)
  1185. # get the minimum x,y and maximum x,y for all objects selected
  1186. xminimal = min(xminlist)
  1187. yminimal = min(yminlist)
  1188. xmaximal = max(xmaxlist)
  1189. ymaximal = max(ymaxlist)
  1190. self.app.progress.emit(20)
  1191. if point is None:
  1192. px = 0.5 * (xminimal + xmaximal)
  1193. py = 0.5 * (yminimal + ymaximal)
  1194. else:
  1195. px = 0
  1196. py = 0
  1197. for sha in shape_list:
  1198. sha.scale(xfactor, yfactor, point=(px, py))
  1199. self.draw_app.replot()
  1200. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1201. #
  1202. # self.draw_app.transform_complete.emit()
  1203. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  1204. self.app.progress.emit(100)
  1205. except Exception as e:
  1206. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  1207. return
  1208. def on_offset(self, axis, num):
  1209. shape_list = self.draw_app.selected
  1210. xminlist = []
  1211. yminlist = []
  1212. if not shape_list:
  1213. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  1214. return
  1215. else:
  1216. with self.app.proc_container.new(_("Applying Offset")):
  1217. try:
  1218. # first get a bounding box to fit all
  1219. for sha in shape_list:
  1220. xmin, ymin, xmax, ymax = sha.bounds()
  1221. xminlist.append(xmin)
  1222. yminlist.append(ymin)
  1223. # get the minimum x,y and maximum x,y for all objects selected
  1224. xminimal = min(xminlist)
  1225. yminimal = min(yminlist)
  1226. self.app.progress.emit(20)
  1227. for sha in shape_list:
  1228. if axis is 'X':
  1229. sha.offset((num, 0))
  1230. elif axis is 'Y':
  1231. sha.offset((0, num))
  1232. self.draw_app.replot()
  1233. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1234. #
  1235. # self.draw_app.transform_complete.emit()
  1236. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  1237. self.app.progress.emit(100)
  1238. except Exception as e:
  1239. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  1240. return
  1241. def on_rotate_key(self):
  1242. val_box = FCInputDialog(title=_("Rotate ..."),
  1243. text=_('Enter an Angle Value (degrees):'),
  1244. min=-359.9999, max=360.0000, decimals=4,
  1245. init_val=float(self.app.defaults['tools_transform_rotate']))
  1246. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1247. val, ok = val_box.get_value()
  1248. if ok:
  1249. self.on_rotate(val=val)
  1250. self.app.inform.emit(
  1251. _("[success] Geometry shape rotate done...")
  1252. )
  1253. return
  1254. else:
  1255. self.app.inform.emit(
  1256. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  1257. )
  1258. def on_offx_key(self):
  1259. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1260. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1261. text=(_('Enter a distance Value (%s):') % str(units)),
  1262. min=-9999.9999, max=10000.0000, decimals=4,
  1263. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1264. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1265. val, ok = val_box.get_value()
  1266. if ok:
  1267. self.on_offx(val=val)
  1268. self.app.inform.emit(
  1269. _("[success] Geometry shape offset on X axis done..."))
  1270. return
  1271. else:
  1272. self.app.inform.emit(
  1273. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  1274. def on_offy_key(self):
  1275. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1276. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1277. text=(_('Enter a distance Value (%s):') % str(units)),
  1278. min=-9999.9999, max=10000.0000, decimals=4,
  1279. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1280. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1281. val, ok = val_box.get_value()
  1282. if ok:
  1283. self.on_offx(val=val)
  1284. self.app.inform.emit(
  1285. _("[success] Geometry shape offset on Y axis done..."))
  1286. return
  1287. else:
  1288. self.app.inform.emit(
  1289. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  1290. def on_skewx_key(self):
  1291. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1292. text=_('Enter an Angle Value (degrees):'),
  1293. min=-359.9999, max=360.0000, decimals=4,
  1294. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1295. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1296. val, ok = val_box.get_value()
  1297. if ok:
  1298. self.on_skewx(val=val)
  1299. self.app.inform.emit(
  1300. _("[success] Geometry shape skew on X axis done..."))
  1301. return
  1302. else:
  1303. self.app.inform.emit(
  1304. _( "[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  1305. def on_skewy_key(self):
  1306. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1307. text=_('Enter an Angle Value (degrees):'),
  1308. min=-359.9999, max=360.0000, decimals=4,
  1309. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1310. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1311. val, ok = val_box.get_value()
  1312. if ok:
  1313. self.on_skewx(val=val)
  1314. self.app.inform.emit(
  1315. _( "[success] Geometry shape skew on Y axis done..."))
  1316. return
  1317. else:
  1318. self.app.inform.emit(
  1319. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))
  1320. class DrawToolShape(object):
  1321. """
  1322. Encapsulates "shapes" under a common class.
  1323. """
  1324. tolerance = None
  1325. @staticmethod
  1326. def get_pts(o):
  1327. """
  1328. Returns a list of all points in the object, where
  1329. the object can be a Polygon, Not a polygon, or a list
  1330. of such. Search is done recursively.
  1331. :param: geometric object
  1332. :return: List of points
  1333. :rtype: list
  1334. """
  1335. pts = []
  1336. ## Iterable: descend into each item.
  1337. try:
  1338. for subo in o:
  1339. pts += DrawToolShape.get_pts(subo)
  1340. ## Non-iterable
  1341. except TypeError:
  1342. if o is not None:
  1343. ## DrawToolShape: descend into .geo.
  1344. if isinstance(o, DrawToolShape):
  1345. pts += DrawToolShape.get_pts(o.geo)
  1346. ## Descend into .exerior and .interiors
  1347. elif type(o) == Polygon:
  1348. pts += DrawToolShape.get_pts(o.exterior)
  1349. for i in o.interiors:
  1350. pts += DrawToolShape.get_pts(i)
  1351. elif type(o) == MultiLineString:
  1352. for line in o:
  1353. pts += DrawToolShape.get_pts(line)
  1354. ## Has .coords: list them.
  1355. else:
  1356. if DrawToolShape.tolerance is not None:
  1357. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1358. else:
  1359. pts += list(o.coords)
  1360. else:
  1361. return
  1362. return pts
  1363. def __init__(self, geo=[]):
  1364. # Shapely type or list of such
  1365. self.geo = geo
  1366. self.utility = False
  1367. def get_all_points(self):
  1368. return DrawToolShape.get_pts(self)
  1369. def bounds(self):
  1370. """
  1371. Returns coordinates of rectangular bounds
  1372. of geometry: (xmin, ymin, xmax, ymax).
  1373. """
  1374. # fixed issue of getting bounds only for one level lists of objects
  1375. # now it can get bounds for nested lists of objects
  1376. def bounds_rec(shape):
  1377. if type(shape) is list:
  1378. minx = Inf
  1379. miny = Inf
  1380. maxx = -Inf
  1381. maxy = -Inf
  1382. for k in shape:
  1383. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1384. minx = min(minx, minx_)
  1385. miny = min(miny, miny_)
  1386. maxx = max(maxx, maxx_)
  1387. maxy = max(maxy, maxy_)
  1388. return minx, miny, maxx, maxy
  1389. else:
  1390. # it's a Shapely object, return it's bounds
  1391. return shape.bounds
  1392. bounds_coords = bounds_rec(self.geo)
  1393. return bounds_coords
  1394. def mirror(self, axis, point):
  1395. """
  1396. Mirrors the shape around a specified axis passing through
  1397. the given point.
  1398. :param axis: "X" or "Y" indicates around which axis to mirror.
  1399. :type axis: str
  1400. :param point: [x, y] point belonging to the mirror axis.
  1401. :type point: list
  1402. :return: None
  1403. """
  1404. px, py = point
  1405. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1406. def mirror_geom(shape):
  1407. if type(shape) is list:
  1408. new_obj = []
  1409. for g in shape:
  1410. new_obj.append(mirror_geom(g))
  1411. return new_obj
  1412. else:
  1413. return affinity.scale(shape, xscale, yscale, origin=(px,py))
  1414. try:
  1415. self.geo = mirror_geom(self.geo)
  1416. except AttributeError:
  1417. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1418. def rotate(self, angle, point):
  1419. """
  1420. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1421. Parameters
  1422. ----------
  1423. The angle of rotation are specified in degrees (default). Positive angles are
  1424. counter-clockwise and negative are clockwise rotations.
  1425. The point of origin can be a keyword 'center' for the bounding box
  1426. center (default), 'centroid' for the geometry's centroid, a Point object
  1427. or a coordinate tuple (x0, y0).
  1428. See shapely manual for more information:
  1429. http://toblerity.org/shapely/manual.html#affine-transformations
  1430. """
  1431. px, py = point
  1432. def rotate_geom(shape):
  1433. if type(shape) is list:
  1434. new_obj = []
  1435. for g in shape:
  1436. new_obj.append(rotate_geom(g))
  1437. return new_obj
  1438. else:
  1439. return affinity.rotate(shape, angle, origin=(px, py))
  1440. try:
  1441. self.geo = rotate_geom(self.geo)
  1442. except AttributeError:
  1443. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1444. def skew(self, angle_x, angle_y, point):
  1445. """
  1446. Shear/Skew a shape by angles along x and y dimensions.
  1447. Parameters
  1448. ----------
  1449. angle_x, angle_y : float, float
  1450. The shear angle(s) for the x and y axes respectively. These can be
  1451. specified in either degrees (default) or radians by setting
  1452. use_radians=True.
  1453. point: tuple of coordinates (x,y)
  1454. See shapely manual for more information:
  1455. http://toblerity.org/shapely/manual.html#affine-transformations
  1456. """
  1457. px, py = point
  1458. def skew_geom(shape):
  1459. if type(shape) is list:
  1460. new_obj = []
  1461. for g in shape:
  1462. new_obj.append(skew_geom(g))
  1463. return new_obj
  1464. else:
  1465. return affinity.skew(shape, angle_x, angle_y, origin=(px, py))
  1466. try:
  1467. self.geo = skew_geom(self.geo)
  1468. except AttributeError:
  1469. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1470. def offset(self, vect):
  1471. """
  1472. Offsets all shapes by a given vector/
  1473. :param vect: (x, y) vector by which to offset the shape geometry
  1474. :type vect: tuple
  1475. :return: None
  1476. :rtype: None
  1477. """
  1478. try:
  1479. dx, dy = vect
  1480. except TypeError:
  1481. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1482. "Probable you entered only one value in the Offset field.")
  1483. return
  1484. def translate_recursion(geom):
  1485. if type(geom) == list:
  1486. geoms=list()
  1487. for local_geom in geom:
  1488. geoms.append(translate_recursion(local_geom))
  1489. return geoms
  1490. else:
  1491. return affinity.translate(geom, xoff=dx, yoff=dy)
  1492. try:
  1493. self.geo = translate_recursion(self.geo)
  1494. except AttributeError:
  1495. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1496. def scale(self, xfactor, yfactor=None, point=None):
  1497. """
  1498. Scales all shape geometry by a given factor.
  1499. :param xfactor: Factor by which to scale the shape's geometry/
  1500. :type xfactor: float
  1501. :param yfactor: Factor by which to scale the shape's geometry/
  1502. :type yfactor: float
  1503. :return: None
  1504. :rtype: None
  1505. """
  1506. try:
  1507. xfactor = float(xfactor)
  1508. except:
  1509. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1510. return
  1511. if yfactor is None:
  1512. yfactor = xfactor
  1513. else:
  1514. try:
  1515. yfactor = float(yfactor)
  1516. except:
  1517. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1518. return
  1519. if point is None:
  1520. px = 0
  1521. py = 0
  1522. else:
  1523. px, py = point
  1524. def scale_recursion(geom):
  1525. if type(geom) == list:
  1526. geoms=list()
  1527. for local_geom in geom:
  1528. geoms.append(scale_recursion(local_geom))
  1529. return geoms
  1530. else:
  1531. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1532. try:
  1533. self.geo = scale_recursion(self.geo)
  1534. except AttributeError:
  1535. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1536. class DrawToolUtilityShape(DrawToolShape):
  1537. """
  1538. Utility shapes are temporary geometry in the editor
  1539. to assist in the creation of shapes. For example it
  1540. will show the outline of a rectangle from the first
  1541. point to the current mouse pointer before the second
  1542. point is clicked and the final geometry is created.
  1543. """
  1544. def __init__(self, geo=[]):
  1545. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1546. self.utility = True
  1547. class DrawTool(object):
  1548. """
  1549. Abstract Class representing a tool in the drawing
  1550. program. Can generate geometry, including temporary
  1551. utility geometry that is updated on user clicks
  1552. and mouse motion.
  1553. """
  1554. def __init__(self, draw_app):
  1555. self.draw_app = draw_app
  1556. self.complete = False
  1557. self.start_msg = "Click on 1st point..."
  1558. self.points = []
  1559. self.geometry = None # DrawToolShape or None
  1560. def click(self, point):
  1561. """
  1562. :param point: [x, y] Coordinate pair.
  1563. """
  1564. return ""
  1565. def click_release(self, point):
  1566. """
  1567. :param point: [x, y] Coordinate pair.
  1568. """
  1569. return ""
  1570. def on_key(self, key):
  1571. return None
  1572. def utility_geometry(self, data=None):
  1573. return None
  1574. class FCShapeTool(DrawTool):
  1575. """
  1576. Abstract class for tools that create a shape.
  1577. """
  1578. def __init__(self, draw_app):
  1579. DrawTool.__init__(self, draw_app)
  1580. def make(self):
  1581. pass
  1582. class FCCircle(FCShapeTool):
  1583. """
  1584. Resulting type: Polygon
  1585. """
  1586. def __init__(self, draw_app):
  1587. DrawTool.__init__(self, draw_app)
  1588. self.name = 'circle'
  1589. self.start_msg = _("Click on CENTER ...")
  1590. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1591. def click(self, point):
  1592. self.points.append(point)
  1593. if len(self.points) == 1:
  1594. self.draw_app.app.inform.emit(_("Click on Circle perimeter point to complete ..."))
  1595. return "Click on perimeter to complete ..."
  1596. if len(self.points) == 2:
  1597. self.make()
  1598. return "Done."
  1599. return ""
  1600. def utility_geometry(self, data=None):
  1601. if len(self.points) == 1:
  1602. p1 = self.points[0]
  1603. p2 = data
  1604. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1605. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1606. return None
  1607. def make(self):
  1608. p1 = self.points[0]
  1609. p2 = self.points[1]
  1610. radius = distance(p1, p2)
  1611. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1612. self.complete = True
  1613. self.draw_app.app.inform.emit(_("[success]Done. Adding Circle completed."))
  1614. class FCArc(FCShapeTool):
  1615. def __init__(self, draw_app):
  1616. DrawTool.__init__(self, draw_app)
  1617. self.name = 'arc'
  1618. self.start_msg = _("Click on CENTER ...")
  1619. # Direction of rotation between point 1 and 2.
  1620. # 'cw' or 'ccw'. Switch direction by hitting the
  1621. # 'o' key.
  1622. self.direction = "cw"
  1623. # Mode
  1624. # C12 = Center, p1, p2
  1625. # 12C = p1, p2, Center
  1626. # 132 = p1, p3, p2
  1627. self.mode = "c12" # Center, p1, p2
  1628. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1629. def click(self, point):
  1630. self.points.append(point)
  1631. if len(self.points) == 1:
  1632. self.draw_app.app.inform.emit(_("Click on Start arc point ..."))
  1633. return "Click on 1st point ..."
  1634. if len(self.points) == 2:
  1635. self.draw_app.app.inform.emit(_("Click on End arc point to complete ..."))
  1636. return "Click on 2nd point to complete ..."
  1637. if len(self.points) == 3:
  1638. self.make()
  1639. return "Done."
  1640. return ""
  1641. def on_key(self, key):
  1642. if key == 'o':
  1643. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1644. return 'Direction: ' + self.direction.upper()
  1645. if key == 'p':
  1646. if self.mode == 'c12':
  1647. self.mode = '12c'
  1648. elif self.mode == '12c':
  1649. self.mode = '132'
  1650. else:
  1651. self.mode = 'c12'
  1652. return 'Mode: ' + self.mode
  1653. def utility_geometry(self, data=None):
  1654. if len(self.points) == 1: # Show the radius
  1655. center = self.points[0]
  1656. p1 = data
  1657. return DrawToolUtilityShape(LineString([center, p1]))
  1658. if len(self.points) == 2: # Show the arc
  1659. if self.mode == 'c12':
  1660. center = self.points[0]
  1661. p1 = self.points[1]
  1662. p2 = data
  1663. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1664. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1665. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1666. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1667. self.direction, self.steps_per_circ)),
  1668. Point(center)])
  1669. elif self.mode == '132':
  1670. p1 = array(self.points[0])
  1671. p3 = array(self.points[1])
  1672. p2 = array(data)
  1673. center, radius, t = three_point_circle(p1, p2, p3)
  1674. direction = 'cw' if sign(t) > 0 else 'ccw'
  1675. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1676. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1677. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1678. direction, self.steps_per_circ)),
  1679. Point(center), Point(p1), Point(p3)])
  1680. else: # '12c'
  1681. p1 = array(self.points[0])
  1682. p2 = array(self.points[1])
  1683. # Midpoint
  1684. a = (p1 + p2) / 2.0
  1685. # Parallel vector
  1686. c = p2 - p1
  1687. # Perpendicular vector
  1688. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1689. b /= norm(b)
  1690. # Distance
  1691. t = distance(data, a)
  1692. # Which side? Cross product with c.
  1693. # cross(M-A, B-A), where line is AB and M is test point.
  1694. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1695. t *= sign(side)
  1696. # Center = a + bt
  1697. center = a + b * t
  1698. radius = norm(center - p1)
  1699. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1700. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1701. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1702. self.direction, self.steps_per_circ)),
  1703. Point(center)])
  1704. return None
  1705. def make(self):
  1706. if self.mode == 'c12':
  1707. center = self.points[0]
  1708. p1 = self.points[1]
  1709. p2 = self.points[2]
  1710. radius = distance(center, p1)
  1711. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1712. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1713. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1714. self.direction, self.steps_per_circ)))
  1715. elif self.mode == '132':
  1716. p1 = array(self.points[0])
  1717. p3 = array(self.points[1])
  1718. p2 = array(self.points[2])
  1719. center, radius, t = three_point_circle(p1, p2, p3)
  1720. direction = 'cw' if sign(t) > 0 else 'ccw'
  1721. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1722. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1723. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1724. direction, self.steps_per_circ)))
  1725. else: # self.mode == '12c'
  1726. p1 = array(self.points[0])
  1727. p2 = array(self.points[1])
  1728. pc = array(self.points[2])
  1729. # Midpoint
  1730. a = (p1 + p2) / 2.0
  1731. # Parallel vector
  1732. c = p2 - p1
  1733. # Perpendicular vector
  1734. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1735. b /= norm(b)
  1736. # Distance
  1737. t = distance(pc, a)
  1738. # Which side? Cross product with c.
  1739. # cross(M-A, B-A), where line is AB and M is test point.
  1740. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1741. t *= sign(side)
  1742. # Center = a + bt
  1743. center = a + b * t
  1744. radius = norm(center - p1)
  1745. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1746. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1747. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1748. self.direction, self.steps_per_circ)))
  1749. self.complete = True
  1750. self.draw_app.app.inform.emit(_("[success]Done. Arc completed."))
  1751. class FCRectangle(FCShapeTool):
  1752. """
  1753. Resulting type: Polygon
  1754. """
  1755. def __init__(self, draw_app):
  1756. DrawTool.__init__(self, draw_app)
  1757. self.name = 'rectangle'
  1758. self.start_msg = _("Click on 1st corner ...")
  1759. def click(self, point):
  1760. self.points.append(point)
  1761. if len(self.points) == 1:
  1762. return "Click on opposite corner to complete ..."
  1763. if len(self.points) == 2:
  1764. self.make()
  1765. return "Done."
  1766. return ""
  1767. def utility_geometry(self, data=None):
  1768. if len(self.points) == 1:
  1769. p1 = self.points[0]
  1770. p2 = data
  1771. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1772. return None
  1773. def make(self):
  1774. p1 = self.points[0]
  1775. p2 = self.points[1]
  1776. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1777. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1778. self.complete = True
  1779. self.draw_app.app.inform.emit("_([success]Done. Rectangle completed.")
  1780. class FCPolygon(FCShapeTool):
  1781. """
  1782. Resulting type: Polygon
  1783. """
  1784. def __init__(self, draw_app):
  1785. DrawTool.__init__(self, draw_app)
  1786. self.name = 'polygon'
  1787. self.start_msg = _("Click on 1st point ...")
  1788. def click(self, point):
  1789. self.draw_app.in_action = True
  1790. self.points.append(point)
  1791. if len(self.points) > 0:
  1792. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  1793. return "Click on next point or hit ENTER to complete ..."
  1794. return ""
  1795. def utility_geometry(self, data=None):
  1796. if len(self.points) == 1:
  1797. temp_points = [x for x in self.points]
  1798. temp_points.append(data)
  1799. return DrawToolUtilityShape(LineString(temp_points))
  1800. if len(self.points) > 1:
  1801. temp_points = [x for x in self.points]
  1802. temp_points.append(data)
  1803. return DrawToolUtilityShape(LinearRing(temp_points))
  1804. return None
  1805. def make(self):
  1806. # self.geometry = LinearRing(self.points)
  1807. self.geometry = DrawToolShape(Polygon(self.points))
  1808. self.draw_app.in_action = False
  1809. self.complete = True
  1810. self.draw_app.app.inform.emit(_("[success]Done. Polygon completed."))
  1811. def on_key(self, key):
  1812. if key == 'backspace':
  1813. if len(self.points) > 0:
  1814. self.points = self.points[0:-1]
  1815. class FCPath(FCPolygon):
  1816. """
  1817. Resulting type: LineString
  1818. """
  1819. def make(self):
  1820. self.geometry = DrawToolShape(LineString(self.points))
  1821. self.name = 'path'
  1822. self.draw_app.in_action = False
  1823. self.complete = True
  1824. self.draw_app.app.inform.emit(_("[success]Done. Path completed."))
  1825. def utility_geometry(self, data=None):
  1826. if len(self.points) > 0:
  1827. temp_points = [x for x in self.points]
  1828. temp_points.append(data)
  1829. return DrawToolUtilityShape(LineString(temp_points))
  1830. return None
  1831. def on_key(self, key):
  1832. if key == 'backspace':
  1833. if len(self.points) > 0:
  1834. self.points = self.points[0:-1]
  1835. class FCSelect(DrawTool):
  1836. def __init__(self, draw_app):
  1837. DrawTool.__init__(self, draw_app)
  1838. self.name = 'select'
  1839. self.storage = self.draw_app.storage
  1840. # self.shape_buffer = self.draw_app.shape_buffer
  1841. # self.selected = self.draw_app.selected
  1842. def click_release(self, point):
  1843. self.select_shapes(point)
  1844. return ""
  1845. def select_shapes(self, pos):
  1846. # list where we store the overlapped shapes under our mouse left click position
  1847. over_shape_list = []
  1848. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1849. for obj_shape in self.storage.get_objects():
  1850. # first method of click selection -> inconvenient
  1851. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1852. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1853. # over_shape_list.append(obj_shape)
  1854. # second method of click selection -> slow
  1855. # outside = obj_shape.geo.buffer(0.1)
  1856. # inside = obj_shape.geo.buffer(-0.1)
  1857. # shape_band = outside.difference(inside)
  1858. # if Point(pos).within(shape_band):
  1859. # over_shape_list.append(obj_shape)
  1860. # 3rd method of click selection -> inconvenient
  1861. try:
  1862. _, closest_shape = self.storage.nearest(pos)
  1863. except StopIteration:
  1864. return ""
  1865. over_shape_list.append(closest_shape)
  1866. try:
  1867. # if there is no shape under our click then deselect all shapes
  1868. # it will not work for 3rd method of click selection
  1869. if not over_shape_list:
  1870. self.draw_app.selected = []
  1871. FlatCAMGeoEditor.draw_shape_idx = -1
  1872. else:
  1873. # if there are shapes under our click then advance through the list of them, one at the time in a
  1874. # circular way
  1875. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1876. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1877. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1878. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1879. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1880. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1881. if key_modifier == Qt.ControlModifier:
  1882. if obj_to_add in self.draw_app.selected:
  1883. self.draw_app.selected.remove(obj_to_add)
  1884. else:
  1885. self.draw_app.selected.append(obj_to_add)
  1886. else:
  1887. self.draw_app.selected = []
  1888. self.draw_app.selected.append(obj_to_add)
  1889. else:
  1890. if key_modifier == Qt.ShiftModifier:
  1891. if obj_to_add in self.draw_app.selected:
  1892. self.draw_app.selected.remove(obj_to_add)
  1893. else:
  1894. self.draw_app.selected.append(obj_to_add)
  1895. else:
  1896. self.draw_app.selected = []
  1897. self.draw_app.selected.append(obj_to_add)
  1898. except Exception as e:
  1899. log.error("[ERROR] Something went bad. %s" % str(e))
  1900. raise
  1901. class FCDrillSelect(DrawTool):
  1902. def __init__(self, exc_editor_app):
  1903. DrawTool.__init__(self, exc_editor_app)
  1904. self.name = 'drill_select'
  1905. self.exc_editor_app = exc_editor_app
  1906. self.storage = self.exc_editor_app.storage_dict
  1907. # self.selected = self.exc_editor_app.selected
  1908. # here we store all shapes that were selected so we can search for the nearest to our click location
  1909. self.sel_storage = FlatCAMExcEditor.make_storage()
  1910. self.exc_editor_app.resize_frame.hide()
  1911. self.exc_editor_app.array_frame.hide()
  1912. def click(self, point):
  1913. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1914. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1915. if key_modifier == Qt.ControlModifier:
  1916. pass
  1917. else:
  1918. self.exc_editor_app.selected = []
  1919. else:
  1920. if key_modifier == Qt.ShiftModifier:
  1921. pass
  1922. else:
  1923. self.exc_editor_app.selected = []
  1924. def click_release(self, point):
  1925. self.select_shapes(point)
  1926. return ""
  1927. def select_shapes(self, pos):
  1928. self.exc_editor_app.tools_table_exc.clearSelection()
  1929. try:
  1930. # for storage in self.exc_editor_app.storage_dict:
  1931. # _, partial_closest_shape = self.exc_editor_app.storage_dict[storage].nearest(pos)
  1932. # if partial_closest_shape is not None:
  1933. # self.sel_storage.insert(partial_closest_shape)
  1934. #
  1935. # _, closest_shape = self.sel_storage.nearest(pos)
  1936. for storage in self.exc_editor_app.storage_dict:
  1937. for shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1938. self.sel_storage.insert(shape)
  1939. _, closest_shape = self.sel_storage.nearest(pos)
  1940. # constrain selection to happen only within a certain bounding box
  1941. x_coord, y_coord = closest_shape.geo[0].xy
  1942. delta = (x_coord[1] - x_coord[0])
  1943. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  1944. xmin = x_coord[0] - (0.7 * delta)
  1945. xmax = x_coord[0] + (1.7 * delta)
  1946. ymin = y_coord[0] - (0.7 * delta)
  1947. ymax = y_coord[0] + (1.7 * delta)
  1948. except StopIteration:
  1949. return ""
  1950. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  1951. self.exc_editor_app.selected = []
  1952. else:
  1953. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1954. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1955. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1956. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1957. if key_modifier == Qt.ControlModifier:
  1958. if closest_shape in self.exc_editor_app.selected:
  1959. self.exc_editor_app.selected.remove(closest_shape)
  1960. else:
  1961. self.exc_editor_app.selected.append(closest_shape)
  1962. else:
  1963. self.exc_editor_app.selected = []
  1964. self.exc_editor_app.selected.append(closest_shape)
  1965. else:
  1966. if key_modifier == Qt.ShiftModifier:
  1967. if closest_shape in self.exc_editor_app.selected:
  1968. self.exc_editor_app.selected.remove(closest_shape)
  1969. else:
  1970. self.exc_editor_app.selected.append(closest_shape)
  1971. else:
  1972. self.exc_editor_app.selected = []
  1973. self.exc_editor_app.selected.append(closest_shape)
  1974. # select the diameter of the selected shape in the tool table
  1975. for storage in self.exc_editor_app.storage_dict:
  1976. for shape_s in self.exc_editor_app.selected:
  1977. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  1978. for key in self.exc_editor_app.tool2tooldia:
  1979. if self.exc_editor_app.tool2tooldia[key] == storage:
  1980. item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1981. self.exc_editor_app.tools_table_exc.setCurrentItem(item)
  1982. # item.setSelected(True)
  1983. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1984. # midx = self.exc_editor_app.tools_table_exc.model().index((key - 1), 0)
  1985. # self.exc_editor_app.tools_table_exc.setCurrentIndex(midx)
  1986. self.draw_app.last_tool_selected = key
  1987. # delete whatever is in selection storage, there is no longer need for those shapes
  1988. self.sel_storage = FlatCAMExcEditor.make_storage()
  1989. return ""
  1990. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1991. # for storage in self.exc_editor_app.storage_dict:
  1992. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1993. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1994. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1995. # over_shape_list.append(obj_shape)
  1996. #
  1997. # try:
  1998. # # if there is no shape under our click then deselect all shapes
  1999. # if not over_shape_list:
  2000. # self.exc_editor_app.selected = []
  2001. # FlatCAMExcEditor.draw_shape_idx = -1
  2002. # self.exc_editor_app.tools_table_exc.clearSelection()
  2003. # else:
  2004. # # if there are shapes under our click then advance through the list of them, one at the time in a
  2005. # # circular way
  2006. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  2007. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  2008. #
  2009. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  2010. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  2011. # if obj_to_add in self.exc_editor_app.selected:
  2012. # self.exc_editor_app.selected.remove(obj_to_add)
  2013. # else:
  2014. # self.exc_editor_app.selected.append(obj_to_add)
  2015. # else:
  2016. # self.exc_editor_app.selected = []
  2017. # self.exc_editor_app.selected.append(obj_to_add)
  2018. # else:
  2019. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  2020. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  2021. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  2022. # if obj_to_add in self.exc_editor_app.selected:
  2023. # self.exc_editor_app.selected.remove(obj_to_add)
  2024. # else:
  2025. # self.exc_editor_app.selected.append(obj_to_add)
  2026. # else:
  2027. # self.exc_editor_app.selected = []
  2028. # self.exc_editor_app.selected.append(obj_to_add)
  2029. #
  2030. # for storage in self.exc_editor_app.storage_dict:
  2031. # for shape in self.exc_editor_app.selected:
  2032. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  2033. # for key in self.exc_editor_app.tool2tooldia:
  2034. # if self.exc_editor_app.tool2tooldia[key] == storage:
  2035. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  2036. # item.setSelected(True)
  2037. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  2038. #
  2039. # except Exception as e:
  2040. # log.error("[ERROR] Something went bad. %s" % str(e))
  2041. # raise
  2042. class FCMove(FCShapeTool):
  2043. def __init__(self, draw_app):
  2044. FCShapeTool.__init__(self, draw_app)
  2045. self.name = 'move'
  2046. # self.shape_buffer = self.draw_app.shape_buffer
  2047. if not self.draw_app.selected:
  2048. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2049. return
  2050. self.origin = None
  2051. self.destination = None
  2052. self.start_msg = _("Click on reference point.")
  2053. def set_origin(self, origin):
  2054. self.draw_app.app.inform.emit(_("Click on destination point."))
  2055. self.origin = origin
  2056. def click(self, point):
  2057. if len(self.draw_app.get_selected()) == 0:
  2058. return "Nothing to move."
  2059. if self.origin is None:
  2060. self.set_origin(point)
  2061. return "Click on final location."
  2062. else:
  2063. self.destination = point
  2064. self.make()
  2065. return "Done."
  2066. def make(self):
  2067. # Create new geometry
  2068. dx = self.destination[0] - self.origin[0]
  2069. dy = self.destination[1] - self.origin[1]
  2070. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2071. for geom in self.draw_app.get_selected()]
  2072. # Delete old
  2073. self.draw_app.delete_selected()
  2074. # # Select the new
  2075. # for g in self.geometry:
  2076. # # Note that g is not in the app's buffer yet!
  2077. # self.draw_app.set_selected(g)
  2078. self.complete = True
  2079. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Move completed."))
  2080. def utility_geometry(self, data=None):
  2081. """
  2082. Temporary geometry on screen while using this tool.
  2083. :param data:
  2084. :return:
  2085. """
  2086. geo_list = []
  2087. if self.origin is None:
  2088. return None
  2089. if len(self.draw_app.get_selected()) == 0:
  2090. return None
  2091. dx = data[0] - self.origin[0]
  2092. dy = data[1] - self.origin[1]
  2093. try:
  2094. for geom in self.draw_app.get_selected():
  2095. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2096. except AttributeError:
  2097. self.draw_app.select_tool('select')
  2098. self.draw_app.selected = []
  2099. return
  2100. return DrawToolUtilityShape(geo_list)
  2101. # return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  2102. # for geom in self.draw_app.get_selected()])
  2103. class FCCopy(FCMove):
  2104. def __init__(self, draw_app):
  2105. FCMove.__init__(self, draw_app)
  2106. self.name = 'copy'
  2107. def make(self):
  2108. # Create new geometry
  2109. dx = self.destination[0] - self.origin[0]
  2110. dy = self.destination[1] - self.origin[1]
  2111. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2112. for geom in self.draw_app.get_selected()]
  2113. self.complete = True
  2114. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Copy completed."))
  2115. class FCText(FCShapeTool):
  2116. def __init__(self, draw_app):
  2117. FCShapeTool.__init__(self, draw_app)
  2118. self.name = 'text'
  2119. # self.shape_buffer = self.draw_app.shape_buffer
  2120. self.draw_app = draw_app
  2121. self.app = draw_app.app
  2122. self.start_msg = _("Click on the Destination point...")
  2123. self.origin = (0, 0)
  2124. self.text_gui = TextInputTool(self.app)
  2125. self.text_gui.run()
  2126. def click(self, point):
  2127. # Create new geometry
  2128. dx = point[0]
  2129. dy = point[1]
  2130. try:
  2131. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2132. except Exception as e:
  2133. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2134. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2135. "supported. Error: %s") % str(e))
  2136. self.text_gui.text_path = []
  2137. self.text_gui.hide_tool()
  2138. self.draw_app.select_tool('select')
  2139. return
  2140. self.text_gui.text_path = []
  2141. self.text_gui.hide_tool()
  2142. self.complete = True
  2143. self.draw_app.app.inform.emit(_("[success]Done. Adding Text completed."))
  2144. def utility_geometry(self, data=None):
  2145. """
  2146. Temporary geometry on screen while using this tool.
  2147. :param data: mouse position coords
  2148. :return:
  2149. """
  2150. dx = data[0] - self.origin[0]
  2151. dy = data[1] - self.origin[1]
  2152. try:
  2153. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2154. except:
  2155. return
  2156. class FCBuffer(FCShapeTool):
  2157. def __init__(self, draw_app):
  2158. FCShapeTool.__init__(self, draw_app)
  2159. self.name = 'buffer'
  2160. # self.shape_buffer = self.draw_app.shape_buffer
  2161. self.draw_app = draw_app
  2162. self.app = draw_app.app
  2163. self.start_msg = _("Create buffer geometry ...")
  2164. self.origin = (0, 0)
  2165. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2166. self.buff_tool.run()
  2167. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2168. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2169. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2170. self.activate()
  2171. def on_buffer(self):
  2172. if not self.draw_app.selected:
  2173. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2174. return
  2175. try:
  2176. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2177. except ValueError:
  2178. # try to convert comma to decimal point. if it's still not working error message and return
  2179. try:
  2180. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2181. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2182. except ValueError:
  2183. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2184. "Add it and retry."))
  2185. return
  2186. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2187. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2188. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2189. self.draw_app.buffer(buffer_distance, join_style)
  2190. self.app.ui.notebook.setTabText(2, _("Tools"))
  2191. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2192. self.disactivate()
  2193. self.draw_app.app.inform.emit(_("[success]Done. Buffer Tool completed."))
  2194. def on_buffer_int(self):
  2195. if not self.draw_app.selected:
  2196. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2197. return
  2198. try:
  2199. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2200. except ValueError:
  2201. # try to convert comma to decimal point. if it's still not working error message and return
  2202. try:
  2203. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2204. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2205. except ValueError:
  2206. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2207. "Add it and retry."))
  2208. return
  2209. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2210. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2211. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2212. self.draw_app.buffer_int(buffer_distance, join_style)
  2213. self.app.ui.notebook.setTabText(2, _("Tools"))
  2214. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2215. self.disactivate()
  2216. self.draw_app.app.inform.emit(_("[success]Done. Buffer Int Tool completed."))
  2217. def on_buffer_ext(self):
  2218. if not self.draw_app.selected:
  2219. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2220. return
  2221. try:
  2222. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2223. except ValueError:
  2224. # try to convert comma to decimal point. if it's still not working error message and return
  2225. try:
  2226. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2227. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2228. except ValueError:
  2229. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2230. "Add it and retry."))
  2231. return
  2232. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2233. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2234. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2235. self.draw_app.buffer_ext(buffer_distance, join_style)
  2236. self.app.ui.notebook.setTabText(2, _("Tools"))
  2237. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2238. self.disactivate()
  2239. self.draw_app.app.inform.emit(_("[success]Done. Buffer Ext Tool completed."))
  2240. def activate(self):
  2241. self.buff_tool.buffer_button.clicked.disconnect()
  2242. self.buff_tool.buffer_int_button.clicked.disconnect()
  2243. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2244. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2245. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2246. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2247. def disactivate(self):
  2248. self.buff_tool.buffer_button.clicked.disconnect()
  2249. self.buff_tool.buffer_int_button.clicked.disconnect()
  2250. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2251. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2252. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2253. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2254. self.complete = True
  2255. self.draw_app.select_tool("select")
  2256. self.buff_tool.hide_tool()
  2257. class FCPaint(FCShapeTool):
  2258. def __init__(self, draw_app):
  2259. FCShapeTool.__init__(self, draw_app)
  2260. self.name = 'paint'
  2261. # self.shape_buffer = self.draw_app.shape_buffer
  2262. self.draw_app = draw_app
  2263. self.app = draw_app.app
  2264. self.start_msg = _("Create Paint geometry ...")
  2265. self.origin = (0, 0)
  2266. self.draw_app.paint_tool.run()
  2267. class FCTransform(FCShapeTool):
  2268. def __init__(self, draw_app):
  2269. FCShapeTool.__init__(self, draw_app)
  2270. self.name = 'transformation'
  2271. # self.shape_buffer = self.draw_app.shape_buffer
  2272. self.draw_app = draw_app
  2273. self.app = draw_app.app
  2274. self.start_msg = _("Shape transformations ...")
  2275. self.origin = (0, 0)
  2276. self.draw_app.transform_tool.run()
  2277. class FCDrillAdd(FCShapeTool):
  2278. """
  2279. Resulting type: MultiLineString
  2280. """
  2281. def __init__(self, draw_app):
  2282. DrawTool.__init__(self, draw_app)
  2283. self.name = 'drill_add'
  2284. self.selected_dia = None
  2285. try:
  2286. self.draw_app.app.inform.emit(self.start_msg)
  2287. # self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.tools_table_exc.currentRow() + 1]
  2288. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2289. # as a visual marker, select again in tooltable the actual tool that we are using
  2290. # remember that it was deselected when clicking on canvas
  2291. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2292. self.draw_app.tools_table_exc.setCurrentItem(item)
  2293. except KeyError:
  2294. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  2295. self.draw_app.select_tool("select")
  2296. return
  2297. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  2298. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2299. self.draw_app.draw_utility_geometry(geo=geo)
  2300. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2301. # Switch notebook to Selected page
  2302. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2303. def click(self, point):
  2304. self.make()
  2305. return "Done."
  2306. def utility_geometry(self, data=None):
  2307. self.points = data
  2308. return DrawToolUtilityShape(self.util_shape(data))
  2309. def util_shape(self, point):
  2310. if point[0] is None and point[1] is None:
  2311. point_x = self.draw_app.x
  2312. point_y = self.draw_app.y
  2313. else:
  2314. point_x = point[0]
  2315. point_y = point[1]
  2316. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2317. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2318. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2319. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2320. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2321. def make(self):
  2322. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2323. # to the value, as a list of itself
  2324. if self.selected_dia in self.draw_app.points_edit:
  2325. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2326. else:
  2327. self.draw_app.points_edit[self.selected_dia] = [self.points]
  2328. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2329. self.geometry = DrawToolShape(self.util_shape(self.points))
  2330. self.complete = True
  2331. self.draw_app.app.inform.emit(_("[success]Done. Drill added."))
  2332. class FCDrillArray(FCShapeTool):
  2333. """
  2334. Resulting type: MultiLineString
  2335. """
  2336. def __init__(self, draw_app):
  2337. DrawTool.__init__(self, draw_app)
  2338. self.name = 'drill_array'
  2339. self.draw_app.array_frame.show()
  2340. self.selected_dia = None
  2341. self.drill_axis = 'X'
  2342. self.drill_array = 'linear'
  2343. self.drill_array_size = None
  2344. self.drill_pitch = None
  2345. self.drill_linear_angle = None
  2346. self.drill_angle = None
  2347. self.drill_direction = None
  2348. self.drill_radius = None
  2349. self.origin = None
  2350. self.destination = None
  2351. self.flag_for_circ_array = None
  2352. self.last_dx = 0
  2353. self.last_dy = 0
  2354. self.pt = []
  2355. try:
  2356. self.draw_app.app.inform.emit(self.start_msg)
  2357. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2358. # as a visual marker, select again in tooltable the actual tool that we are using
  2359. # remember that it was deselected when clicking on canvas
  2360. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2361. self.draw_app.tools_table_exc.setCurrentItem(item)
  2362. except KeyError:
  2363. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  2364. return
  2365. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  2366. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2367. self.draw_app.draw_utility_geometry(geo=geo)
  2368. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2369. # Switch notebook to Selected page
  2370. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2371. def click(self, point):
  2372. if self.drill_array == 'Linear':
  2373. self.make()
  2374. return
  2375. else:
  2376. if self.flag_for_circ_array is None:
  2377. self.draw_app.in_action = True
  2378. self.pt.append(point)
  2379. self.flag_for_circ_array = True
  2380. self.set_origin(point)
  2381. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  2382. else:
  2383. self.destination = point
  2384. self.make()
  2385. self.flag_for_circ_array = None
  2386. return
  2387. def set_origin(self, origin):
  2388. self.origin = origin
  2389. def utility_geometry(self, data=None, static=None):
  2390. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  2391. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  2392. self.drill_array = self.draw_app.array_type_combo.get_value()
  2393. try:
  2394. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  2395. try:
  2396. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  2397. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  2398. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  2399. except TypeError:
  2400. self.draw_app.app.inform.emit(
  2401. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  2402. return
  2403. except Exception as e:
  2404. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  2405. return
  2406. if self.drill_array == 'Linear':
  2407. if data[0] is None and data[1] is None:
  2408. dx = self.draw_app.x
  2409. dy = self.draw_app.y
  2410. else:
  2411. dx = data[0]
  2412. dy = data[1]
  2413. geo_list = []
  2414. geo = None
  2415. self.points = [dx, dy]
  2416. for item in range(self.drill_array_size):
  2417. if self.drill_axis == 'X':
  2418. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  2419. if self.drill_axis == 'Y':
  2420. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  2421. if self.drill_axis == 'A':
  2422. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2423. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2424. geo = self.util_shape(
  2425. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  2426. )
  2427. if static is None or static is False:
  2428. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  2429. else:
  2430. geo_list.append(geo)
  2431. # self.origin = data
  2432. self.last_dx = dx
  2433. self.last_dy = dy
  2434. return DrawToolUtilityShape(geo_list)
  2435. else:
  2436. if data[0] is None and data[1] is None:
  2437. cdx = self.draw_app.x
  2438. cdy = self.draw_app.y
  2439. else:
  2440. cdx = data[0]
  2441. cdy = data[1]
  2442. if len(self.pt) > 0:
  2443. temp_points = [x for x in self.pt]
  2444. temp_points.append([cdx, cdy])
  2445. return DrawToolUtilityShape(LineString(temp_points))
  2446. def util_shape(self, point):
  2447. if point[0] is None and point[1] is None:
  2448. point_x = self.draw_app.x
  2449. point_y = self.draw_app.y
  2450. else:
  2451. point_x = point[0]
  2452. point_y = point[1]
  2453. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2454. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2455. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2456. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2457. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2458. def make(self):
  2459. self.geometry = []
  2460. geo = None
  2461. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2462. # to the value, as a list of itself
  2463. if self.selected_dia not in self.draw_app.points_edit:
  2464. self.draw_app.points_edit[self.selected_dia] = []
  2465. for i in range(self.drill_array_size):
  2466. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2467. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2468. if self.drill_array == 'Linear':
  2469. for item in range(self.drill_array_size):
  2470. if self.drill_axis == 'X':
  2471. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  2472. if self.drill_axis == 'Y':
  2473. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  2474. if self.drill_axis == 'A':
  2475. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2476. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2477. geo = self.util_shape(
  2478. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  2479. )
  2480. self.geometry.append(DrawToolShape(geo))
  2481. else:
  2482. if (self.drill_angle * self.drill_array_size) > 360:
  2483. self.draw_app.app.inform.emit(_("[WARNING_NOTCL]Too many drills for the selected spacing angle."))
  2484. return
  2485. radius = distance(self.destination, self.origin)
  2486. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  2487. for i in range(self.drill_array_size):
  2488. angle_radians = math.radians(self.drill_angle * i)
  2489. if self.drill_direction == 'CW':
  2490. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  2491. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  2492. else:
  2493. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  2494. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  2495. geo = self.util_shape((x, y))
  2496. self.geometry.append(DrawToolShape(geo))
  2497. self.complete = True
  2498. self.draw_app.app.inform.emit(_("[success]Done. Drill Array added."))
  2499. self.draw_app.in_action = True
  2500. self.draw_app.array_frame.hide()
  2501. return
  2502. class FCDrillResize(FCShapeTool):
  2503. def __init__(self, draw_app):
  2504. DrawTool.__init__(self, draw_app)
  2505. self.name = 'drill_resize'
  2506. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  2507. self.resize_dia = None
  2508. self.draw_app.resize_frame.show()
  2509. self.points = None
  2510. self.selected_dia_list = []
  2511. self.current_storage = None
  2512. self.geometry = []
  2513. self.destination_storage = None
  2514. self.draw_app.resize_btn.clicked.connect(self.make)
  2515. # Switch notebook to Selected page
  2516. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2517. def make(self):
  2518. self.draw_app.is_modified = True
  2519. try:
  2520. new_dia = self.draw_app.resdrill_entry.get_value()
  2521. except:
  2522. self.draw_app.app.inform.emit(_("[ERROR_NOTCL]Resize drill(s) failed. Please enter a diameter for resize."))
  2523. return
  2524. if new_dia not in self.draw_app.olddia_newdia:
  2525. self.destination_storage = FlatCAMGeoEditor.make_storage()
  2526. self.draw_app.storage_dict[new_dia] = self.destination_storage
  2527. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2528. # each time a tool diameter is edited or added
  2529. self.draw_app.olddia_newdia[new_dia] = new_dia
  2530. else:
  2531. self.destination_storage = self.draw_app.storage_dict[new_dia]
  2532. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2533. row = index.row()
  2534. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2535. # therefore below we convert to float
  2536. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2537. self.selected_dia_list.append(float(dia_on_row))
  2538. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2539. # we add a new entry in the tool2tooldia dict
  2540. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  2541. sel_shapes_to_be_deleted = []
  2542. for sel_dia in self.selected_dia_list:
  2543. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2544. for select_shape in self.draw_app.get_selected():
  2545. if select_shape in self.current_storage.get_objects():
  2546. factor = new_dia / sel_dia
  2547. self.geometry.append(
  2548. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  2549. )
  2550. self.current_storage.remove(select_shape)
  2551. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  2552. # self.points_edit it's only useful first time when we load the data into the storage
  2553. # but is still used as reference when building tool_table in self.build_ui()
  2554. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2555. # deleting self.points_edit elements (doesn't matter who but just the number)
  2556. # solved the display issue.
  2557. del self.draw_app.points_edit[sel_dia][0]
  2558. sel_shapes_to_be_deleted.append(select_shape)
  2559. self.draw_app.on_exc_shape_complete(self.destination_storage)
  2560. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  2561. # self.points_edit it's only useful first time when we load the data into the storage
  2562. # but is still used as reference when building tool_table in self.build_ui()
  2563. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2564. # deleting self.points_edit elements (doesn't matter who but just the number)
  2565. # solved the display issue.
  2566. if new_dia not in self.draw_app.points_edit:
  2567. self.draw_app.points_edit[new_dia] = [(0, 0)]
  2568. else:
  2569. self.draw_app.points_edit[new_dia].append((0,0))
  2570. self.geometry = []
  2571. # if following the resize of the drills there will be no more drills for the selected tool then
  2572. # delete that tool
  2573. if not self.draw_app.points_edit[sel_dia]:
  2574. self.draw_app.on_tool_delete(sel_dia)
  2575. for shp in sel_shapes_to_be_deleted:
  2576. self.draw_app.selected.remove(shp)
  2577. sel_shapes_to_be_deleted = []
  2578. self.draw_app.build_ui()
  2579. self.draw_app.replot()
  2580. self.draw_app.resize_frame.hide()
  2581. self.complete = True
  2582. self.draw_app.app.inform.emit(_("[success]Done. Drill Resize completed."))
  2583. # MS: always return to the Select Tool
  2584. self.draw_app.select_tool("select")
  2585. class FCDrillMove(FCShapeTool):
  2586. def __init__(self, draw_app):
  2587. DrawTool.__init__(self, draw_app)
  2588. self.name = 'drill_move'
  2589. # self.shape_buffer = self.draw_app.shape_buffer
  2590. self.origin = None
  2591. self.destination = None
  2592. self.selected_dia_list = []
  2593. if self.draw_app.launched_from_shortcuts is True:
  2594. self.draw_app.launched_from_shortcuts = False
  2595. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2596. else:
  2597. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  2598. self.current_storage = None
  2599. self.geometry = []
  2600. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2601. row = index.row()
  2602. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2603. # therefore below we convert to float
  2604. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2605. self.selected_dia_list.append(float(dia_on_row))
  2606. # Switch notebook to Selected page
  2607. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2608. def set_origin(self, origin):
  2609. self.origin = origin
  2610. def click(self, point):
  2611. if len(self.draw_app.get_selected()) == 0:
  2612. return "Nothing to move."
  2613. if self.origin is None:
  2614. self.set_origin(point)
  2615. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2616. return
  2617. else:
  2618. self.destination = point
  2619. self.make()
  2620. # MS: always return to the Select Tool
  2621. self.draw_app.select_tool("select")
  2622. return
  2623. def make(self):
  2624. # Create new geometry
  2625. dx = self.destination[0] - self.origin[0]
  2626. dy = self.destination[1] - self.origin[1]
  2627. sel_shapes_to_be_deleted = []
  2628. for sel_dia in self.selected_dia_list:
  2629. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2630. for select_shape in self.draw_app.get_selected():
  2631. if select_shape in self.current_storage.get_objects():
  2632. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2633. self.current_storage.remove(select_shape)
  2634. sel_shapes_to_be_deleted.append(select_shape)
  2635. self.draw_app.on_exc_shape_complete(self.current_storage)
  2636. self.geometry = []
  2637. for shp in sel_shapes_to_be_deleted:
  2638. self.draw_app.selected.remove(shp)
  2639. sel_shapes_to_be_deleted = []
  2640. self.draw_app.build_ui()
  2641. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) Move completed."))
  2642. def utility_geometry(self, data=None):
  2643. """
  2644. Temporary geometry on screen while using this tool.
  2645. :param data:
  2646. :return:
  2647. """
  2648. geo_list = []
  2649. if self.origin is None:
  2650. return None
  2651. if len(self.draw_app.get_selected()) == 0:
  2652. return None
  2653. dx = data[0] - self.origin[0]
  2654. dy = data[1] - self.origin[1]
  2655. for geom in self.draw_app.get_selected():
  2656. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2657. return DrawToolUtilityShape(geo_list)
  2658. class FCDrillCopy(FCDrillMove):
  2659. def __init__(self, draw_app):
  2660. FCDrillMove.__init__(self, draw_app)
  2661. self.name = 'drill_copy'
  2662. def make(self):
  2663. # Create new geometry
  2664. dx = self.destination[0] - self.origin[0]
  2665. dy = self.destination[1] - self.origin[1]
  2666. sel_shapes_to_be_deleted = []
  2667. for sel_dia in self.selected_dia_list:
  2668. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2669. for select_shape in self.draw_app.get_selected():
  2670. if select_shape in self.current_storage.get_objects():
  2671. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2672. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  2673. self.draw_app.points_edit[sel_dia].append((0, 0))
  2674. sel_shapes_to_be_deleted.append(select_shape)
  2675. self.draw_app.on_exc_shape_complete(self.current_storage)
  2676. self.geometry = []
  2677. for shp in sel_shapes_to_be_deleted:
  2678. self.draw_app.selected.remove(shp)
  2679. sel_shapes_to_be_deleted = []
  2680. self.draw_app.build_ui()
  2681. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) copied."))
  2682. ########################
  2683. ### Main Application ###
  2684. ########################
  2685. class FlatCAMGeoEditor(QtCore.QObject):
  2686. transform_complete = QtCore.pyqtSignal()
  2687. draw_shape_idx = -1
  2688. def __init__(self, app, disabled=False):
  2689. assert isinstance(app, FlatCAMApp.App), \
  2690. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2691. super(FlatCAMGeoEditor, self).__init__()
  2692. self.app = app
  2693. self.canvas = app.plotcanvas
  2694. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2695. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2696. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2697. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2698. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2699. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2700. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2701. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2702. self.app.ui.geo_transform_menuitem.triggered.connect(self.on_transform_tool)
  2703. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2704. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2705. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2706. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2707. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2708. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2709. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2710. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2711. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2712. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2713. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2714. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2715. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2716. self.transform_complete.connect(self.on_transform_complete)
  2717. ## Toolbar events and properties
  2718. self.tools = {
  2719. "select": {"button": self.app.ui.geo_select_btn,
  2720. "constructor": FCSelect},
  2721. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2722. "constructor": FCArc},
  2723. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2724. "constructor": FCCircle},
  2725. "path": {"button": self.app.ui.geo_add_path_btn,
  2726. "constructor": FCPath},
  2727. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2728. "constructor": FCRectangle},
  2729. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2730. "constructor": FCPolygon},
  2731. "text": {"button": self.app.ui.geo_add_text_btn,
  2732. "constructor": FCText},
  2733. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2734. "constructor": FCBuffer},
  2735. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2736. "constructor": FCPaint},
  2737. "move": {"button": self.app.ui.geo_move_btn,
  2738. "constructor": FCMove},
  2739. "transform": {"button": self.app.ui.geo_transform_btn,
  2740. "constructor": FCTransform},
  2741. "copy": {"button": self.app.ui.geo_copy_btn,
  2742. "constructor": FCCopy}
  2743. }
  2744. ### Data
  2745. self.active_tool = None
  2746. self.storage = FlatCAMGeoEditor.make_storage()
  2747. self.utility = []
  2748. # VisPy visuals
  2749. self.fcgeometry = None
  2750. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2751. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2752. self.app.pool_recreated.connect(self.pool_recreated)
  2753. # Remove from scene
  2754. self.shapes.enabled = False
  2755. self.tool_shape.enabled = False
  2756. ## List of selected shapes.
  2757. self.selected = []
  2758. self.flat_geo = []
  2759. self.move_timer = QtCore.QTimer()
  2760. self.move_timer.setSingleShot(True)
  2761. # this var will store the state of the toolbar before starting the editor
  2762. self.toolbar_old_state = False
  2763. self.key = None # Currently pressed key
  2764. self.geo_key_modifiers = None
  2765. self.x = None # Current mouse cursor pos
  2766. self.y = None
  2767. # Current snapped mouse pos
  2768. self.snap_x = None
  2769. self.snap_y = None
  2770. self.pos = None
  2771. # signal that there is an action active like polygon or path
  2772. self.in_action = False
  2773. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2774. self.launched_from_shortcuts = False
  2775. def make_callback(thetool):
  2776. def f():
  2777. self.on_tool_select(thetool)
  2778. return f
  2779. for tool in self.tools:
  2780. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2781. self.tools[tool]["button"].setCheckable(True) # Checkable
  2782. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2783. self.app.ui.corner_snap_btn.setCheckable(True)
  2784. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2785. self.options = {
  2786. "global_gridx": 0.1,
  2787. "global_gridy": 0.1,
  2788. "global_snap_max": 0.05,
  2789. "grid_snap": True,
  2790. "corner_snap": False,
  2791. "grid_gap_link": True
  2792. }
  2793. self.app.options_read_form()
  2794. for option in self.options:
  2795. if option in self.app.options:
  2796. self.options[option] = self.app.options[option]
  2797. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2798. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2799. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2800. self.app.ui.grid_gap_link_cb.setChecked(True)
  2801. self.rtree_index = rtindex.Index()
  2802. def entry2option(option, entry):
  2803. try:
  2804. self.options[option] = float(entry.text())
  2805. except Exception as e:
  2806. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2807. return
  2808. def gridx_changed(goption, gentry):
  2809. entry2option(option=goption, entry=gentry)
  2810. # if the grid link is checked copy the value in the GridX field to GridY
  2811. if self.app.ui.grid_gap_link_cb.isChecked():
  2812. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2813. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2814. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2815. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2816. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2817. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2818. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2819. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2820. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2821. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2822. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2823. self.editor_active = False
  2824. # if using Paint store here the tool diameter used
  2825. self.paint_tooldia = None
  2826. self.paint_tool = PaintOptionsTool(self.app, self)
  2827. self.transform_tool = TransformEditorTool(self.app, self)
  2828. def pool_recreated(self, pool):
  2829. self.shapes.pool = pool
  2830. self.tool_shape.pool = pool
  2831. def on_transform_complete(self):
  2832. self.delete_selected()
  2833. self.replot()
  2834. def activate(self):
  2835. self.connect_canvas_event_handlers()
  2836. self.shapes.enabled = True
  2837. self.tool_shape.enabled = True
  2838. self.app.app_cursor.enabled = True
  2839. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2840. self.app.ui.corner_snap_btn.setEnabled(True)
  2841. self.app.ui.snap_magnet.setVisible(True)
  2842. self.app.ui.corner_snap_btn.setVisible(True)
  2843. self.app.ui.geo_editor_menu.setDisabled(False)
  2844. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2845. self.app.ui.update_obj_btn.setEnabled(True)
  2846. self.app.ui.g_editor_cmenu.setEnabled(True)
  2847. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2848. self.app.ui.geo_edit_toolbar.setVisible(True)
  2849. self.app.ui.snap_toolbar.setDisabled(False)
  2850. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2851. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2852. for w in sel_tab_widget_list:
  2853. w.setEnabled(False)
  2854. # Tell the App that the editor is active
  2855. self.editor_active = True
  2856. def deactivate(self):
  2857. self.disconnect_canvas_event_handlers()
  2858. self.clear()
  2859. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2860. settings = QSettings("Open Source", "FlatCAM")
  2861. if settings.contains("layout"):
  2862. layout = settings.value('layout', type=str)
  2863. if layout == 'standard':
  2864. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2865. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2866. self.app.ui.corner_snap_btn.setEnabled(False)
  2867. self.app.ui.snap_magnet.setVisible(False)
  2868. self.app.ui.corner_snap_btn.setVisible(False)
  2869. elif layout == 'compact':
  2870. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2871. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2872. self.app.ui.corner_snap_btn.setEnabled(False)
  2873. else:
  2874. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2875. self.app.ui.snap_magnet.setVisible(False)
  2876. self.app.ui.corner_snap_btn.setVisible(False)
  2877. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2878. self.app.ui.corner_snap_btn.setEnabled(False)
  2879. # set the Editor Toolbar visibility to what was before entering in the Editor
  2880. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2881. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2882. # Disable visuals
  2883. self.shapes.enabled = False
  2884. self.tool_shape.enabled = False
  2885. self.app.app_cursor.enabled = False
  2886. self.app.ui.geo_editor_menu.setDisabled(True)
  2887. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2888. self.app.ui.update_obj_btn.setEnabled(False)
  2889. self.app.ui.g_editor_cmenu.setEnabled(False)
  2890. self.app.ui.e_editor_cmenu.setEnabled(False)
  2891. # Tell the app that the editor is no longer active
  2892. self.editor_active = False
  2893. # Show original geometry
  2894. if self.fcgeometry:
  2895. self.fcgeometry.visible = True
  2896. def connect_canvas_event_handlers(self):
  2897. ## Canvas events
  2898. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2899. # but those from FlatCAMGeoEditor
  2900. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2901. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2902. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2903. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2904. self.app.collection.view.clicked.disconnect()
  2905. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2906. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2907. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  2908. def disconnect_canvas_event_handlers(self):
  2909. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2910. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2911. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  2912. # we restore the key and mouse control to FlatCAMApp method
  2913. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2914. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2915. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2916. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2917. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2918. def add_shape(self, shape):
  2919. """
  2920. Adds a shape to the shape storage.
  2921. :param shape: Shape to be added.
  2922. :type shape: DrawToolShape
  2923. :return: None
  2924. """
  2925. # List of DrawToolShape?
  2926. if isinstance(shape, list):
  2927. for subshape in shape:
  2928. self.add_shape(subshape)
  2929. return
  2930. assert isinstance(shape, DrawToolShape), \
  2931. "Expected a DrawToolShape, got %s" % type(shape)
  2932. assert shape.geo is not None, \
  2933. "Shape object has empty geometry (None)"
  2934. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2935. not isinstance(shape.geo, list), \
  2936. "Shape objects has empty geometry ([])"
  2937. if isinstance(shape, DrawToolUtilityShape):
  2938. self.utility.append(shape)
  2939. else:
  2940. self.storage.insert(shape) # TODO: Check performance
  2941. def delete_utility_geometry(self):
  2942. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2943. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2944. for_deletion = [shape for shape in self.utility]
  2945. for shape in for_deletion:
  2946. self.delete_shape(shape)
  2947. self.tool_shape.clear(update=True)
  2948. self.tool_shape.redraw()
  2949. def cutpath(self):
  2950. selected = self.get_selected()
  2951. tools = selected[1:]
  2952. toolgeo = cascaded_union([shp.geo for shp in tools])
  2953. target = selected[0]
  2954. if type(target.geo) == Polygon:
  2955. for ring in poly2rings(target.geo):
  2956. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2957. self.delete_shape(target)
  2958. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2959. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2960. self.delete_shape(target)
  2961. elif type(target.geo) == MultiLineString:
  2962. try:
  2963. for linestring in target.geo:
  2964. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2965. except:
  2966. self.app.log.warning("Current LinearString does not intersect the target")
  2967. self.delete_shape(target)
  2968. else:
  2969. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2970. self.replot()
  2971. def toolbar_tool_toggle(self, key):
  2972. self.options[key] = self.sender().isChecked()
  2973. if self.options[key] == True:
  2974. return 1
  2975. else:
  2976. return 0
  2977. def clear(self):
  2978. self.active_tool = None
  2979. # self.shape_buffer = []
  2980. self.selected = []
  2981. self.shapes.clear(update=True)
  2982. self.tool_shape.clear(update=True)
  2983. self.storage = FlatCAMGeoEditor.make_storage()
  2984. self.replot()
  2985. def edit_fcgeometry(self, fcgeometry):
  2986. """
  2987. Imports the geometry from the given FlatCAM Geometry object
  2988. into the editor.
  2989. :param fcgeometry: FlatCAMGeometry
  2990. :return: None
  2991. """
  2992. assert isinstance(fcgeometry, Geometry), \
  2993. "Expected a Geometry, got %s" % type(fcgeometry)
  2994. self.deactivate()
  2995. self.activate()
  2996. # Hide original geometry
  2997. self.fcgeometry = fcgeometry
  2998. fcgeometry.visible = False
  2999. # Set selection tolerance
  3000. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3001. self.select_tool("select")
  3002. # Link shapes into editor.
  3003. for shape in fcgeometry.flatten():
  3004. if shape is not None: # TODO: Make flatten never create a None
  3005. if type(shape) == Polygon:
  3006. self.add_shape(DrawToolShape(shape.exterior))
  3007. for inter in shape.interiors:
  3008. self.add_shape(DrawToolShape(inter))
  3009. else:
  3010. self.add_shape(DrawToolShape(shape))
  3011. self.replot()
  3012. # start with GRID toolbar activated
  3013. if self.app.ui.grid_snap_btn.isChecked() == False:
  3014. self.app.ui.grid_snap_btn.trigger()
  3015. def on_buffer_tool(self):
  3016. buff_tool = BufferSelectionTool(self.app, self)
  3017. buff_tool.run()
  3018. def on_paint_tool(self):
  3019. paint_tool = PaintOptionsTool(self.app, self)
  3020. paint_tool.run()
  3021. def on_transform_tool(self):
  3022. transform_tool = TransformEditorTool(self.app, self)
  3023. transform_tool.run()
  3024. def on_tool_select(self, tool):
  3025. """
  3026. Behavior of the toolbar. Tool initialization.
  3027. :rtype : None
  3028. """
  3029. self.app.log.debug("on_tool_select('%s')" % tool)
  3030. # This is to make the group behave as radio group
  3031. if tool in self.tools:
  3032. if self.tools[tool]["button"].isChecked():
  3033. self.app.log.debug("%s is checked." % tool)
  3034. for t in self.tools:
  3035. if t != tool:
  3036. self.tools[t]["button"].setChecked(False)
  3037. self.active_tool = self.tools[tool]["constructor"](self)
  3038. if not isinstance(self.active_tool, FCSelect):
  3039. self.app.inform.emit(self.active_tool.start_msg)
  3040. else:
  3041. self.app.log.debug("%s is NOT checked." % tool)
  3042. for t in self.tools:
  3043. self.tools[t]["button"].setChecked(False)
  3044. self.active_tool = None
  3045. def draw_tool_path(self):
  3046. self.select_tool('path')
  3047. return
  3048. def draw_tool_rectangle(self):
  3049. self.select_tool('rectangle')
  3050. return
  3051. def on_grid_toggled(self):
  3052. self.toolbar_tool_toggle("grid_snap")
  3053. # make sure that the cursor shape is enabled/disabled, too
  3054. if self.options['grid_snap'] is True:
  3055. self.app.app_cursor.enabled = True
  3056. else:
  3057. self.app.app_cursor.enabled = False
  3058. def on_canvas_click(self, event):
  3059. """
  3060. event.x and .y have canvas coordinates
  3061. event.xdaya and .ydata have plot coordinates
  3062. :param event: Event object dispatched by Matplotlib
  3063. :return: None
  3064. """
  3065. if event.button is 1:
  3066. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3067. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3068. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3069. ### Snap coordinates
  3070. x, y = self.snap(self.pos[0], self.pos[1])
  3071. self.pos = (x, y)
  3072. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3073. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3074. if modifiers == QtCore.Qt.ShiftModifier:
  3075. self.app.clipboard.setText(
  3076. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3077. return
  3078. # Selection with left mouse button
  3079. if self.active_tool is not None and event.button is 1:
  3080. # Dispatch event to active_tool
  3081. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3082. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3083. # If it is a shape generating tool
  3084. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3085. self.on_shape_complete()
  3086. # MS: always return to the Select Tool if modifier key is not pressed
  3087. # else return to the current tool
  3088. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3089. if self.app.defaults["global_mselect_key"] == 'Control':
  3090. modifier_to_use = Qt.ControlModifier
  3091. else:
  3092. modifier_to_use = Qt.ShiftModifier
  3093. # if modifier key is pressed then we add to the selected list the current shape but if
  3094. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  3095. if key_modifier == modifier_to_use:
  3096. self.select_tool(self.active_tool.name)
  3097. else:
  3098. self.select_tool("select")
  3099. return
  3100. if isinstance(self.active_tool, FCSelect):
  3101. # self.app.log.debug("Replotting after click.")
  3102. self.replot()
  3103. else:
  3104. self.app.log.debug("No active tool to respond to click!")
  3105. def on_canvas_move(self, event):
  3106. """
  3107. Called on 'mouse_move' event
  3108. event.pos have canvas screen coordinates
  3109. :param event: Event object dispatched by VisPy SceneCavas
  3110. :return: None
  3111. """
  3112. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3113. event.xdata, event.ydata = pos[0], pos[1]
  3114. self.x = event.xdata
  3115. self.y = event.ydata
  3116. # Prevent updates on pan
  3117. # if len(event.buttons) > 0:
  3118. # return
  3119. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3120. if event.button == 2:
  3121. self.app.panning_action = True
  3122. return
  3123. else:
  3124. self.app.panning_action = False
  3125. try:
  3126. x = float(event.xdata)
  3127. y = float(event.ydata)
  3128. except TypeError:
  3129. return
  3130. if self.active_tool is None:
  3131. return
  3132. ### Snap coordinates
  3133. x, y = self.snap(x, y)
  3134. self.snap_x = x
  3135. self.snap_y = y
  3136. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3137. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3138. "<b>Y</b>: %.4f" % (x, y))
  3139. if self.pos is None:
  3140. self.pos = (0, 0)
  3141. dx = x - self.pos[0]
  3142. dy = y - self.pos[1]
  3143. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3144. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3145. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3146. ### Utility geometry (animated)
  3147. geo = self.active_tool.utility_geometry(data=(x, y))
  3148. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3149. # Remove any previous utility shape
  3150. self.tool_shape.clear(update=True)
  3151. self.draw_utility_geometry(geo=geo)
  3152. ### Selection area on canvas section ###
  3153. dx = pos[0] - self.pos[0]
  3154. if event.is_dragging == 1 and event.button == 1:
  3155. self.app.delete_selection_shape()
  3156. if dx < 0:
  3157. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  3158. color=self.app.defaults["global_alt_sel_line"],
  3159. face_color=self.app.defaults['global_alt_sel_fill'])
  3160. self.app.selection_type = False
  3161. else:
  3162. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  3163. self.app.selection_type = True
  3164. else:
  3165. self.app.selection_type = None
  3166. # Update cursor
  3167. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  3168. def on_canvas_click_release(self, event):
  3169. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  3170. if self.app.grid_status():
  3171. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3172. else:
  3173. pos = (pos_canvas[0], pos_canvas[1])
  3174. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3175. # canvas menu
  3176. try:
  3177. if event.button == 2: # right click
  3178. if self.app.panning_action is True:
  3179. self.app.panning_action = False
  3180. else:
  3181. if self.in_action is False:
  3182. self.app.cursor = QtGui.QCursor()
  3183. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3184. else:
  3185. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3186. # right mouse click will finish the action
  3187. if isinstance(self.active_tool, FCShapeTool):
  3188. self.active_tool.click(self.snap(self.x, self.y))
  3189. self.active_tool.make()
  3190. if self.active_tool.complete:
  3191. self.on_shape_complete()
  3192. self.app.inform.emit(_("[success]Done."))
  3193. # MS: always return to the Select Tool if modifier key is not pressed
  3194. # else return to the current tool
  3195. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3196. if self.app.defaults["global_mselect_key"] == 'Control':
  3197. modifier_to_use = Qt.ControlModifier
  3198. else:
  3199. modifier_to_use = Qt.ShiftModifier
  3200. if key_modifier == modifier_to_use:
  3201. self.select_tool(self.active_tool.name)
  3202. else:
  3203. self.select_tool("select")
  3204. except Exception as e:
  3205. log.warning("Error: %s" % str(e))
  3206. return
  3207. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3208. # selection and then select a type of selection ("enclosing" or "touching")
  3209. try:
  3210. if event.button == 1: # left click
  3211. if self.app.selection_type is not None:
  3212. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3213. self.app.selection_type = None
  3214. elif isinstance(self.active_tool, FCSelect):
  3215. # Dispatch event to active_tool
  3216. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3217. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  3218. # self.app.inform.emit(msg)
  3219. self.replot()
  3220. except Exception as e:
  3221. log.warning("Error: %s" % str(e))
  3222. return
  3223. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3224. """
  3225. :param start_pos: mouse position when the selection LMB click was done
  3226. :param end_pos: mouse position when the left mouse button is released
  3227. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3228. :type Bool
  3229. :return:
  3230. """
  3231. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3232. self.app.delete_selection_shape()
  3233. for obj in self.storage.get_objects():
  3234. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  3235. (sel_type is False and poly_selection.intersects(obj.geo)):
  3236. if self.key == self.app.defaults["global_mselect_key"]:
  3237. if obj in self.selected:
  3238. self.selected.remove(obj)
  3239. else:
  3240. # add the object to the selected shapes
  3241. self.selected.append(obj)
  3242. else:
  3243. if obj not in self.selected:
  3244. self.selected.append(obj)
  3245. self.replot()
  3246. def draw_utility_geometry(self, geo):
  3247. # Add the new utility shape
  3248. try:
  3249. # this case is for the Font Parse
  3250. for el in list(geo.geo):
  3251. if type(el) == MultiPolygon:
  3252. for poly in el:
  3253. self.tool_shape.add(
  3254. shape=poly,
  3255. color=(self.app.defaults["global_draw_color"] + '80'),
  3256. update=False,
  3257. layer=0,
  3258. tolerance=None
  3259. )
  3260. elif type(el) == MultiLineString:
  3261. for linestring in el:
  3262. self.tool_shape.add(
  3263. shape=linestring,
  3264. color=(self.app.defaults["global_draw_color"] + '80'),
  3265. update=False,
  3266. layer=0,
  3267. tolerance=None
  3268. )
  3269. else:
  3270. self.tool_shape.add(
  3271. shape=el,
  3272. color=(self.app.defaults["global_draw_color"] + '80'),
  3273. update=False,
  3274. layer=0,
  3275. tolerance=None
  3276. )
  3277. except TypeError:
  3278. self.tool_shape.add(
  3279. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3280. update=False, layer=0, tolerance=None)
  3281. self.tool_shape.redraw()
  3282. def on_delete_btn(self):
  3283. self.delete_selected()
  3284. self.replot()
  3285. def delete_selected(self):
  3286. tempref = [s for s in self.selected]
  3287. for shape in tempref:
  3288. self.delete_shape(shape)
  3289. self.selected = []
  3290. def delete_shape(self, shape):
  3291. if shape in self.utility:
  3292. self.utility.remove(shape)
  3293. return
  3294. self.storage.remove(shape)
  3295. if shape in self.selected:
  3296. self.selected.remove(shape) # TODO: Check performance
  3297. def on_move(self):
  3298. self.app.ui.geo_move_btn.setChecked(True)
  3299. self.on_tool_select('move')
  3300. def on_move_click(self):
  3301. if not self.selected:
  3302. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3303. return
  3304. self.on_move()
  3305. self.active_tool.set_origin(self.snap(self.x, self.y))
  3306. def on_copy_click(self):
  3307. if not self.selected:
  3308. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3309. return
  3310. self.app.ui.geo_copy_btn.setChecked(True)
  3311. self.app.geo_editor.on_tool_select('copy')
  3312. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3313. self.app.geo_editor.x, self.app.geo_editor.y))
  3314. self.app.inform.emit(_("Click on target point."))
  3315. def on_corner_snap(self):
  3316. self.app.ui.corner_snap_btn.trigger()
  3317. def get_selected(self):
  3318. """
  3319. Returns list of shapes that are selected in the editor.
  3320. :return: List of shapes.
  3321. """
  3322. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3323. return self.selected
  3324. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3325. """
  3326. Plots a geometric object or list of objects without rendering. Plotted objects
  3327. are returned as a list. This allows for efficient/animated rendering.
  3328. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3329. :param color: Shape color
  3330. :param linewidth: Width of lines in # of pixels.
  3331. :return: List of plotted elements.
  3332. """
  3333. plot_elements = []
  3334. if geometry is None:
  3335. geometry = self.active_tool.geometry
  3336. try:
  3337. for geo in geometry:
  3338. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3339. ## Non-iterable
  3340. except TypeError:
  3341. ## DrawToolShape
  3342. if isinstance(geometry, DrawToolShape):
  3343. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3344. ## Polygon: Descend into exterior and each interior.
  3345. if type(geometry) == Polygon:
  3346. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3347. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3348. if type(geometry) == LineString or type(geometry) == LinearRing:
  3349. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3350. tolerance=self.fcgeometry.drawing_tolerance))
  3351. if type(geometry) == Point:
  3352. pass
  3353. return plot_elements
  3354. def plot_all(self):
  3355. """
  3356. Plots all shapes in the editor.
  3357. :return: None
  3358. :rtype: None
  3359. """
  3360. # self.app.log.debug("plot_all()")
  3361. self.shapes.clear(update=True)
  3362. for shape in self.storage.get_objects():
  3363. if shape.geo is None: # TODO: This shouldn't have happened
  3364. continue
  3365. if shape in self.selected:
  3366. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3367. continue
  3368. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3369. for shape in self.utility:
  3370. self.plot_shape(geometry=shape.geo, linewidth=1)
  3371. continue
  3372. self.shapes.redraw()
  3373. def replot(self):
  3374. self.plot_all()
  3375. def on_shape_complete(self):
  3376. self.app.log.debug("on_shape_complete()")
  3377. # Add shape
  3378. self.add_shape(self.active_tool.geometry)
  3379. # Remove any utility shapes
  3380. self.delete_utility_geometry()
  3381. self.tool_shape.clear(update=True)
  3382. # Replot and reset tool.
  3383. self.replot()
  3384. # self.active_tool = type(self.active_tool)(self)
  3385. @staticmethod
  3386. def make_storage():
  3387. ## Shape storage.
  3388. storage = FlatCAMRTreeStorage()
  3389. storage.get_points = DrawToolShape.get_pts
  3390. return storage
  3391. def select_tool(self, toolname):
  3392. """
  3393. Selects a drawing tool. Impacts the object and GUI.
  3394. :param toolname: Name of the tool.
  3395. :return: None
  3396. """
  3397. self.tools[toolname]["button"].setChecked(True)
  3398. self.on_tool_select(toolname)
  3399. def set_selected(self, shape):
  3400. # Remove and add to the end.
  3401. if shape in self.selected:
  3402. self.selected.remove(shape)
  3403. self.selected.append(shape)
  3404. def set_unselected(self, shape):
  3405. if shape in self.selected:
  3406. self.selected.remove(shape)
  3407. def snap(self, x, y):
  3408. """
  3409. Adjusts coordinates to snap settings.
  3410. :param x: Input coordinate X
  3411. :param y: Input coordinate Y
  3412. :return: Snapped (x, y)
  3413. """
  3414. snap_x, snap_y = (x, y)
  3415. snap_distance = Inf
  3416. ### Object (corner?) snap
  3417. ### No need for the objects, just the coordinates
  3418. ### in the index.
  3419. if self.options["corner_snap"]:
  3420. try:
  3421. nearest_pt, shape = self.storage.nearest((x, y))
  3422. nearest_pt_distance = distance((x, y), nearest_pt)
  3423. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3424. snap_distance = nearest_pt_distance
  3425. snap_x, snap_y = nearest_pt
  3426. except (StopIteration, AssertionError):
  3427. pass
  3428. ### Grid snap
  3429. if self.options["grid_snap"]:
  3430. if self.options["global_gridx"] != 0:
  3431. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3432. else:
  3433. snap_x_ = x
  3434. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3435. # and it will use the snap distance from GridX entry
  3436. if self.app.ui.grid_gap_link_cb.isChecked():
  3437. if self.options["global_gridx"] != 0:
  3438. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3439. else:
  3440. snap_y_ = y
  3441. else:
  3442. if self.options["global_gridy"] != 0:
  3443. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3444. else:
  3445. snap_y_ = y
  3446. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3447. if nearest_grid_distance < snap_distance:
  3448. snap_x, snap_y = (snap_x_, snap_y_)
  3449. return snap_x, snap_y
  3450. def update_fcgeometry(self, fcgeometry):
  3451. """
  3452. Transfers the geometry tool shape buffer to the selected geometry
  3453. object. The geometry already in the object are removed.
  3454. :param fcgeometry: FlatCAMGeometry
  3455. :return: None
  3456. """
  3457. fcgeometry.solid_geometry = []
  3458. # for shape in self.shape_buffer:
  3459. for shape in self.storage.get_objects():
  3460. fcgeometry.solid_geometry.append(shape.geo)
  3461. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  3462. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  3463. for w in sel_tab_widget_list:
  3464. w.setEnabled(True)
  3465. def update_options(self, obj):
  3466. if self.paint_tooldia:
  3467. obj.options['cnctooldia'] = self.paint_tooldia
  3468. self.paint_tooldia = None
  3469. return True
  3470. else:
  3471. return False
  3472. def union(self):
  3473. """
  3474. Makes union of selected polygons. Original polygons
  3475. are deleted.
  3476. :return: None.
  3477. """
  3478. results = cascaded_union([t.geo for t in self.get_selected()])
  3479. # Delete originals.
  3480. for_deletion = [s for s in self.get_selected()]
  3481. for shape in for_deletion:
  3482. self.delete_shape(shape)
  3483. # Selected geometry is now gone!
  3484. self.selected = []
  3485. self.add_shape(DrawToolShape(results))
  3486. self.replot()
  3487. def intersection(self):
  3488. """
  3489. Makes intersectino of selected polygons. Original polygons are deleted.
  3490. :return: None
  3491. """
  3492. shapes = self.get_selected()
  3493. try:
  3494. results = shapes[0].geo
  3495. except Exception as e:
  3496. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3497. self.app.inform.emit(_("[WARNING_NOTCL]A selection of at least 2 geo items is required to do Intersection."))
  3498. self.select_tool('select')
  3499. return
  3500. for shape in shapes[1:]:
  3501. results = results.intersection(shape.geo)
  3502. # Delete originals.
  3503. for_deletion = [s for s in self.get_selected()]
  3504. for shape in for_deletion:
  3505. self.delete_shape(shape)
  3506. # Selected geometry is now gone!
  3507. self.selected = []
  3508. self.add_shape(DrawToolShape(results))
  3509. self.replot()
  3510. def subtract(self):
  3511. selected = self.get_selected()
  3512. try:
  3513. tools = selected[1:]
  3514. toolgeo = cascaded_union([shp.geo for shp in tools])
  3515. result = selected[0].geo.difference(toolgeo)
  3516. self.delete_shape(selected[0])
  3517. self.add_shape(DrawToolShape(result))
  3518. self.replot()
  3519. except Exception as e:
  3520. log.debug(str(e))
  3521. def buffer(self, buf_distance, join_style):
  3522. selected = self.get_selected()
  3523. if buf_distance < 0:
  3524. self.app.inform.emit(
  3525. _( "[ERROR_NOTCL]Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3526. # deselect everything
  3527. self.selected = []
  3528. self.replot()
  3529. return
  3530. if len(selected) == 0:
  3531. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3532. return
  3533. if not isinstance(buf_distance, float):
  3534. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3535. # deselect everything
  3536. self.selected = []
  3537. self.replot()
  3538. return
  3539. pre_buffer = cascaded_union([t.geo for t in selected])
  3540. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3541. if results.is_empty:
  3542. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3543. # deselect everything
  3544. self.selected = []
  3545. self.replot()
  3546. return
  3547. self.add_shape(DrawToolShape(results))
  3548. self.replot()
  3549. self.app.inform.emit(_("[success]Full buffer geometry created."))
  3550. def buffer_int(self, buf_distance, join_style):
  3551. selected = self.get_selected()
  3552. if buf_distance < 0:
  3553. self.app.inform.emit(
  3554. _("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3555. "Use Buffer interior to generate an 'inside' shape")
  3556. )
  3557. # deselect everything
  3558. self.selected = []
  3559. self.replot()
  3560. return
  3561. if len(selected) == 0:
  3562. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3563. return
  3564. if not isinstance(buf_distance, float):
  3565. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3566. # deselect everything
  3567. self.selected = []
  3568. self.replot()
  3569. return
  3570. pre_buffer = cascaded_union([t.geo for t in selected])
  3571. results = pre_buffer.buffer(-buf_distance + 1e-10, resolution=32, join_style=join_style)
  3572. if results.is_empty:
  3573. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a smaller buffer value."))
  3574. # deselect everything
  3575. self.selected = []
  3576. self.replot()
  3577. return
  3578. if type(results) == MultiPolygon:
  3579. for poly in results:
  3580. self.add_shape(DrawToolShape(poly.exterior))
  3581. else:
  3582. self.add_shape(DrawToolShape(results.exterior))
  3583. self.replot()
  3584. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3585. # selected = self.get_selected()
  3586. #
  3587. # if len(selected) == 0:
  3588. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3589. # return
  3590. #
  3591. # if not isinstance(buf_distance, float):
  3592. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3593. # return
  3594. #
  3595. # pre_buffer = cascaded_union([t.geo for t in selected])
  3596. # results = pre_buffer.buffer(buf_distance)
  3597. # if results.is_empty:
  3598. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3599. # return
  3600. #
  3601. # int_geo = []
  3602. # if type(results) == MultiPolygon:
  3603. # for poly in results:
  3604. # for g in poly.interiors:
  3605. # int_geo.append(g)
  3606. # res = cascaded_union(int_geo)
  3607. # self.add_shape(DrawToolShape(res))
  3608. # else:
  3609. # print(results.interiors)
  3610. # for g in results.interiors:
  3611. # int_geo.append(g)
  3612. # res = cascaded_union(int_geo)
  3613. # self.add_shape(DrawToolShape(res))
  3614. #
  3615. # self.replot()
  3616. # self.app.inform.emit("Interior buffer geometry created.")
  3617. def buffer_ext(self, buf_distance, join_style):
  3618. selected = self.get_selected()
  3619. if buf_distance < 0:
  3620. self.app.inform.emit(_("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3621. "Use Buffer interior to generate an 'inside' shape"))
  3622. # deselect everything
  3623. self.selected = []
  3624. self.replot()
  3625. return
  3626. if len(selected) == 0:
  3627. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3628. return
  3629. if not isinstance(buf_distance, float):
  3630. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3631. # deselect everything
  3632. self.selected = []
  3633. self.replot()
  3634. return
  3635. pre_buffer = cascaded_union([t.geo for t in selected])
  3636. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3637. if results.is_empty:
  3638. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3639. # deselect everything
  3640. self.selected = []
  3641. self.replot()
  3642. return
  3643. if type(results) == MultiPolygon:
  3644. for poly in results:
  3645. self.add_shape(DrawToolShape(poly.exterior))
  3646. else:
  3647. self.add_shape(DrawToolShape(results.exterior))
  3648. self.replot()
  3649. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3650. # def paint(self, tooldia, overlap, margin, method):
  3651. # selected = self.get_selected()
  3652. #
  3653. # if len(selected) == 0:
  3654. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3655. # return
  3656. #
  3657. # for param in [tooldia, overlap, margin]:
  3658. # if not isinstance(param, float):
  3659. # param_name = [k for k, v in locals().items() if v is param][0]
  3660. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3661. #
  3662. # # Todo: Check for valid method.
  3663. #
  3664. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3665. #
  3666. # results = []
  3667. #
  3668. # def recurse(geo):
  3669. # try:
  3670. # for subg in geo:
  3671. # for subsubg in recurse(subg):
  3672. # yield subsubg
  3673. # except TypeError:
  3674. # if isinstance(geo, LinearRing):
  3675. # yield geo
  3676. #
  3677. # raise StopIteration
  3678. #
  3679. # for geo in selected:
  3680. # print(type(geo.geo))
  3681. #
  3682. # local_results = []
  3683. # for poly in recurse(geo.geo):
  3684. # if method == "seed":
  3685. # # Type(cp) == FlatCAMRTreeStorage | None
  3686. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3687. # tooldia, overlap=overlap)
  3688. #
  3689. # else:
  3690. # # Type(cp) == FlatCAMRTreeStorage | None
  3691. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3692. # tooldia, overlap=overlap)
  3693. #
  3694. # if cp is not None:
  3695. # local_results += list(cp.get_objects())
  3696. #
  3697. # results.append(cascaded_union(local_results))
  3698. #
  3699. # # This is a dirty patch:
  3700. # for r in results:
  3701. # self.add_shape(DrawToolShape(r))
  3702. #
  3703. # self.replot()
  3704. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3705. self.paint_tooldia = tooldia
  3706. selected = self.get_selected()
  3707. if len(selected) == 0:
  3708. self.app.inform.emit(_("[WARNING_NOTCL]Nothing selected for painting."))
  3709. return
  3710. for param in [tooldia, overlap, margin]:
  3711. if not isinstance(param, float):
  3712. param_name = [k for k, v in locals().items() if v is param][0]
  3713. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3714. results = []
  3715. if overlap >= 1:
  3716. self.app.inform.emit(
  3717. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3718. return
  3719. def recurse(geometry, reset=True):
  3720. """
  3721. Creates a list of non-iterable linear geometry objects.
  3722. Results are placed in self.flat_geometry
  3723. :param geometry: Shapely type or list or list of list of such.
  3724. :param reset: Clears the contents of self.flat_geometry.
  3725. """
  3726. if geometry is None:
  3727. return
  3728. if reset:
  3729. self.flat_geo = []
  3730. ## If iterable, expand recursively.
  3731. try:
  3732. for geo in geometry:
  3733. if geo is not None:
  3734. recurse(geometry=geo, reset=False)
  3735. ## Not iterable, do the actual indexing and add.
  3736. except TypeError:
  3737. self.flat_geo.append(geometry)
  3738. return self.flat_geo
  3739. for geo in selected:
  3740. local_results = []
  3741. for geo_obj in recurse(geo.geo):
  3742. try:
  3743. if type(geo_obj) == Polygon:
  3744. poly_buf = geo_obj.buffer(-margin)
  3745. else:
  3746. poly_buf = Polygon(geo_obj).buffer(-margin)
  3747. if method == "seed":
  3748. cp = Geometry.clear_polygon2(poly_buf,
  3749. tooldia, self.app.defaults["geometry_circle_steps"],
  3750. overlap=overlap, contour=contour, connect=connect)
  3751. elif method == "lines":
  3752. cp = Geometry.clear_polygon3(poly_buf,
  3753. tooldia, self.app.defaults["geometry_circle_steps"],
  3754. overlap=overlap, contour=contour, connect=connect)
  3755. else:
  3756. cp = Geometry.clear_polygon(poly_buf,
  3757. tooldia, self.app.defaults["geometry_circle_steps"],
  3758. overlap=overlap, contour=contour, connect=connect)
  3759. if cp is not None:
  3760. local_results += list(cp.get_objects())
  3761. except Exception as e:
  3762. log.debug("Could not Paint the polygons. %s" % str(e))
  3763. self.app.inform.emit(
  3764. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3765. "Or a different method of Paint\n%s") % str(e))
  3766. return
  3767. # add the result to the results list
  3768. results.append(cascaded_union(local_results))
  3769. # This is a dirty patch:
  3770. for r in results:
  3771. self.add_shape(DrawToolShape(r))
  3772. self.app.inform.emit(
  3773. _("[success] Paint done."))
  3774. self.replot()
  3775. class FlatCAMExcEditor(QtCore.QObject):
  3776. draw_shape_idx = -1
  3777. def __init__(self, app):
  3778. assert isinstance(app, FlatCAMApp.App), \
  3779. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  3780. super(FlatCAMExcEditor, self).__init__()
  3781. self.app = app
  3782. self.canvas = self.app.plotcanvas
  3783. self.exc_edit_widget = QtWidgets.QWidget()
  3784. layout = QtWidgets.QVBoxLayout()
  3785. self.exc_edit_widget.setLayout(layout)
  3786. ## Page Title box (spacing between children)
  3787. self.title_box = QtWidgets.QHBoxLayout()
  3788. layout.addLayout(self.title_box)
  3789. ## Page Title icon
  3790. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  3791. self.icon = QtWidgets.QLabel()
  3792. self.icon.setPixmap(pixmap)
  3793. self.title_box.addWidget(self.icon, stretch=0)
  3794. ## Title label
  3795. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  3796. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  3797. self.title_box.addWidget(self.title_label, stretch=1)
  3798. ## Object name
  3799. self.name_box = QtWidgets.QHBoxLayout()
  3800. layout.addLayout(self.name_box)
  3801. name_label = QtWidgets.QLabel(_("Name:"))
  3802. self.name_box.addWidget(name_label)
  3803. self.name_entry = FCEntry()
  3804. self.name_box.addWidget(self.name_entry)
  3805. ## Box box for custom widgets
  3806. # This gets populated in offspring implementations.
  3807. self.custom_box = QtWidgets.QVBoxLayout()
  3808. layout.addLayout(self.custom_box)
  3809. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3810. # this way I can hide/show the frame
  3811. self.drills_frame = QtWidgets.QFrame()
  3812. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  3813. self.custom_box.addWidget(self.drills_frame)
  3814. self.tools_box = QtWidgets.QVBoxLayout()
  3815. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3816. self.drills_frame.setLayout(self.tools_box)
  3817. #### Tools Drills ####
  3818. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  3819. self.tools_table_label.setToolTip(
  3820. _( "Tools in this Excellon object\n"
  3821. "when are used for drilling.")
  3822. )
  3823. self.tools_box.addWidget(self.tools_table_label)
  3824. self.tools_table_exc = FCTable()
  3825. self.tools_box.addWidget(self.tools_table_exc)
  3826. self.tools_table_exc.setColumnCount(4)
  3827. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  3828. self.tools_table_exc.setSortingEnabled(False)
  3829. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3830. self.empty_label = QtWidgets.QLabel('')
  3831. self.tools_box.addWidget(self.empty_label)
  3832. #### Add a new Tool ####
  3833. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  3834. self.addtool_label.setToolTip(
  3835. _("Add/Delete a tool to the tool list\n"
  3836. "for this Excellon object.")
  3837. )
  3838. self.tools_box.addWidget(self.addtool_label)
  3839. grid1 = QtWidgets.QGridLayout()
  3840. self.tools_box.addLayout(grid1)
  3841. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  3842. addtool_entry_lbl.setToolTip(
  3843. _("Diameter for the new tool")
  3844. )
  3845. grid1.addWidget(addtool_entry_lbl, 0, 0)
  3846. hlay = QtWidgets.QHBoxLayout()
  3847. self.addtool_entry = FCEntry()
  3848. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  3849. hlay.addWidget(self.addtool_entry)
  3850. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  3851. self.addtool_btn.setToolTip(
  3852. _( "Add a new tool to the tool list\n"
  3853. "with the diameter specified above.")
  3854. )
  3855. self.addtool_btn.setFixedWidth(80)
  3856. hlay.addWidget(self.addtool_btn)
  3857. grid1.addLayout(hlay, 0, 1)
  3858. grid2 = QtWidgets.QGridLayout()
  3859. self.tools_box.addLayout(grid2)
  3860. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  3861. self.deltool_btn.setToolTip(
  3862. _( "Delete a tool in the tool list\n"
  3863. "by selecting a row in the tool table.")
  3864. )
  3865. grid2.addWidget(self.deltool_btn, 0, 1)
  3866. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3867. # this way I can hide/show the frame
  3868. self.resize_frame = QtWidgets.QFrame()
  3869. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  3870. self.tools_box.addWidget(self.resize_frame)
  3871. self.resize_box = QtWidgets.QVBoxLayout()
  3872. self.resize_box.setContentsMargins(0, 0, 0, 0)
  3873. self.resize_frame.setLayout(self.resize_box)
  3874. #### Resize a drill ####
  3875. self.emptyresize_label = QtWidgets.QLabel('')
  3876. self.resize_box.addWidget(self.emptyresize_label)
  3877. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  3878. self.drillresize_label.setToolTip(
  3879. _("Resize a drill or a selection of drills.")
  3880. )
  3881. self.resize_box.addWidget(self.drillresize_label)
  3882. grid3 = QtWidgets.QGridLayout()
  3883. self.resize_box.addLayout(grid3)
  3884. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  3885. res_entry_lbl.setToolTip(
  3886. _( "Diameter to resize to.")
  3887. )
  3888. grid3.addWidget(addtool_entry_lbl, 0, 0)
  3889. hlay2 = QtWidgets.QHBoxLayout()
  3890. self.resdrill_entry = LengthEntry()
  3891. hlay2.addWidget(self.resdrill_entry)
  3892. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  3893. self.resize_btn.setToolTip(
  3894. _("Resize drill(s)")
  3895. )
  3896. self.resize_btn.setFixedWidth(80)
  3897. hlay2.addWidget(self.resize_btn)
  3898. grid3.addLayout(hlay2, 0, 1)
  3899. self.resize_frame.hide()
  3900. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  3901. # all the add drill array widgets
  3902. # this way I can hide/show the frame
  3903. self.array_frame = QtWidgets.QFrame()
  3904. self.array_frame.setContentsMargins(0, 0, 0, 0)
  3905. self.tools_box.addWidget(self.array_frame)
  3906. self.array_box = QtWidgets.QVBoxLayout()
  3907. self.array_box.setContentsMargins(0, 0, 0, 0)
  3908. self.array_frame.setLayout(self.array_box)
  3909. #### Add DRILL Array ####
  3910. self.emptyarray_label = QtWidgets.QLabel('')
  3911. self.array_box.addWidget(self.emptyarray_label)
  3912. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  3913. self.drillarray_label.setToolTip(
  3914. _("Add an array of drills (linear or circular array)")
  3915. )
  3916. self.array_box.addWidget(self.drillarray_label)
  3917. self.array_type_combo = FCComboBox()
  3918. self.array_type_combo.setToolTip(
  3919. _( "Select the type of drills array to create.\n"
  3920. "It can be Linear X(Y) or Circular")
  3921. )
  3922. self.array_type_combo.addItem(_("Linear"))
  3923. self.array_type_combo.addItem(_("Circular"))
  3924. self.array_box.addWidget(self.array_type_combo)
  3925. self.array_form = QtWidgets.QFormLayout()
  3926. self.array_box.addLayout(self.array_form)
  3927. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  3928. self.drill_array_size_label.setToolTip(
  3929. _("Specify how many drills to be in the array.")
  3930. )
  3931. self.drill_array_size_label.setFixedWidth(100)
  3932. self.drill_array_size_entry = LengthEntry()
  3933. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  3934. self.array_linear_frame = QtWidgets.QFrame()
  3935. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  3936. self.array_box.addWidget(self.array_linear_frame)
  3937. self.linear_box = QtWidgets.QVBoxLayout()
  3938. self.linear_box.setContentsMargins(0, 0, 0, 0)
  3939. self.array_linear_frame.setLayout(self.linear_box)
  3940. self.linear_form = QtWidgets.QFormLayout()
  3941. self.linear_box.addLayout(self.linear_form)
  3942. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  3943. self.drill_axis_label.setToolTip(
  3944. _("Direction on which the linear array is oriented:\n"
  3945. "- 'X' - horizontal axis \n"
  3946. "- 'Y' - vertical axis or \n"
  3947. "- 'Angle' - a custom angle for the array inclination")
  3948. )
  3949. self.drill_axis_label.setFixedWidth(100)
  3950. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  3951. {'label': 'Y', 'value': 'Y'},
  3952. {'label': _('Angle'), 'value': 'A'}])
  3953. self.drill_axis_radio.set_value('X')
  3954. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  3955. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  3956. self.drill_pitch_label.setToolTip(
  3957. _("Pitch = Distance between elements of the array.")
  3958. )
  3959. self.drill_pitch_label.setFixedWidth(100)
  3960. self.drill_pitch_entry = LengthEntry()
  3961. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  3962. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  3963. self.linear_angle_label.setToolTip(
  3964. _( "Angle at which the linear array is placed.\n"
  3965. "The precision is of max 2 decimals.\n"
  3966. "Min value is: -359.99 degrees.\n"
  3967. "Max value is: 360.00 degrees.")
  3968. )
  3969. self.linear_angle_label.setFixedWidth(100)
  3970. self.linear_angle_spinner = FCDoubleSpinner()
  3971. self.linear_angle_spinner.set_precision(2)
  3972. self.linear_angle_spinner.setRange(-359.99, 360.00)
  3973. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  3974. self.array_circular_frame = QtWidgets.QFrame()
  3975. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  3976. self.array_box.addWidget(self.array_circular_frame)
  3977. self.circular_box = QtWidgets.QVBoxLayout()
  3978. self.circular_box.setContentsMargins(0, 0, 0, 0)
  3979. self.array_circular_frame.setLayout(self.circular_box)
  3980. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  3981. self.drill_direction_label.setToolTip(
  3982. _( "Direction for circular array."
  3983. "Can be CW = clockwise or CCW = counter clockwise.")
  3984. )
  3985. self.drill_direction_label.setFixedWidth(100)
  3986. self.circular_form = QtWidgets.QFormLayout()
  3987. self.circular_box.addLayout(self.circular_form)
  3988. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  3989. {'label': 'CCW.', 'value': 'CCW'}])
  3990. self.drill_direction_radio.set_value('CW')
  3991. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  3992. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  3993. self.drill_angle_label.setToolTip(
  3994. _("Angle at which each element in circular array is placed.")
  3995. )
  3996. self.drill_angle_label.setFixedWidth(100)
  3997. self.drill_angle_entry = LengthEntry()
  3998. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  3999. self.array_circular_frame.hide()
  4000. self.linear_angle_spinner.hide()
  4001. self.linear_angle_label.hide()
  4002. self.array_frame.hide()
  4003. self.tools_box.addStretch()
  4004. ## Toolbar events and properties
  4005. self.tools_exc = {
  4006. "select": {"button": self.app.ui.select_drill_btn,
  4007. "constructor": FCDrillSelect},
  4008. "drill_add": {"button": self.app.ui.add_drill_btn,
  4009. "constructor": FCDrillAdd},
  4010. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  4011. "constructor": FCDrillArray},
  4012. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  4013. "constructor": FCDrillResize},
  4014. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  4015. "constructor": FCDrillCopy},
  4016. "drill_move": {"button": self.app.ui.move_drill_btn,
  4017. "constructor": FCDrillMove},
  4018. }
  4019. ### Data
  4020. self.active_tool = None
  4021. self.storage_dict = {}
  4022. self.current_storage = []
  4023. # build the data from the Excellon point into a dictionary
  4024. # {tool_dia: [geometry_in_points]}
  4025. self.points_edit = {}
  4026. self.sorted_diameters =[]
  4027. self.new_drills = []
  4028. self.new_tools = {}
  4029. self.new_slots = {}
  4030. self.new_tool_offset = {}
  4031. # dictionary to store the tool_row and diameters in Tool_table
  4032. # it will be updated everytime self.build_ui() is called
  4033. self.olddia_newdia = {}
  4034. self.tool2tooldia = {}
  4035. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  4036. # is cleared but as a side effect also the selected tool is cleared
  4037. self.last_tool_selected = None
  4038. self.utility = []
  4039. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  4040. self.launched_from_shortcuts = False
  4041. # this var will store the state of the toolbar before starting the editor
  4042. self.toolbar_old_state = False
  4043. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  4044. self.name_entry.returnPressed.connect(self.on_name_activate)
  4045. self.addtool_btn.clicked.connect(self.on_tool_add)
  4046. # self.addtool_entry.editingFinished.connect(self.on_tool_add)
  4047. self.deltool_btn.clicked.connect(self.on_tool_delete)
  4048. self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4049. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  4050. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  4051. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  4052. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  4053. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  4054. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  4055. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  4056. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  4057. # Init GUI
  4058. self.drill_array_size_entry.set_value(5)
  4059. self.drill_pitch_entry.set_value(2.54)
  4060. self.drill_angle_entry.set_value(12)
  4061. self.drill_direction_radio.set_value('CW')
  4062. self.drill_axis_radio.set_value('X')
  4063. self.exc_obj = None
  4064. # VisPy Visuals
  4065. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  4066. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  4067. self.app.pool_recreated.connect(self.pool_recreated)
  4068. # Remove from scene
  4069. self.shapes.enabled = False
  4070. self.tool_shape.enabled = False
  4071. ## List of selected shapes.
  4072. self.selected = []
  4073. self.move_timer = QtCore.QTimer()
  4074. self.move_timer.setSingleShot(True)
  4075. ## Current application units in Upper Case
  4076. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4077. self.key = None # Currently pressed key
  4078. self.modifiers = None
  4079. self.x = None # Current mouse cursor pos
  4080. self.y = None
  4081. # Current snapped mouse pos
  4082. self.snap_x = None
  4083. self.snap_y = None
  4084. self.pos = None
  4085. def make_callback(thetool):
  4086. def f():
  4087. self.on_tool_select(thetool)
  4088. return f
  4089. for tool in self.tools_exc:
  4090. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  4091. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  4092. self.options = {
  4093. "global_gridx": 0.1,
  4094. "global_gridy": 0.1,
  4095. "snap_max": 0.05,
  4096. "grid_snap": True,
  4097. "corner_snap": False,
  4098. "grid_gap_link": True
  4099. }
  4100. self.app.options_read_form()
  4101. for option in self.options:
  4102. if option in self.app.options:
  4103. self.options[option] = self.app.options[option]
  4104. self.rtree_exc_index = rtindex.Index()
  4105. # flag to show if the object was modified
  4106. self.is_modified = False
  4107. self.edited_obj_name = ""
  4108. # variable to store the total amount of drills per job
  4109. self.tot_drill_cnt = 0
  4110. self.tool_row = 0
  4111. # variable to store the total amount of slots per job
  4112. self.tot_slot_cnt = 0
  4113. self.tool_row_slots = 0
  4114. self.tool_row = 0
  4115. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4116. self.editor_active = False
  4117. def entry2option(option, entry):
  4118. self.options[option] = float(entry.text())
  4119. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4120. self.editor_active = False
  4121. def pool_recreated(self, pool):
  4122. self.shapes.pool = pool
  4123. self.tool_shape.pool = pool
  4124. @staticmethod
  4125. def make_storage():
  4126. ## Shape storage.
  4127. storage = FlatCAMRTreeStorage()
  4128. storage.get_points = DrawToolShape.get_pts
  4129. return storage
  4130. def set_ui(self):
  4131. # updated units
  4132. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4133. self.olddia_newdia.clear()
  4134. self.tool2tooldia.clear()
  4135. # build the self.points_edit dict {dimaters: [point_list]}
  4136. for drill in self.exc_obj.drills:
  4137. if drill['tool'] in self.exc_obj.tools:
  4138. if self.units == 'IN':
  4139. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  4140. else:
  4141. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  4142. try:
  4143. self.points_edit[tool_dia].append(drill['point'])
  4144. except KeyError:
  4145. self.points_edit[tool_dia] = [drill['point']]
  4146. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  4147. for key in self.points_edit:
  4148. self.olddia_newdia[key] = key
  4149. sort_temp = []
  4150. for diam in self.olddia_newdia:
  4151. sort_temp.append(float(diam))
  4152. self.sorted_diameters = sorted(sort_temp)
  4153. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  4154. for i in range(len(self.sorted_diameters)):
  4155. tt_dia = self.sorted_diameters[i]
  4156. self.tool2tooldia[i + 1] = tt_dia
  4157. def build_ui(self):
  4158. try:
  4159. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4160. self.tools_table_exc.itemChanged.disconnect()
  4161. except:
  4162. pass
  4163. # updated units
  4164. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4165. # make a new name for the new Excellon object (the one with edited content)
  4166. self.edited_obj_name = self.exc_obj.options['name']
  4167. self.name_entry.set_value(self.edited_obj_name)
  4168. if self.units == "IN":
  4169. self.addtool_entry.set_value(0.039)
  4170. else:
  4171. self.addtool_entry.set_value(1.00)
  4172. sort_temp = []
  4173. for diam in self.olddia_newdia:
  4174. sort_temp.append(float(diam))
  4175. self.sorted_diameters = sorted(sort_temp)
  4176. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  4177. n = len(self.sorted_diameters)
  4178. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  4179. self.tools_table_exc.setRowCount(n + 2)
  4180. self.tot_drill_cnt = 0
  4181. self.tot_slot_cnt = 0
  4182. self.tool_row = 0
  4183. # this variable will serve as the real tool_number
  4184. tool_id = 0
  4185. for tool_no in self.sorted_diameters:
  4186. tool_id += 1
  4187. drill_cnt = 0 # variable to store the nr of drills per tool
  4188. slot_cnt = 0 # variable to store the nr of slots per tool
  4189. # Find no of drills for the current tool
  4190. for tool_dia in self.points_edit:
  4191. if float(tool_dia) == tool_no:
  4192. drill_cnt = len(self.points_edit[tool_dia])
  4193. self.tot_drill_cnt += drill_cnt
  4194. try:
  4195. # Find no of slots for the current tool
  4196. for slot in self.slots:
  4197. if slot['tool'] == tool_no:
  4198. slot_cnt += 1
  4199. self.tot_slot_cnt += slot_cnt
  4200. except AttributeError:
  4201. # log.debug("No slots in the Excellon file")
  4202. # slot editing not implemented
  4203. pass
  4204. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  4205. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4206. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  4207. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  4208. # There are no drill bits in MM with more than 3 decimals diameter
  4209. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  4210. if self.units == 'MM':
  4211. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  4212. else:
  4213. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  4214. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  4215. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  4216. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4217. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  4218. if slot_cnt > 0:
  4219. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  4220. else:
  4221. slot_count = QtWidgets.QTableWidgetItem('')
  4222. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4223. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  4224. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  4225. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  4226. self.tool_row += 1
  4227. # make the diameter column editable
  4228. for row in range(self.tool_row):
  4229. self.tools_table_exc.item(row, 1).setFlags(
  4230. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4231. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  4232. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  4233. # add a last row with the Total number of drills
  4234. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  4235. # it will have to have the foreground color (font color) white
  4236. empty = QtWidgets.QTableWidgetItem('9998')
  4237. empty.setForeground(QtGui.QColor(255, 255, 255))
  4238. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  4239. empty_b = QtWidgets.QTableWidgetItem('')
  4240. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  4241. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  4242. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  4243. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4244. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4245. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  4246. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  4247. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  4248. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  4249. font = QtGui.QFont()
  4250. font.setBold(True)
  4251. font.setWeight(75)
  4252. for k in [1, 2]:
  4253. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  4254. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  4255. self.tool_row += 1
  4256. # add a last row with the Total number of slots
  4257. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  4258. # it will have to have the foreground color (font color) white
  4259. empty_2 = QtWidgets.QTableWidgetItem('9999')
  4260. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  4261. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  4262. empty_3 = QtWidgets.QTableWidgetItem('')
  4263. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  4264. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  4265. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  4266. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4267. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4268. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  4269. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  4270. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  4271. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  4272. for kl in [1, 2, 3]:
  4273. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  4274. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  4275. # all the tools are selected by default
  4276. self.tools_table_exc.selectColumn(0)
  4277. #
  4278. self.tools_table_exc.resizeColumnsToContents()
  4279. self.tools_table_exc.resizeRowsToContents()
  4280. vertical_header = self.tools_table_exc.verticalHeader()
  4281. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4282. vertical_header.hide()
  4283. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4284. horizontal_header = self.tools_table_exc.horizontalHeader()
  4285. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  4286. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4287. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  4288. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4289. # horizontal_header.setStretchLastSection(True)
  4290. # self.tools_table_exc.setSortingEnabled(True)
  4291. # sort by tool diameter
  4292. self.tools_table_exc.sortItems(1)
  4293. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  4294. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  4295. # use them
  4296. self.tool2tooldia.clear()
  4297. for row in range(self.tools_table_exc.rowCount() - 2):
  4298. tool = int(self.tools_table_exc.item(row, 0).text())
  4299. diameter = float(self.tools_table_exc.item(row, 1).text())
  4300. self.tool2tooldia[tool] = diameter
  4301. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  4302. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  4303. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  4304. self.tools_table_exc.clearSelection()
  4305. # Remove anything else in the GUI Selected Tab
  4306. self.app.ui.selected_scroll_area.takeWidget()
  4307. # Put ourself in the GUI Selected Tab
  4308. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  4309. # Switch notebook to Selected page
  4310. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4311. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  4312. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4313. def on_tool_add(self, tooldia=None):
  4314. self.is_modified = True
  4315. if tooldia:
  4316. tool_dia = tooldia
  4317. else:
  4318. try:
  4319. tool_dia = float(self.addtool_entry.get_value())
  4320. except ValueError:
  4321. # try to convert comma to decimal point. if it's still not working error message and return
  4322. try:
  4323. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  4324. except ValueError:
  4325. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  4326. "use a number.")
  4327. )
  4328. return
  4329. if tool_dia not in self.olddia_newdia:
  4330. storage_elem = FlatCAMGeoEditor.make_storage()
  4331. self.storage_dict[tool_dia] = storage_elem
  4332. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  4333. # each time a tool diameter is edited or added
  4334. self.olddia_newdia[tool_dia] = tool_dia
  4335. else:
  4336. self.app.inform.emit(_("[WARNING_NOTCL]Tool already in the original or actual tool list.\n"
  4337. "Save and reedit Excellon if you need to add this tool. ")
  4338. )
  4339. return
  4340. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  4341. # we add a new entry in the tool2tooldia dict
  4342. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  4343. self.app.inform.emit(_("[success]Added new tool with dia: %s %s") % (str(tool_dia), str(self.units)))
  4344. self.build_ui()
  4345. # make a quick sort through the tool2tooldia dict so we find which row to select
  4346. row_to_be_selected = None
  4347. for key in sorted(self.tool2tooldia):
  4348. if self.tool2tooldia[key] == tool_dia:
  4349. row_to_be_selected = int(key) - 1
  4350. break
  4351. self.tools_table_exc.selectRow(row_to_be_selected)
  4352. def on_tool_delete(self, dia=None):
  4353. self.is_modified = True
  4354. deleted_tool_dia_list = []
  4355. deleted_tool_offset_list = []
  4356. try:
  4357. if dia is None or dia is False:
  4358. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  4359. for index in self.tools_table_exc.selectionModel().selectedRows():
  4360. row = index.row()
  4361. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  4362. else:
  4363. if isinstance(dia, list):
  4364. for dd in dia:
  4365. deleted_tool_dia_list.append(float('%.4f' % dd))
  4366. else:
  4367. deleted_tool_dia_list.append(float('%.4f' % dia))
  4368. except:
  4369. self.app.inform.emit(_("[WARNING_NOTCL]Select a tool in Tool Table"))
  4370. return
  4371. for deleted_tool_dia in deleted_tool_dia_list:
  4372. # delete de tool offset
  4373. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  4374. # delete the storage used for that tool
  4375. storage_elem = FlatCAMGeoEditor.make_storage()
  4376. self.storage_dict[deleted_tool_dia] = storage_elem
  4377. self.storage_dict.pop(deleted_tool_dia, None)
  4378. # I've added this flag_del variable because dictionary don't like
  4379. # having keys deleted while iterating through them
  4380. flag_del = []
  4381. # self.points_edit.pop(deleted_tool_dia, None)
  4382. for deleted_tool in self.tool2tooldia:
  4383. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  4384. flag_del.append(deleted_tool)
  4385. if flag_del:
  4386. for tool_to_be_deleted in flag_del:
  4387. # delete the tool
  4388. self.tool2tooldia.pop(tool_to_be_deleted, None)
  4389. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  4390. # number of drills from before was deleter
  4391. self.points_edit[deleted_tool_dia] = []
  4392. flag_del = []
  4393. self.olddia_newdia.pop(deleted_tool_dia, None)
  4394. self.app.inform.emit(_("[success]Deleted tool with dia: %s %s") % (str(deleted_tool_dia), str(self.units)))
  4395. self.replot()
  4396. # self.app.inform.emit("Could not delete selected tool")
  4397. self.build_ui()
  4398. def on_tool_edit(self):
  4399. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4400. self.tools_table_exc.itemChanged.disconnect()
  4401. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  4402. self.is_modified = True
  4403. geometry = []
  4404. current_table_dia_edited = None
  4405. if self.tools_table_exc.currentItem() is not None:
  4406. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  4407. row_of_item_changed = self.tools_table_exc.currentRow()
  4408. # rows start with 0, tools start with 1 so we adjust the value by 1
  4409. key_in_tool2tooldia = row_of_item_changed + 1
  4410. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  4411. # tool diameter is not used so we create a new tool with the desired diameter
  4412. if current_table_dia_edited not in self.olddia_newdia.values():
  4413. # update the dict that holds as keys our initial diameters and as values the edited diameters
  4414. self.olddia_newdia[dia_changed] = current_table_dia_edited
  4415. # update the dict that holds tool_no as key and tool_dia as value
  4416. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  4417. # update the tool offset
  4418. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  4419. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  4420. self.replot()
  4421. else:
  4422. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  4423. factor = current_table_dia_edited / dia_changed
  4424. for shape in self.storage_dict[dia_changed].get_objects():
  4425. geometry.append(DrawToolShape(
  4426. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  4427. self.points_edit[current_table_dia_edited].append((0, 0))
  4428. self.add_exc_shape(geometry, self.storage_dict[current_table_dia_edited])
  4429. self.on_tool_delete(dia=dia_changed)
  4430. # delete the tool offset
  4431. self.exc_obj.tool_offset.pop(dia_changed, None)
  4432. # we reactivate the signals after the after the tool editing
  4433. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4434. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4435. def on_name_activate(self):
  4436. self.edited_obj_name = self.name_entry.get_value()
  4437. def activate(self):
  4438. self.connect_canvas_event_handlers()
  4439. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  4440. self.shapes.enabled = True
  4441. self.tool_shape.enabled = True
  4442. # self.app.app_cursor.enabled = True
  4443. self.app.ui.snap_max_dist_entry.setEnabled(True)
  4444. self.app.ui.corner_snap_btn.setEnabled(True)
  4445. self.app.ui.snap_magnet.setVisible(True)
  4446. self.app.ui.corner_snap_btn.setVisible(True)
  4447. self.app.ui.exc_editor_menu.setDisabled(False)
  4448. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  4449. self.app.ui.update_obj_btn.setEnabled(True)
  4450. self.app.ui.e_editor_cmenu.setEnabled(True)
  4451. self.app.ui.exc_edit_toolbar.setDisabled(False)
  4452. self.app.ui.exc_edit_toolbar.setVisible(True)
  4453. # self.app.ui.snap_toolbar.setDisabled(False)
  4454. # start with GRID toolbar activated
  4455. if self.app.ui.grid_snap_btn.isChecked() is False:
  4456. self.app.ui.grid_snap_btn.trigger()
  4457. # Tell the App that the editor is active
  4458. self.editor_active = True
  4459. def deactivate(self):
  4460. self.disconnect_canvas_event_handlers()
  4461. self.clear()
  4462. self.app.ui.exc_edit_toolbar.setDisabled(True)
  4463. settings = QSettings("Open Source", "FlatCAM")
  4464. if settings.contains("layout"):
  4465. layout = settings.value('layout', type=str)
  4466. if layout == 'standard':
  4467. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4468. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4469. self.app.ui.corner_snap_btn.setEnabled(False)
  4470. self.app.ui.snap_magnet.setVisible(False)
  4471. self.app.ui.corner_snap_btn.setVisible(False)
  4472. elif layout == 'compact':
  4473. # self.app.ui.exc_edit_toolbar.setVisible(True)
  4474. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4475. self.app.ui.corner_snap_btn.setEnabled(False)
  4476. self.app.ui.snap_magnet.setVisible(True)
  4477. self.app.ui.corner_snap_btn.setVisible(True)
  4478. else:
  4479. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4480. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4481. self.app.ui.corner_snap_btn.setEnabled(False)
  4482. self.app.ui.snap_magnet.setVisible(False)
  4483. self.app.ui.corner_snap_btn.setVisible(False)
  4484. # set the Editor Toolbar visibility to what was before entering in the Editor
  4485. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  4486. else self.app.ui.exc_edit_toolbar.setVisible(True)
  4487. # Disable visuals
  4488. self.shapes.enabled = False
  4489. self.tool_shape.enabled = False
  4490. # self.app.app_cursor.enabled = False
  4491. # Tell the app that the editor is no longer active
  4492. self.editor_active = False
  4493. self.app.ui.exc_editor_menu.setDisabled(True)
  4494. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  4495. self.app.ui.update_obj_btn.setEnabled(False)
  4496. self.app.ui.g_editor_cmenu.setEnabled(False)
  4497. self.app.ui.e_editor_cmenu.setEnabled(False)
  4498. # Show original geometry
  4499. if self.exc_obj:
  4500. self.exc_obj.visible = True
  4501. def connect_canvas_event_handlers(self):
  4502. ## Canvas events
  4503. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  4504. # but those from FlatCAMGeoEditor
  4505. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  4506. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  4507. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4508. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  4509. self.app.collection.view.clicked.disconnect()
  4510. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  4511. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  4512. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  4513. def disconnect_canvas_event_handlers(self):
  4514. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  4515. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  4516. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  4517. # we restore the key and mouse control to FlatCAMApp method
  4518. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  4519. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  4520. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4521. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  4522. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  4523. def clear(self):
  4524. self.active_tool = None
  4525. # self.shape_buffer = []
  4526. self.selected = []
  4527. self.points_edit = {}
  4528. self.new_tools = {}
  4529. self.new_drills = []
  4530. self.storage_dict = {}
  4531. self.shapes.clear(update=True)
  4532. self.tool_shape.clear(update=True)
  4533. # self.storage = FlatCAMExcEditor.make_storage()
  4534. self.replot()
  4535. def edit_fcexcellon(self, exc_obj):
  4536. """
  4537. Imports the geometry from the given FlatCAM Excellon object
  4538. into the editor.
  4539. :param fcgeometry: FlatCAMExcellon
  4540. :return: None
  4541. """
  4542. assert isinstance(exc_obj, Excellon), \
  4543. "Expected an Excellon Object, got %s" % type(exc_obj)
  4544. self.deactivate()
  4545. self.activate()
  4546. # Hide original geometry
  4547. self.exc_obj = exc_obj
  4548. exc_obj.visible = False
  4549. # Set selection tolerance
  4550. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  4551. self.select_tool("select")
  4552. self.set_ui()
  4553. # now that we hava data, create the GUI interface and add it to the Tool Tab
  4554. self.build_ui()
  4555. # we activate this after the initial build as we don't need to see the tool been populated
  4556. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4557. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  4558. # and then add it to the storage elements (each storage elements is a member of a list
  4559. for tool_dia in self.points_edit:
  4560. storage_elem = FlatCAMGeoEditor.make_storage()
  4561. for point in self.points_edit[tool_dia]:
  4562. # make a '+' sign, the line length is the tool diameter
  4563. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  4564. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  4565. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  4566. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  4567. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  4568. if shape is not None:
  4569. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  4570. self.storage_dict[tool_dia] = storage_elem
  4571. self.replot()
  4572. # add a first tool in the Tool Table but only if the Excellon Object is empty
  4573. if not self.tool2tooldia:
  4574. self.on_tool_add(tooldia=1.00)
  4575. def update_fcexcellon(self, exc_obj):
  4576. """
  4577. Create a new Excellon object that contain the edited content of the source Excellon object
  4578. :param exc_obj: FlatCAMExcellon
  4579. :return: None
  4580. """
  4581. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  4582. # the values of this dict are coordinates of the holes (drills)
  4583. edited_points = {}
  4584. for storage_tooldia in self.storage_dict:
  4585. for x in self.storage_dict[storage_tooldia].get_objects():
  4586. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  4587. # each MultiLineString is made out of Linestrings
  4588. # select first Linestring object in the current MultiLineString
  4589. first_linestring = x.geo[0]
  4590. # get it's coordinates
  4591. first_linestring_coords = first_linestring.coords
  4592. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  4593. y_coord = first_linestring_coords[0][1]
  4594. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  4595. # edited_points dictionary
  4596. point = (x_coord, y_coord)
  4597. if not storage_tooldia in edited_points:
  4598. edited_points[storage_tooldia] = [point]
  4599. else:
  4600. edited_points[storage_tooldia].append(point)
  4601. # recreate the drills and tools to be added to the new Excellon edited object
  4602. # first, we look in the tool table if one of the tool diameters was changed then
  4603. # append that a tuple formed by (old_dia, edited_dia) to a list
  4604. changed_key = []
  4605. for initial_dia in self.olddia_newdia:
  4606. edited_dia = self.olddia_newdia[initial_dia]
  4607. if edited_dia != initial_dia:
  4608. for old_dia in edited_points:
  4609. if old_dia == initial_dia:
  4610. changed_key.append((old_dia, edited_dia))
  4611. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  4612. # (and we have to add it)
  4613. # because in case we have drill points it will have to be already added in edited_points
  4614. # if initial_dia not in edited_points.keys():
  4615. # edited_points[initial_dia] = []
  4616. for el in changed_key:
  4617. edited_points[el[1]] = edited_points.pop(el[0])
  4618. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  4619. # ordered_edited_points is a ordered list of tuples;
  4620. # element[0] of the tuple is the diameter and
  4621. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  4622. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  4623. current_tool = 0
  4624. for tool_dia in ordered_edited_points:
  4625. current_tool += 1
  4626. # create the self.tools for the new Excellon object (the one with edited content)
  4627. name = str(current_tool)
  4628. spec = {"C": float(tool_dia[0])}
  4629. self.new_tools[name] = spec
  4630. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  4631. self.new_tools[name]['solid_geometry'] = []
  4632. # create the self.drills for the new Excellon object (the one with edited content)
  4633. for point in tool_dia[1]:
  4634. self.new_drills.append(
  4635. {
  4636. 'point': Point(point),
  4637. 'tool': str(current_tool)
  4638. }
  4639. )
  4640. # repopulate the 'solid_geometry' for each tool
  4641. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  4642. self.new_tools[name]['solid_geometry'].append(poly)
  4643. if self.is_modified is True:
  4644. if "_edit" in self.edited_obj_name:
  4645. try:
  4646. id = int(self.edited_obj_name[-1]) + 1
  4647. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  4648. except ValueError:
  4649. self.edited_obj_name += "_1"
  4650. else:
  4651. self.edited_obj_name += "_edit"
  4652. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  4653. 'params': [self.edited_obj_name]})
  4654. if self.exc_obj.slots:
  4655. self.new_slots = self.exc_obj.slots
  4656. self.new_tool_offset = self.exc_obj.tool_offset
  4657. # reset the tool table
  4658. self.tools_table_exc.clear()
  4659. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  4660. self.last_tool_selected = None
  4661. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  4662. self.app.collection.set_active(self.exc_obj.options['name'])
  4663. self.app.collection.delete_active()
  4664. # restore GUI to the Selected TAB
  4665. # Remove anything else in the GUI
  4666. self.app.ui.tool_scroll_area.takeWidget()
  4667. # Switch notebook to Selected page
  4668. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4669. def update_options(self, obj):
  4670. try:
  4671. if not obj.options:
  4672. obj.options = {}
  4673. obj.options['xmin'] = 0
  4674. obj.options['ymin'] = 0
  4675. obj.options['xmax'] = 0
  4676. obj.options['ymax'] = 0
  4677. return True
  4678. else:
  4679. return False
  4680. except AttributeError:
  4681. obj.options = {}
  4682. return True
  4683. def new_edited_excellon(self, outname):
  4684. """
  4685. Creates a new Excellon object for the edited Excellon. Thread-safe.
  4686. :param outname: Name of the resulting object. None causes the
  4687. name to be that of the file.
  4688. :type outname: str
  4689. :return: None
  4690. """
  4691. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  4692. self.exc_obj.options['name'])
  4693. # How the object should be initialized
  4694. def obj_init(excellon_obj, app_obj):
  4695. # self.progress.emit(20)
  4696. excellon_obj.drills = self.new_drills
  4697. excellon_obj.tools = self.new_tools
  4698. excellon_obj.slots = self.new_slots
  4699. excellon_obj.tool_offset = self.new_tool_offset
  4700. excellon_obj.options['name'] = outname
  4701. try:
  4702. excellon_obj.create_geometry()
  4703. except KeyError:
  4704. self.app.inform.emit(
  4705. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  4706. )
  4707. except:
  4708. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  4709. msg += traceback.format_exc()
  4710. app_obj.inform.emit(msg)
  4711. raise
  4712. # raise
  4713. with self.app.proc_container.new(_("Creating Excellon.")):
  4714. try:
  4715. self.app.new_object("excellon", outname, obj_init)
  4716. except Exception as e:
  4717. log.error("Error on object creation: %s" % str(e))
  4718. self.app.progress.emit(100)
  4719. return
  4720. self.app.inform.emit(_("[success]Excellon editing finished."))
  4721. # self.progress.emit(100)
  4722. def on_tool_select(self, tool):
  4723. """
  4724. Behavior of the toolbar. Tool initialization.
  4725. :rtype : None
  4726. """
  4727. current_tool = tool
  4728. self.app.log.debug("on_tool_select('%s')" % tool)
  4729. if self.last_tool_selected is None and current_tool is not 'select':
  4730. # self.draw_app.select_tool('select')
  4731. self.complete = True
  4732. current_tool = 'select'
  4733. self.app.inform.emit(_("[WARNING_NOTCL]Cancelled. There is no Tool/Drill selected"))
  4734. # This is to make the group behave as radio group
  4735. if current_tool in self.tools_exc:
  4736. if self.tools_exc[current_tool]["button"].isChecked():
  4737. self.app.log.debug("%s is checked." % current_tool)
  4738. for t in self.tools_exc:
  4739. if t != current_tool:
  4740. self.tools_exc[t]["button"].setChecked(False)
  4741. # this is where the Editor toolbar classes (button's) are instantiated
  4742. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  4743. # self.app.inform.emit(self.active_tool.start_msg)
  4744. else:
  4745. self.app.log.debug("%s is NOT checked." % current_tool)
  4746. for t in self.tools_exc:
  4747. self.tools_exc[t]["button"].setChecked(False)
  4748. self.active_tool = None
  4749. def on_row_selected(self):
  4750. self.selected = []
  4751. try:
  4752. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  4753. self.last_tool_selected = self.tools_table_exc.currentRow() + 1
  4754. for obj in self.storage_dict[selected_dia].get_objects():
  4755. self.selected.append(obj)
  4756. except Exception as e:
  4757. self.app.log.debug(str(e))
  4758. self.replot()
  4759. def toolbar_tool_toggle(self, key):
  4760. self.options[key] = self.sender().isChecked()
  4761. if self.options[key] == True:
  4762. return 1
  4763. else:
  4764. return 0
  4765. def on_canvas_click(self, event):
  4766. """
  4767. event.x and .y have canvas coordinates
  4768. event.xdaya and .ydata have plot coordinates
  4769. :param event: Event object dispatched by Matplotlib
  4770. :return: None
  4771. """
  4772. if event.button is 1:
  4773. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4774. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  4775. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4776. ### Snap coordinates
  4777. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  4778. self.pos = (x, y)
  4779. # print(self.active_tool)
  4780. # Selection with left mouse button
  4781. if self.active_tool is not None and event.button is 1:
  4782. # Dispatch event to active_tool
  4783. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4784. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  4785. # If it is a shape generating tool
  4786. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  4787. if self.current_storage is not None:
  4788. self.on_exc_shape_complete(self.current_storage)
  4789. self.build_ui()
  4790. # MS: always return to the Select Tool if modifier key is not pressed
  4791. # else return to the current tool
  4792. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4793. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  4794. modifier_to_use = Qt.ControlModifier
  4795. else:
  4796. modifier_to_use = Qt.ShiftModifier
  4797. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  4798. # in the selected list, we removed it. Therefore first click selects, second deselects.
  4799. if key_modifier == modifier_to_use:
  4800. self.select_tool(self.active_tool.name)
  4801. else:
  4802. self.select_tool("select")
  4803. return
  4804. if isinstance(self.active_tool, FCDrillSelect):
  4805. # self.app.log.debug("Replotting after click.")
  4806. self.replot()
  4807. else:
  4808. self.app.log.debug("No active tool to respond to click!")
  4809. def on_exc_shape_complete(self, storage):
  4810. self.app.log.debug("on_shape_complete()")
  4811. # Add shape
  4812. if type(storage) is list:
  4813. for item_storage in storage:
  4814. self.add_exc_shape(self.active_tool.geometry, item_storage)
  4815. else:
  4816. self.add_exc_shape(self.active_tool.geometry, storage)
  4817. # Remove any utility shapes
  4818. self.delete_utility_geometry()
  4819. self.tool_shape.clear(update=True)
  4820. # Replot and reset tool.
  4821. self.replot()
  4822. # self.active_tool = type(self.active_tool)(self)
  4823. def add_exc_shape(self, shape, storage):
  4824. """
  4825. Adds a shape to the shape storage.
  4826. :param shape: Shape to be added.
  4827. :type shape: DrawToolShape
  4828. :return: None
  4829. """
  4830. # List of DrawToolShape?
  4831. if isinstance(shape, list):
  4832. for subshape in shape:
  4833. self.add_exc_shape(subshape, storage)
  4834. return
  4835. assert isinstance(shape, DrawToolShape), \
  4836. "Expected a DrawToolShape, got %s" % str(type(shape))
  4837. assert shape.geo is not None, \
  4838. "Shape object has empty geometry (None)"
  4839. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4840. not isinstance(shape.geo, list), \
  4841. "Shape objects has empty geometry ([])"
  4842. if isinstance(shape, DrawToolUtilityShape):
  4843. self.utility.append(shape)
  4844. else:
  4845. storage.insert(shape) # TODO: Check performance
  4846. def add_shape(self, shape):
  4847. """
  4848. Adds a shape to the shape storage.
  4849. :param shape: Shape to be added.
  4850. :type shape: DrawToolShape
  4851. :return: None
  4852. """
  4853. # List of DrawToolShape?
  4854. if isinstance(shape, list):
  4855. for subshape in shape:
  4856. self.add_shape(subshape)
  4857. return
  4858. assert isinstance(shape, DrawToolShape), \
  4859. "Expected a DrawToolShape, got %s" % type(shape)
  4860. assert shape.geo is not None, \
  4861. "Shape object has empty geometry (None)"
  4862. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4863. not isinstance(shape.geo, list), \
  4864. "Shape objects has empty geometry ([])"
  4865. if isinstance(shape, DrawToolUtilityShape):
  4866. self.utility.append(shape)
  4867. else:
  4868. self.storage.insert(shape) # TODO: Check performance
  4869. def on_canvas_click_release(self, event):
  4870. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  4871. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  4872. if self.app.grid_status():
  4873. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4874. else:
  4875. pos = (pos_canvas[0], pos_canvas[1])
  4876. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4877. # canvas menu
  4878. try:
  4879. if event.button == 2: # right click
  4880. if self.app.panning_action is True:
  4881. self.app.panning_action = False
  4882. else:
  4883. self.app.cursor = QtGui.QCursor()
  4884. self.app.ui.popMenu.popup(self.app.cursor.pos())
  4885. except Exception as e:
  4886. log.warning("Error: %s" % str(e))
  4887. raise
  4888. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4889. # selection and then select a type of selection ("enclosing" or "touching")
  4890. try:
  4891. if event.button == 1: # left click
  4892. if self.app.selection_type is not None:
  4893. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  4894. self.app.selection_type = None
  4895. elif isinstance(self.active_tool, FCDrillSelect):
  4896. # Dispatch event to active_tool
  4897. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4898. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  4899. # self.app.inform.emit(msg)
  4900. self.active_tool.click_release((self.pos[0], self.pos[1]))
  4901. self.replot()
  4902. except Exception as e:
  4903. log.warning("Error: %s" % str(e))
  4904. raise
  4905. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  4906. """
  4907. :param start_pos: mouse position when the selection LMB click was done
  4908. :param end_pos: mouse position when the left mouse button is released
  4909. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4910. :type Bool
  4911. :return:
  4912. """
  4913. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4914. self.app.delete_selection_shape()
  4915. for storage in self.storage_dict:
  4916. for obj in self.storage_dict[storage].get_objects():
  4917. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  4918. (sel_type is False and poly_selection.intersects(obj.geo)):
  4919. if self.key == self.app.defaults["global_mselect_key"]:
  4920. if obj in self.selected:
  4921. self.selected.remove(obj)
  4922. else:
  4923. # add the object to the selected shapes
  4924. self.selected.append(obj)
  4925. else:
  4926. self.selected.append(obj)
  4927. # select the diameter of the selected shape in the tool table
  4928. for storage in self.storage_dict:
  4929. for shape_s in self.selected:
  4930. if shape_s in self.storage_dict[storage].get_objects():
  4931. for key in self.tool2tooldia:
  4932. if self.tool2tooldia[key] == storage:
  4933. item = self.tools_table_exc.item((key - 1), 1)
  4934. self.tools_table_exc.setCurrentItem(item)
  4935. self.last_tool_selected = key
  4936. # item.setSelected(True)
  4937. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  4938. self.replot()
  4939. def on_canvas_move(self, event):
  4940. """
  4941. Called on 'mouse_move' event
  4942. event.pos have canvas screen coordinates
  4943. :param event: Event object dispatched by VisPy SceneCavas
  4944. :return: None
  4945. """
  4946. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4947. event.xdata, event.ydata = pos[0], pos[1]
  4948. self.x = event.xdata
  4949. self.y = event.ydata
  4950. # Prevent updates on pan
  4951. # if len(event.buttons) > 0:
  4952. # return
  4953. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4954. if event.button == 2:
  4955. self.app.panning_action = True
  4956. return
  4957. else:
  4958. self.app.panning_action = False
  4959. try:
  4960. x = float(event.xdata)
  4961. y = float(event.ydata)
  4962. except TypeError:
  4963. return
  4964. if self.active_tool is None:
  4965. return
  4966. ### Snap coordinates
  4967. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  4968. self.snap_x = x
  4969. self.snap_y = y
  4970. # update the position label in the infobar since the APP mouse event handlers are disconnected
  4971. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4972. "<b>Y</b>: %.4f" % (x, y))
  4973. if self.pos is None:
  4974. self.pos = (0, 0)
  4975. dx = x - self.pos[0]
  4976. dy = y - self.pos[1]
  4977. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  4978. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4979. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4980. ### Utility geometry (animated)
  4981. geo = self.active_tool.utility_geometry(data=(x, y))
  4982. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  4983. # Remove any previous utility shape
  4984. self.tool_shape.clear(update=True)
  4985. self.draw_utility_geometry(geo=geo)
  4986. ### Selection area on canvas section ###
  4987. dx = pos[0] - self.pos[0]
  4988. if event.is_dragging == 1 and event.button == 1:
  4989. self.app.delete_selection_shape()
  4990. if dx < 0:
  4991. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  4992. color=self.app.defaults["global_alt_sel_line"],
  4993. face_color=self.app.defaults['global_alt_sel_fill'])
  4994. self.app.selection_type = False
  4995. else:
  4996. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  4997. self.app.selection_type = True
  4998. else:
  4999. self.app.selection_type = None
  5000. # Update cursor
  5001. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  5002. def on_canvas_key_release(self, event):
  5003. self.key = None
  5004. def draw_utility_geometry(self, geo):
  5005. # Add the new utility shape
  5006. try:
  5007. # this case is for the Font Parse
  5008. for el in list(geo.geo):
  5009. if type(el) == MultiPolygon:
  5010. for poly in el:
  5011. self.tool_shape.add(
  5012. shape=poly,
  5013. color=(self.app.defaults["global_draw_color"] + '80'),
  5014. update=False,
  5015. layer=0,
  5016. tolerance=None
  5017. )
  5018. elif type(el) == MultiLineString:
  5019. for linestring in el:
  5020. self.tool_shape.add(
  5021. shape=linestring,
  5022. color=(self.app.defaults["global_draw_color"] + '80'),
  5023. update=False,
  5024. layer=0,
  5025. tolerance=None
  5026. )
  5027. else:
  5028. self.tool_shape.add(
  5029. shape=el,
  5030. color=(self.app.defaults["global_draw_color"] + '80'),
  5031. update=False,
  5032. layer=0,
  5033. tolerance=None
  5034. )
  5035. except TypeError:
  5036. self.tool_shape.add(
  5037. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  5038. update=False, layer=0, tolerance=None)
  5039. self.tool_shape.redraw()
  5040. def replot(self):
  5041. self.plot_all()
  5042. def plot_all(self):
  5043. """
  5044. Plots all shapes in the editor.
  5045. :return: None
  5046. :rtype: None
  5047. """
  5048. # self.app.log.debug("plot_all()")
  5049. self.shapes.clear(update=True)
  5050. for storage in self.storage_dict:
  5051. for shape_plus in self.storage_dict[storage].get_objects():
  5052. if shape_plus.geo is None:
  5053. continue
  5054. if shape_plus in self.selected:
  5055. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  5056. linewidth=2)
  5057. continue
  5058. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  5059. # for shape in self.storage.get_objects():
  5060. # if shape.geo is None: # TODO: This shouldn't have happened
  5061. # continue
  5062. #
  5063. # if shape in self.selected:
  5064. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  5065. # continue
  5066. #
  5067. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  5068. for shape in self.utility:
  5069. self.plot_shape(geometry=shape.geo, linewidth=1)
  5070. continue
  5071. self.shapes.redraw()
  5072. def plot_shape(self, geometry=None, color='black', linewidth=1):
  5073. """
  5074. Plots a geometric object or list of objects without rendering. Plotted objects
  5075. are returned as a list. This allows for efficient/animated rendering.
  5076. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  5077. :param color: Shape color
  5078. :param linewidth: Width of lines in # of pixels.
  5079. :return: List of plotted elements.
  5080. """
  5081. plot_elements = []
  5082. if geometry is None:
  5083. geometry = self.active_tool.geometry
  5084. try:
  5085. for geo in geometry:
  5086. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  5087. ## Non-iterable
  5088. except TypeError:
  5089. ## DrawToolShape
  5090. if isinstance(geometry, DrawToolShape):
  5091. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  5092. ## Polygon: Descend into exterior and each interior.
  5093. if type(geometry) == Polygon:
  5094. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  5095. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  5096. if type(geometry) == LineString or type(geometry) == LinearRing:
  5097. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  5098. if type(geometry) == Point:
  5099. pass
  5100. return plot_elements
  5101. def on_shape_complete(self):
  5102. self.app.log.debug("on_shape_complete()")
  5103. # Add shape
  5104. self.add_shape(self.active_tool.geometry)
  5105. # Remove any utility shapes
  5106. self.delete_utility_geometry()
  5107. self.tool_shape.clear(update=True)
  5108. # Replot and reset tool.
  5109. self.replot()
  5110. # self.active_tool = type(self.active_tool)(self)
  5111. def get_selected(self):
  5112. """
  5113. Returns list of shapes that are selected in the editor.
  5114. :return: List of shapes.
  5115. """
  5116. # return [shape for shape in self.shape_buffer if shape["selected"]]
  5117. return self.selected
  5118. def delete_selected(self):
  5119. temp_ref = [s for s in self.selected]
  5120. for shape_sel in temp_ref:
  5121. self.delete_shape(shape_sel)
  5122. self.selected = []
  5123. self.build_ui()
  5124. self.app.inform.emit(_("[success]Done. Drill(s) deleted."))
  5125. def delete_shape(self, shape):
  5126. self.is_modified = True
  5127. if shape in self.utility:
  5128. self.utility.remove(shape)
  5129. return
  5130. for storage in self.storage_dict:
  5131. # try:
  5132. # self.storage_dict[storage].remove(shape)
  5133. # except:
  5134. # pass
  5135. if shape in self.storage_dict[storage].get_objects():
  5136. self.storage_dict[storage].remove(shape)
  5137. # a hack to make the tool_table display less drills per diameter
  5138. # self.points_edit it's only useful first time when we load the data into the storage
  5139. # but is still used as referecen when building tool_table in self.build_ui()
  5140. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  5141. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  5142. del self.points_edit[storage][0]
  5143. if shape in self.selected:
  5144. self.selected.remove(shape) # TODO: Check performance
  5145. def delete_utility_geometry(self):
  5146. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  5147. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  5148. for_deletion = [shape for shape in self.utility]
  5149. for shape in for_deletion:
  5150. self.delete_shape(shape)
  5151. self.tool_shape.clear(update=True)
  5152. self.tool_shape.redraw()
  5153. def on_delete_btn(self):
  5154. self.delete_selected()
  5155. self.replot()
  5156. def select_tool(self, toolname):
  5157. """
  5158. Selects a drawing tool. Impacts the object and GUI.
  5159. :param toolname: Name of the tool.
  5160. :return: None
  5161. """
  5162. self.tools_exc[toolname]["button"].setChecked(True)
  5163. self.on_tool_select(toolname)
  5164. def set_selected(self, shape):
  5165. # Remove and add to the end.
  5166. if shape in self.selected:
  5167. self.selected.remove(shape)
  5168. self.selected.append(shape)
  5169. def set_unselected(self, shape):
  5170. if shape in self.selected:
  5171. self.selected.remove(shape)
  5172. def on_array_type_combo(self):
  5173. if self.array_type_combo.currentIndex() == 0:
  5174. self.array_circular_frame.hide()
  5175. self.array_linear_frame.show()
  5176. else:
  5177. self.delete_utility_geometry()
  5178. self.array_circular_frame.show()
  5179. self.array_linear_frame.hide()
  5180. self.app.inform.emit(_("Click on the circular array Center position"))
  5181. def on_linear_angle_radio(self):
  5182. val = self.drill_axis_radio.get_value()
  5183. if val == 'A':
  5184. self.linear_angle_spinner.show()
  5185. self.linear_angle_label.show()
  5186. else:
  5187. self.linear_angle_spinner.hide()
  5188. self.linear_angle_label.hide()
  5189. def exc_add_drill(self):
  5190. self.select_tool('add')
  5191. return
  5192. def exc_add_drill_array(self):
  5193. self.select_tool('add_array')
  5194. return
  5195. def exc_resize_drills(self):
  5196. self.select_tool('resize')
  5197. return
  5198. def exc_copy_drills(self):
  5199. self.select_tool('copy')
  5200. return
  5201. def exc_move_drills(self):
  5202. self.select_tool('move')
  5203. return
  5204. def distance(pt1, pt2):
  5205. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  5206. def mag(vec):
  5207. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  5208. def poly2rings(poly):
  5209. return [poly.exterior] + [interior for interior in poly.interiors]